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).
Related
this is my code
import requests
r = requests.get('https://www.reddit.com/r/Art.json').json()
print(r['data'])
this code sometimes work but sometimes get fail
Exception is
Traceback (most recent call last):
File "c:/Users/SAMET/Desktop/python/a.py", line 5, in <module>
print(r['data'])
KeyError: 'data'
You must use r.data. r['data'] could work in Javascript, but in Python you can't access objects as dictionaries.
Input function is only accepting integers as an input otherwise I receive this error message when I run using REPL in python 3:
Entry:
b
Traceback (most recent call last):
File "Ex7.5.py", line 1, in <module>
a = input("Entry:\n")
File "<string>", line 1, in <module>
NameError: name 'b' is not defined
Need my code to accept both letters and numbers as input and cant understand why it's not taking b as a string and printing it?
Literally just trying to get this print input function to work currently to then use later in other functions.
If I run the same code with integers only it works no problem.
a = input("Entry:\n")
print(a)
print(type(a))
The answer I'm expecting is b.
This error is occurring because you're running the code in Python 2, not Python 3. input() in Python 2 will evaluate what you give it, in this case as a variable name, which doesn't exist; while input() in Python 3 will keep it as a string. For more details see What's the difference between raw_input() and input() in python3.x?
How to use the correct Python version is another question, but it looks like you're making some progress in the comments so far.
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.
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.
is it possible in Python to modify, or - at least - deny of execution builtin functions? I need, for educational purpose, to make sure that strings split is unavailable.
For example, I want, if call
'a,b,c'.split(',')
to throw exception or be returned inputed string.
I want to force someone to write own version of that function. Is it possible?
Thanks in advance!
Built-in types (str in your case) and methods cannot be monkey-patched, since they are implemented in C (for cpython implementation).
However, you can define a subclass and redefine the method:
>>> class Mystr(str):
... def split(self, *args):
... raise Exception("Split is not defined")
...
>>> Mystr("test").split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in split
Exception: Split is not defined