Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I generated this error in Python 3.5:
Traceback (most recent call last):
File "C:\Users\Owner\AppData\Local\Programs\Python\Python35\lib\shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'P4_vegetables'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Owner\Documents\Python\Allotment\allotment.py", line 217, in
main_program()
File "C:\Users\Owner\Documents\Python\Allotment\allotment.py", line 195, in main_program
main_program()
File "C:\Users\Owner\Documents\Python\Allotment\allotment.py", line 49, in main_program
print("Plot 4 - ", s["P4_vegetables"])
File "C:\Users\Owner\AppData\Local\Programs\Python\Python35\lib\shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "C:\Users\Owner\AppData\Local\Programs\Python\Python35\lib\dbm\dumb.py", line 141, in __getitem__
pos, siz = self._index[key] # may raise KeyError
KeyError: b'P4_vegetables'
It has been a while, but in case somebody comes across this: The following error
Traceback (most recent call last):
File "filepath", line 111, in __getitem__
value = self.cache[key]
KeyError: 'item1'
can occur if one attempts to retrieve the item outside of the with block. The shelf is closed once we start executing code outside of the with block. Therefore, any operation performed on the shelf outside of the with block in which the shelf is opened will be considered an invalid operation. For example,
import shelve
with shelve.open('ShelfTest') as item:
item['item1'] = 'item 1'
item['item2'] = 'item 2'
item['item3'] = 'item 3'
item['item4'] = 'item 4'
print(item['item1']) # no error, since shelf file is still open
# If we try print after file is closed
# an error will be thrown
# This is quite common
print(item['item1']) #error. It has been closed, so you can't retrieve it.
Hope this helps anyone who comes across a similar issue as the original poster.
It means that the dictionary (or of whatever type it is) cache does not contain the key named key which is of value 'P4_vegetables'. Make sure you added the key before using it.
Related
I want to get all the node IP addresses of ETH, so I need to parse the geth/nodes directory, but I can't find the specific data format and cannot parse it.
I found a same problem, but there is no solution:
https://ethereum.stackexchange.com/questions/5999/format-of-leveldb-files-in-nodes-directory-trouble-pulling-contents-with-python
My code:
import leveldb
import rlp
db = leveldb.LevelDB("../nodes")
for k in db.RangeIter():
print(k)
print(rlp.decode(k[0]))
break
Result:
(bytearray(b'local:\xc6\x83\x00\xb8LX\xcc+\xcd\x98CDd\x96\x89R\x92\x1a\xaeV\xe1\x93\xfeV\x95)\t~$e\xfa|:seq'), bytearray(b'\x97\x08'))
Traceback (most recent call last):
File "temp.py", line 7, in <module>
print(rlp.decode(k[0]))
File "PATH/.local/lib/python3.6/site-packages/rlp/codec.py", line 235, in decode
raise DecodingError(msg, rlp)
rlp.exceptions.DecodingError: RLP string ends with 41 superfluous bytes
I searched a lot of information and found that rlp.sedes needs to be specified when decoding. I can't determine which kind of sedes it is. I am a newcomer to ETH and I need help. Examples of parsing in other programming languages are also available.
Thank you.
I am using ete3(http://etetoolkit.org/) package in Python within a bioinformatics pipeline I wrote myself.
While running this script, I get the following error. I have used this script a lot for other datasets which don't have any issues and have not given any errors. I am using Python3.5 and miniconda. Any fixes/insights to resolve this error will be appreciated.
[Error]
Traceback (most recent call last):
File "/Users/d/miniconda2/envs/py35/bin/ete3", line 11, in <module>
load_entry_point('ete3==3.1.1', 'console_scripts', 'ete3')()
File "/Users/d/miniconda2/envs/py35/lib/python3.5/site-packages/ete3/tools/ete.py", line 95, in main
_main(sys.argv)
File "/Users/d/miniconda2/envs/py35/lib/python3.5/site-packages/ete3/tools/ete.py", line 268, in _main
args.func(args)
File "/Users/d/miniconda2/envs/py35/lib/python3.5/site-packages/ete3/tools/ete_ncbiquery.py", line 168, in run
collapse_subspecies=args.collapse_subspecies)
File "/Users/d/miniconda2/envs/py35/lib/python3.5/site-packages/ete3/ncbi_taxonomy/ncbiquery.py", line 434, in get_topology
lineage = id2lineage[sp]
KeyError: 3
Continuing from the comment section for better formatting.
Assuming that the sp contains 3 as suggested by the error message (do check this yourself). You can inspect the ete3 code (current version) following its definition, you can trace it to line:
def get_lineage_translator(self, taxids):
"""Given a valid taxid number, return its corresponding lineage track as a
hierarchically sorted list of parent taxids.
So I went to https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi
and checked if 3 is valid taxid and it appears that it is not.
# relevant section from ncbi taxonomy browser
No result found in the Taxonomy database for taxonomy id
3
It appears to me that your only option is to trace how the 3 gets computed. Because the root cause is simply that taxid 3 is not valid taxid number as required by the function.
I wrote a program in Python 3 which scrapes and download the pages of wikipedia category with certain depth and places them in a directory.
The problem which I am facing is, "suppose during the execution of code, if the algorithm encounters any page of wikipedia having special character like (*, #, $ etc.), then the algorithm fails with the below mentioned message in terms of error trace ".
An example of the special character wiki page is as follows:
https://en.wikipedia.org/wiki/Eden*
The error trace is as follows:
Traceback (most recent call last):
File "F:\Pen Drive 8 GB\PDF\Code\wiki.py", line 103, in <module>
d.search_and_store("Biomedical_engineering", subcategory_depth=2, path=PATH)
File "F:\Pen Drive 8 GB\PDF\Code\wiki.py", line 98, in search_and_store
self.search_and_store(subcat_result['title'], subcategory_depth-1, path)
File "F:\Pen Drive 8 GB\PDF\Code\wiki.py", line 98, in search_and_store
self.search_and_store(subcat_result['title'], subcategory_depth-1, path)
File "F:\Pen Drive 8 GB\PDF\Code\wiki.py", line 76, in search_and_store
if self.write_page_text(path, page_result):
File "F:\Pen Drive 8 GB\PDF\Code\wiki.py", line 44, in write_page_text
txt_file = open(file_path, 'w')
OSError: [Errno 22] Invalid argument: 'F:\\Code\\Wikipedia\\DATASETS\\Biomedical Engineering/Eden*.txt'
As you can see clearly, the algorithm scrapes the data of the pages without having any special character's, but why it raising the aforementioned error.
The MWE is very large. If anybody suggests, then I can share the same.
Please suggest something, as I am trying this since long and frustrated. I don't even have idea what I am doing wrong? Please help.
Any small help is deeply appreciated.
Thanks in Advance.
I have code that sets up an environment for running and logging scientific experiments. Some of the initial setup involves using the built in input() method to query the user for values. I keep getting a I/O operation on closed file error whenever I try to call input however.
Code flow: Control.py calls Analyzer.py which calls a specific method in Prompts.py (the code for which is below).
def prompt_instruments(message):
res = input(message) # query user with arg message
print("done")
if '.' in res:
print("User input not cool. Use comma-separated values.")
return None # to continue prompting
...
I have searched all over the internet and have been unable to find anything remotely related. Thank you so much!!
The code you posted seems ok, and the error is probably in one of your other files.
The input() function uses sys.stdout to display the prompt text, and sys.stdin to get the user's input text.
The error message you get is probably caused by one of these files being closed, e.g.:
>>> import sys
>>> input('test: ')
test: hello
'hello'
>>> sys.stdin.close()
>>> input('test: ')
test: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
or:
>>> import sys
>>> input('test: ')
test: hi
'hi'
>>> sys.stdout.close()
>>> input('test: ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
I can't tell you exactly where to fix this issue, but look for things that might close one of these file, either directly or indirectly (e.g. context manager).
I try to get the custom json from my OpsWorks stacks with python and boto3. Getting the name is ok but if I want to get the CustomJson - KeyError. Don't have a clue why.
import boto3
import traceback
client = boto3.client('opsworks')
response = client.describe_stacks()
max_elements = len(response['Stacks'])
for i in range(max_elements):
stack_Name = response['Stacks'][i]['Name'] # works
try:
stack_CustomJson = response['Stacks'][i]['CustomJson'] # KeyError
except:
traceback.print_exc()
That's the console output:
$ python3 get_custom_json.py
Traceback (most recent call last):
File "get_custom_json.py", line 27, in get_opsworks_details
stack_CustomJson = response['Stacks'][i]['CustomJson']
KeyError: 'CustomJson'
Reading the docs from http://boto3.readthedocs.org/en/latest/reference/services/opsworks.html#OpsWorks.Client.describe_stacks I don't see a difference between 'Name' and 'CustomJson' except that CustomJson is a JSON object. Do I have to transform it?
Thx in advance
You are getting a KeyError occasionally because the CustomStack element in the response is optional. If a custom stack is specified for the stack, it will be returned. Otherwise, the CustomStack key will not be there at all. You should do something like:
if 'CustomStack' in stack:
# do your thing
Had a quick chat with a developer in my company. Got some basic introductions for getting better in coding and python and whatever (must loose some of my admin thinking).
Don't iterate about max_elements, better iterate above 'stack in stacks'.
for stack in response['Stacks']:
print(stack['CustomJson'])
Now it works - I'll get the custom json from the OpsWorks stacks. But still there is the KeyError.
Traceback (most recent call last):
File "get_custom_json.py", line 22, in <module>
get_opsworks_details()
File "get_custom_json.py", line 18, in get_opsworks_details
print(stack['CustomJson'])
KeyError: 'CustomJson'
I'll check if I can fetch him again to see why that's happening.
[EDIT] Blind spot - if a stack has no custom json then the KeyError will occur.