In the following code, I would expect python to free fileinput.input when I return ing in the middle of my loop, as it is out of scope. However, when called again, my fileinput function tells me
raise RuntimeError, "input() already active"
Here is my code:
def func(inplace): for line in fileinput.input(sys.argv[1], inplace=inplace): [..] if condition: return True [..] if func(False): func(True)
I would expect this behavior when using yield , but not when using return.
I am using Python 2.7.3.
Is there a way to force reset fileinput?
EDIT
When calling fileinput.close() before returning, it works. Why is this not done implicitly?
EDIT 2 : thanks @MatsLindh
Replacement
for line in fileinput.input(sys.argv[1], inplace=inplace):
with
for line in fileinput.FileInput(sys.argv[1], inplace=inplace):
does what I want because it returns an object that goes out of scope in a certain way. I assumed that fileinput.input() does this, but no. It uses a global instance.
source share