Update: I deleted the .dat file where everything is saved and now it works again. I would like some input on what might have caused it anything will help. I just want to know how to prevent it in the future.
Everything work perfectly yesterday using python idle.
Today I edited my program in pycharm to add a delete account feature. Everything runs on pycharm I can receive accounts, delete accounts, and create them. I decided to test it on idle because most computers I work on I can't download pycharm and I keep getting this error:
Traceback (most recent call last):
File "E:\Passwords\password.py", line 140, in ?
program_start()
File "E:\Passwords\password.py", line 137, in program_start
all_accounts()
File "E:\Passwords\password.py", line 93, in all_accounts
klist = f.keys()
File "C:\Python24\lib\shelve.py", line 98, in keys
return self.dict.keys()
File "C:\Python24\lib\bsddb\__init__.py", line 244, in keys
return self.db.keys()
DBRunRecoveryError: (-30978, 'DB_RUNRECOVERY: Fatal error, run database recovery -- accounts.dat: pgin failed for page 1')
I decided to run on pycharm again and against all odds it still ran perfectly no errors. What does this error mean? How can I fix it? And what causes it?
Also I have tried to run it on multiple computers to see if python idle would run it and none of them would.
Did the delete function ruin it?
def delete_account():
"""Deletes an account"""
print'\n'
account = raw_input("What account do you want to delete?: ")
f = shelve.open("accounts.dat")
if account in f:
confirm_deletion = raw_input("Are you sure you want to delete " + account + "?: ")
if confirm_deletion.lower() in ('yes', 'y'):
del f[account]
print "This account has been deleted."
else:
print "Canceled... "
else:
print "I'm sorry we could not find any account related to " + account
print '\n'
f.close
Or did pycharm cause this error?
Check your python version
It could be pycharm is using a different version of python as compared to the idle you have installed.
Related
I am currently working with the Instabot API for python and I ran across the following issue:
I wrote a small program:
from instabot import Bot
bot = Bot()
bot.login(username = "[my username]", password = "[my passowrd]")
bot.follow("lego")
which worked fine after running it for the very first time. However, after running the program for a second time, this time following another account, it raised an error ("KeyError: ds_user").
This error can be fixed by deleting the config folder inside the project folder. Unfortunately, this isn't a very sustainable solution, as it makes working on the code really arduous. I therefore would like to know if there is any solution for getting the program to run multiple times without having to delete the config folder over and over again.
I am receiving the following traceback (code is running in an anaconda environment called "Instagram Automation"):
Traceback (most recent call last):
File "e:/Programme/OneDrive/Dokumente/Projekte/Instagram Automation/main.py", line 4, in <module>
bot.login(username = "[my username]", password = "[my password]")
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\bot\bot.py", line 443, in login
if self.api.login(**args) is False:
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api.py", line 240, in login
self.load_uuid_and_cookie(load_cookie=use_cookie, load_uuid=use_uuid)
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api.py", line 199, in load_uuid_and_cookie
return load_uuid_and_cookie(self, load_uuid=load_uuid, load_cookie=load_cookie)
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api_login.py", line 352, in load_uuid_and_cookie
cookie_username = self.cookie_dict["ds_user"]
KeyError: 'ds_user'
As far as I can see, the only way on your side to fight the symptoms is to always delete the JSON file in the config folder, e.g:
import os
if os.path.isfile("path/to/config/file.json"):
os.remove("path/to/config/file.json")
import instabot
# rest of your code goes here
The developers of instabot should fix the source of the problem, for example by using self.cookie_dict.get("ds_user", "some default value") instead of self.cookie_dict["ds_user"]
I am trying to return the current_time or current_time +1 in a func, where I am using the win10toast. My code was working fine before, it just suddenly stopped working. I didn't do anything or change any settings. When running the following code:
from datetime import datetime, timedelta
from win10toast import ToastNotifier
toast = ToastNotifier()
def At_Time():
global Input_time, Ahead_time
At_time = datetime.now()
Ahead_time = (At_time + timedelta(minutes=1))
if timedelta(seconds=At_time.second) < timedelta(seconds=30):
L = 'Less Than 30 secs... Not changing Current_time'
infoL = str('Current Time: ' + At_time.strftime("%H:%M:%S") + '\n' + "Input Time: " + At_time.strftime("%H:%M:%S"))
toast.show_toast(title=L, msg=infoL, duration=7, threaded= True)
Input_time = At_time.strftime("%H:%M")
return Input_time
else:
M = 'More than 30 secs... Adding 1 Min to Current_time'
infoM = str("Current Time: " + At_time.strftime("%H:%M:%S") + '\n' + "Input Time: " + Ahead_time.strftime("%H:%M:%S"))
toast.show_toast(title=M, msg=infoM, duration=7, threaded= True)
Input_time = Ahead_time.strftime("%H:%M")
# meeting_row = Row
return Input_time
At_Time()
When running this, I am now getting the following Error :
`Traceback (most recent call last):
File "C:\Program Files\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run()
File "C:\Program Files\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python39\lib\site-packages\win10toast\__init__.py", line 106, in
show_toast Shell_NotifyIcon(NIM_ADD, nid)
pywintypes.error: (-2147467259, 'Shell_NotifyIcon', 'Unspecified error')`
Specifically speaking, This is the Error :
pywintypes.error: (-2147467259, 'Shell_NotifyIcon', 'Unspecified error')
I could not find this issue reported anywhere except one https://stackoverflow.com/a/65224994/15136959, where the solution said to use
icon_path= None
This is not going to work as it is already the default value of parameter. I assume the error is associated with the Shell_NotifyIcon(NIM_ADD, nid) , or an Win API Error. This bug/issue is nowhere else mentioned. Can I get reason for this Error, or a fix directly ?
Thanks for the help and your valuable time...
EDIT: This Error got fixed after a Restart. Also during the Restart, Windows got an
"Updating Windows, Do Not Turn Off PC"
, even though I paused the Windows Updates. But still, someone got a permanent fix or even a reason why this occurred, So as to avoid any future issues by other users ??
Lastly, Can a Genius explain.. How can we show multiple notifications by win10toast at the same time, without the Registered Class Error ? ( Optional )
I can't reproduce your problem with this code, but a similar problem appears in this thread, I think it is caused by the python script triggering win10toast at the same time. Then, you can refer to: Stopping all automatic updates Windows 10 to stop Win10 Update automatically.
Then, you can refer to: Stopping all automatic updates Windows 10 to stop Win10 Update automatically. to stop Win10 Update automatically.
Finally, you cannot display multiple notifications at the same time. While one notification is active the second one won't be triggered. If needed you can reduce the duration of the first toast. Setting the duration of first toast as 3 seconds and this would work fine.
Regarding whether multiple notifications will be displayed at the same time in the future, Microsoft has not made it clear at present, and it does not seem to be added in the future.I think you can report the demand to Microsoft.
I want to search a Perforce depot for files.
I do this from a python script and use the p4python library command:
list = p4.run("files", "//mypath/myfolder/*")
This works fine as long as myfolder contains some files. I get a python list as a return value. But when there is no file in myfolder the program stops running and no error message is displayed. My goal is to get an empty python list, so that I can see that this folder doesn't contain any files.
Does anybody has some ideas? I could not find information in the p4 files documentation and on StackOverflow.
I'm going to guess you've got an exception handler around that command execution that's eating the exception and exiting. I wrote a very simple test script and got this:
C:\Perforce\test>C:\users\samwise\AppData\local\programs\python\Python36-32\python files.py
Traceback (most recent call last):
File "files.py", line 6, in <module>
print(p4.run("files", "//depot/no such path/*"))
File "C:\users\samwise\AppData\local\programs\python\Python36-32\lib\site-packages\P4.py", line 611, in run
raise e
File "C:\users\samwise\AppData\local\programs\python\Python36-32\lib\site-packages\P4.py", line 605, in run
result = P4API.P4Adapter.run(self, *flatArgs)
P4.P4Exception: [P4#run] Errors during command execution( "p4 files //depot/no such path/*" )
[Error]: "//depot/no such path/* - must refer to client 'Samwise-dvcs-1509687817'."
Try something like this ?
import os
if len(os.listdir('//mypath/myfolder/') ) == 0: # Do not execute p4.run if directory is empty
list = []
else:
list = p4.run("files", "//mypath/myfolder/*")
I'm currently completing an assignment which requires me to create a script to crack a password from a PDF file, I already have a list which contains the password within, I am having issues when prompt to enter the path to the file and met with an Name not define error, please mind I am a novice to coding.
file = raw_input('Path: ')
wordlist = 'wordlist.txt'
word =open(wordlist, 'r')
allpass = word.readlines()
word.close()
for password in allpass:
password = password.strip()
print ("Testing password: "+password)
instance = dispatch('pdf.Application')
try:
instance.Workbooks.Open(file, False, True, None, password)
print ("Password Cracked: "+password)
break
except:
pass
When the program is running, it attempts the first password from the list then proceeds to crash.
python Comsec.py
Path: /home/hall/Desktop/comsec121/examAnswers.pdf
Testing password: 123456
Traceback (most recent call last):
File "Comsec.py", line 11, in <module>
instance = dispatch('pdf.Application')
NameError: name 'dispatch' is not defined
Please excuse my formatting on this website, I am trying my best to help you understand my issue!
Thanks in advance!
This error means that inside your Python script there is no object or function with the name dispatch. You would get that same error if you tried:
instance = this_is_a_function_that_has_not_been_defined('pdf.Application')
Typically, this function should be defined in a Python module. To access it, at the top of your code you should have some import statement like this:
from aBeautifulModuleForPDFs import dispatch
That module will be providing you the missing dispatch function. Checking in Google, I suggest you to try with module pywin32. Install it (run pip install pywin32 in a terminal) and add this line at the beginning of the code:
from win32com.client import Dispatch as dispatch
I'm teaching myself how to Python3. I wanted to train my acquired skills and write a command-line backup program. I'm trying to save the default backup and save locations with the Shelve module but it seems that it keeps forgetting the variables I save whenever I close or restart the program.
Here is the main function that works with the shelves:
def WorkShelf(key, mode='get', variable=None):
"""Either stores a variable to the shelf or gets one from it.
Possible modes are 'store' and 'get'"""
config = shelve.open('Config')
if mode.strip() == 'get':
print(config[key])
return config[key]
elif mode.strip() == 'store':
config[key] = variable
print(key,'holds',variable)
else:
print("mode has not been reconginzed. Possible modes:\n\t- 'get'\n\t-'store'")
config.close()
So, whenever I call this function to store variables and call the function just after that, it works perfectly. I tried to access the shelf manually and everything is there.
This is the code used to store the variables:
WorkShelf('BackUpPath','store', bupath)
WorkShelf('Path2BU', 'store', path)
The problem comes when I try to get my variables from the shelf after restarting the script. This code:
config = shelve.open('Config')
path = config['Path2BU']
bupath = config['BackUpPath']
Gives me this error:
Traceback (most recent call last):
File "C:\Python35-32\lib\shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Path2BU'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
config['Path2BU']
File "C:\Python35-32\lib\shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "C:\Python35-32\lib\dbm\dumb.py", line 141, in __getitem__
pos, siz = self._index[key] # may raise KeyError
KeyError: b'Path2BU
Basically, this is an error I could reproduce by calling ShelveObject['ThisKeyDoesNotExist'].
I am really lost right now. When I try to manually create a shelf, close it and access it again it seems to work (even though I got an error doing that before) now. I've read every post concerning this, I thought about shelf corruption (but it's not likely it happens every time), and I've read my script A to Z around 20 times now.
Thanks for any help (and I hope I asked my question the right way this time)!
EDIT
Okay so this is making me crazy. Isolating WorkShelf() does work perfectly, like so:
import shelve
def WorkShelf(key, mode='get', variable=None):
"""Either stores a variable to the shelf or gets one from it.
Possible modes are 'store' and 'get'"""
config = shelve.open('Config')
if mode.strip() == 'get':
print(config[key])
return config[key]
elif mode.strip() == 'store':
config[key] = variable
print(key,'holds',variable)
else:
print("mode has not been reconginzed. Possible modes:\n\t- 'get'\n\t-'store'")
config.close()
if False:
print('Enter path n1: ')
path1 = input("> ")
WorkShelf('Path1', 'store', path1)
print ('Enter path n2: ')
path2 = input("> ")
WorkShelf('Path2', 'store', path2)
else:
path1, path2 = WorkShelf('Path1'), WorkShelf('Path2')
print (path1, path2)
No problem, perfect.
But when I use the same function in my script, I get this output. It basically tells me it does write the variables to the shelve files ('This key holds this variable' message). I can even call them with the same code I use when restarting. But when calling them after a program reset it's all like 'What are you talking about m8? I never saved these'.
Welcome to this backup manager.
We will walk you around creating your backup and backup preferences
What directory would you like to backup?
Enter path here: W:\Users\Damien\Documents\Code\Code Pyth
Would you like to se all folders and files at that path? (enter YES|NO)
> n
Okay, let's proceed.
Where would you like to create your backup?
Enter path here: N:\
Something already exists there:
19 folders and 254 documents
Would you like to change your location?
> n
Would you like to save this destination (N:\) as your default backup location ? That way you don't have to type it again.
> y
BackUpPath holds N:\
If you're going to be backing the same data up we can save the files location W:\Users\Damien\Documents\Code\Code Pyth so you don't have to type all the paths again.
Would you like me to remember the backup file's location?
> y
Path2BU holds W:\Users\Damien\Documents\Code\Code Pyth
>>>
======== RESTART: W:\Users\Damien\Documents\Code\Code Pyth\Backup.py ========
Welcome to this backup manager.
Traceback (most recent call last):
File "C:\Python35-32\lib\shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Path2BU'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "W:\Users\Damien\Documents\Code\Code Pyth\Backup.py", line 198, in <module>
path, bupath = WorkShelf('Path2BU'), WorkShelf('BackUpPath')
File "W:\Users\Damien\Documents\Code\Code Pyth\Backup.py", line 165, in WorkShelf
print(config[key])
File "C:\Python35-32\lib\shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "C:\Python35-32\lib\dbm\dumb.py", line 141, in __getitem__
pos, siz = self._index[key] # may raise KeyError
KeyError: b'Path2BU'
Please help, I'm going crazy and might develop a class to store and get variables from text files.
Okay so I just discovered what went wrong.
I had a os.chdir() in my setup code. Whenever Setup was done and I wanted to open my config files it would look in the current directory but the shelves were in the directory os.chdir() pointed to in the setup.
For some reason I ended up with empty shelves in the directory the actual ones were supposed to be. That cost me a day of debugging.
That's all for today folks!