Reputation: 615
i bumped into one line of code which use the file descriptor to get the input from stdin.
print(sum(1-2*('-'in s)for s in[*open(0)][1:]))
from the documentation here i found that file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
The thing is that when i run this in the bash like
python3 -c "print(sum(1-2*('-'in s)for s in[*open(0)][1:]))"
i cant terminate and exit the execution, unless i kill it.
Do you know how i can close the IO object in this case?
Upvotes: 0
Views: 160
Reputation:
You could do it like this:-
with open(0) as stdin:
print(sum(1-2*('-' in s)for s in [*stdin][1:]))
Then, you need to emulate EOF with Ctrl-D. That will indicate that there's no more input, the context manager will terminate and stdin will be closed
Upvotes: 1