1

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?

1 Answer 1

2

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()`
Sign up to request clarification or add additional context in comments.

5 Comments

I'm guessing it's impossible to change the destination of stdin at execution time?
@mathsaey: The destination is your script. You cannot change the source, no. That's all set up before Python is even run.
Alright, would it be possible to ask for user input in some other way if stdin is bound to a pipe?
Command-line switches perhaps? stdin is out, no pun intended.
In my case, I can pass the information requested by the raw_input through the command line, so I'll probably just go that route. Allow either input through stdin, or passing fileinput through stdin, but not both. Regardless, thank you for your help, I'll accept this tomorrow if nobody came up with something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.