Reputation: 78
I have a python script that can read it's data from stdin or from a file. In order to do this, I use fileinput in the following manner:
for line in fileinput.input(args.path):
read.parseLine(line)
Which works fine. However, after reading this file/input, I want to be able to ask the user for some additional input through stdin using read:
data = raw_input("Please enter your data for port {}: ".format(core.getPort()))
This does not work, since raw_input keeps on encountering an EOF.
Please enter your data for port 0: Traceback (most recent call last):
File "app_main.py", line 72, in run_toplevel
File "/usr/local/bin/dvm", line 98, in <module>
data = raw_input("Please enter your data for port {}: ".format(core.getPort()))
EOFError
I tried to resolve this by usingsys.stdin.seek(0)
But that returns the following error:
Traceback (most recent call last):
File "app_main.py", line 72, in run_toplevel
File "/usr/local/bin/dvm", line 88, in <module>
sys.stdin.seek(0)
IOError: [Errno 29] Illegal seek: '<fdopen>'
Is there any way to ask for user input after using fileinput?
Upvotes: 1
Views: 282
Reputation: 1123590
fileinput
doesn't do anything to sys.stdin
other than read (it explicitly makes sure not to close sys.stdin
).
But you cannot use sys.stdin
both as file input and for raw_input()
; either sys.stdin
is attached to a pipe, or it is connected to the user terminal. It cannot be attached to both. And fileinput
would read from stdin
indefinitely unless an end-of-file was reached at some point.
In other words, you cannot use raw_input
when sys.stdin
is not attached to a terminal. You could use the os.isatty()
function to detect if a terminal is available:
if os.isatty(sys.stdin.fileno()):
# we have a terminal, I can use `raw_input()`
Upvotes: 2