NameError: name 'savefile' is not defined - python-3.x

Here is my code, I'm having issues trying to get this to run. I keep getting a failure when trying to execute:
I am referencing this function the same way I am trying to reference this one? I'm not sure what's going on?
#### PARSING RESULTS
Traceback (most recent call last):
File "masscanner.py", line 49, in <module>
main()
File "masscanner.py", line 43, in main
file = write_file(savefile)
NameError: name 'savefile' is not defined
def write_file(savefile):
print('\n\n########## WRITING FILE ##########\n')
fh = open("endpointslist", "w")
for i in savefile:
fh.write(i[0])
fh.write('\n')
def main():
""" Main program """
results = find_endpoints()
ipportset = parse_results(results)
fh = write_file(savefile)
pprint(ipportset)
return 0
if __name__ == "__main__":
main()

Possible that its just a typo. Shouldn't it be write_file(ipportset). In the context, the variable savefile comes from nowhere and is therefore giving you the error NameError: name 'savefile' is not defined

Related

Executing SPARQL queries with the wikibaseintegrator package on a local Wikibase instance

I'm attempting to run a SPARQL query using the Python package wikibaseintegrator (version 0.10.0).
The program is written as follows:
from wikibaseintegrator.wbi_config import config as wbi_config
from wikibaseintegrator import wbi_login, wbi_core
wbi_config['MEDIAWIKI_API_URL'] = 'http://localhost/database_name/api.php'
wbi_config['SPARQL_ENDPOINT_URL'] = 'http://localhost:8989/database_name/sparql'
wbi_config['WIKIBASE_URL'] = 'http://wikibase.svc'
temp_username = "placeholder_username"
temp_password = "placeholder_password"
def main():
login_instance = login()
sparql_str = """
SELECT ?item ?itemLabel
WHERE
{
?item wdt:P98 wd:Q45.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
"""
sparql_results = run_sparql_query(sparql_str)
print(sparql_results)
def login(username=temp_username, password=temp_password):
login_instance = wbi_login.Login(user=username, pwd=password)
return login_instance
def run_sparql_query(sparql_str):
sparql_results = wbi_core.ItemsEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
return sparql_results
# MAIN
if __name__ == "__main__": main()
When I run this though, the error I get is:
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.ItemsEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: module 'wikibaseintegrator.wbi_core' has no attribute 'ItemsEngine'
However, the documentation (https://github.com/LeMyst/WikibaseIntegrator) seems to imply that this is the correct way to format the query. Any help in diagnosing would be much appreciated!
EDIT 1: The documentation says it's in the ItemEngine (The method wbi_core.ItemEngine.execute_sparql_query()), but the program itself seems to show it being in the FuctionsEngine
I have tried all of these variations, with the error being the same:
$ python database_script.py
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.FuctionsEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: module 'wikibaseintegrator.wbi_core' has no attribute 'FuctionsEngine'
$ python database_script.py
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.ItemEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: type object 'ItemEngine' has no attribute 'execute_sparql_query'
$ python database_script.py
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.FunctionEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: module 'wikibaseintegrator.wbi_core' has no attribute 'FunctionEngine'
EDIT 2: The larger issue seemed to be the lack of an install for the SPARQL service since I had gotten it running with WAMP64. I installed a Docker instance and it's been a decent amount easier out of the box (except the export of the WAMP64 version and import into the Docker instance).

Python Multiprocessing( TypeError: cannot serialize '_io.BufferedReader' object )

I'm trying to make dictionary attack on zip file using Pool to increase speed.
But I face next error in Python 3.6, while it works in Python 2.7:
Traceback (most recent call last):
File "zip_crack.py", line 42, in <module>
main()
File "zip_crack.py", line 28, in main
for result in results:
File "/usr/lib/python3.6/multiprocessing/pool.py", line 761, in next
raise value
File "/usr/lib/python3.6/multiprocessing/pool.py", line 450, in _ handle_tasks
put(task)
File "/usr/lib/python3.6/multiprocessing/connection.py", line 206, in send
self._send_bytes(_ForkingPickler.dumps(obj))
File "/usr/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: cannot serialize '_io.BufferedReader' object
I tried to search for same errors but couldn't find answer that can help here.
Code looks like this
def crack(pwd, f):
try:
key = pwd.strip()
f.extractall(pwd=key)
return True
except:
pass
z_file = zipfile.ZipFile("../folder.zip")
with open('words.dic', 'r') as passes:
start = time.time()
lines = passes.readlines()
pool = Pool(50)
results = pool.imap_unordered(partial(crack, f=z_file), lines)
pool.close()
for result in results:
if result:
pool.terminate()
break
pool.join()
I also tried another approach using map
with contextlib.closing(Pool(50)) as pool:
pool.map(partial(crack, f=z_file), lines)
which worked great and found passwords quickly in Python 2.7 but it throws same exception in python 3.6

Python cmd shell: handling undefined commands

I'm writing a shell that must be able to take an unlimited number of commands. I can't figure out from the docs (https://docs.python.org/3.6/library/cmd.html) which say:
Cmd.default(line) Method called on an input line when the command
prefix is not recognized. If this method is not overridden, it prints
an error message and returns.
I must be writing the default() method incorrectly?
I've tried this:
import cmd
class MyShell(cmd.Cmd):
def default():
print('you entered this unknown command: ')
if __name__ == '__main__':
MyShell().cmdloop()
but get this (when I enter 'hi' in the shell):
(Cmd) hi
Traceback (most recent call last):
File "/Users/david/anaconda/lib/python3.6/cmd.py", line 214, in onecmd
func = getattr(self, 'do_' + cmd)
AttributeError: 'MyShell' object has no attribute 'do_hi'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "bitmessage_shell.py", line 9, in <module>
MyShell().cmdloop()
File "/Users/david/anaconda/lib/python3.6/cmd.py", line 138, in cmdloop
stop = self.onecmd(line)
File "/Users/david/anaconda/lib/python3.6/cmd.py", line 216, in onecmd
return self.default(line)
TypeError: default() takes 0 positional arguments but 2 were given
def default():
print('you entered this unknown command: ')
that doesn't work in a class. You need at least the object argument (self), or make the method static/class using #staticmethod or #classmethod decorators (but not very convenient, you may need the object state at some point)
Moreover, the parent class seems to pass the line, so now you need 2 arguments:
def default(self,line):
print('you entered this unknown command: ',line)

Contradicting Errors?

So I'm trying to edit a csv file by writing to a temporary file and eventually replacing the original with the temp file. I'm going to have to edit the csv file multiple times so I need to be able to reference it. I've never used the NamedTemporaryFile command before and I'm running into a lot of difficulties. The most persistent problem I'm having is writing over the edited lines.
This part goes through and writes over rows unless specific values are in a specific column and then it just passes over.
I have this:
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, "rb") as oi, temp:
r = csv.reader(oi)
w = csv.writer(temp)
for row in r:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
w.writerow(row)
and I get this error:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 63, in cleanOfficeCol
for row in r:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
So I searched for that error and the general consensus was that "rb" needs to be "rt" so I tried that and got this error:
Traceback (most recent call last):
File "H:\jcatoe\Practice Python\pract.py", line 86, in <module>
cleanOfficeCol()
File "H:\jcatoe\Practice Python\pract.py", line 67, in cleanOfficeCol
w.writerow(row)
File "C:\Users\jcatoe\AppData\Local\Programs\Python\Python35-32\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'
I'm confused because the errors seem to be saying to do the opposite thing.
If you read the tempfile docs you'll see that by default it's opening the file in 'w+b' mode. If you take a closer look at your errors, you'll see that you're getting one on read, and one on write. What you need to be doing is making sure that you're opening your input and output file in the same mode.
You can do it like this:
import csv
import tempfile
office = 3
temp = tempfile.NamedTemporaryFile(delete=False)
with open(inFile, 'r') as oi, tempfile.NamedTemporaryFile(delete=False, mode='w') as temp:
reader = csv.reader(oi)
writer = csv.writer(temp)
for row in reader:
if row[office] == "R00" or row[office] == "ALC" or row[office] == "RMS":
pass
else:
writer.writerow(row)

Using threading.timer to delay sub-procedure

def emailCheck(self):
n=0
(retcode, messages) = mail.search(None, '(UNSEEN)')
if retcode == 'OK':
for num in messages[0].split() :
n=n+1
typ, data = mail.fetch(num,'(RFC822)')
for response_part in data:
if isinstance(response_part, tuple):
original = email.message_from_bytes(response_part[1])
print (original['From'])
print (original['Subject'])
typ, data = mail.store(num,'+FLAGS','\\Seen')
print (n)
t = threading.Timer(10.0, emailCheck)
t.start()
I am trying to delay the sub-procedure using threading.timer(), but I think the error is to do with the inclusion of self in the brackets. I am using PyQt so all of this is contained within the class MainWindow.
The error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python33\lib\threading.py", line 637, in _bootstrap_inner
self.run()
File "C:\Python33\lib\threading.py", line 823, in run
self.function(*self.args, **self.kwargs)
TypeError: emailCheck() missing 1 required positional argument: 'self'
t = threading.Timer(10.0, self.emailCheck)

Resources