1

I'm currently writing a python program on linux which will accept a binary stream via sys.stdin.buffer.read(), and then I'd like it to accept input interactively afterward using input().

Here is a completely contrived example which illustrates my issue:

#!/usr/bin/env python3
import sys 

buf = b"Garbage Data"
#comment out the following line to avoid the EOFError:
buf = sys.stdin.buffer.read()

with open("outTempFile", 'wb') as f:
    f.write(buf)

print("Please enter your name:")
buf2 = input("First:\t")
print("Your first name is:\t{}".format(buf2))

When I run this program with a stdin input, I get the following error/output:

-> % cat contrivedExample.py | ./contrivedExample.py Please enter your name: First: Traceback (most recent call last): File "./contrivedExample.py", line 11, in <module> buf2 = input("First:\t") EOFError: EOF when reading a line

The output file, outTempFile does get written to, however the call to input() fails with the EOFError. I'm guessing this is because STDIN is tied to the pipe I used in the command-line invocation of the script.

When I comment out line #6 and run the program with the same invocation:

-> % cat contrivedExample.py | ./contrivedExample.py

I get the following output:

Please enter your name: First: Your first name is: #!/usr/bin/env python3

Which tells me that input() is indeed reading STDIN from the pipe (|) provided on the command line.

My question is how I can switch the program from reading in via the pipe (|) to reading in via interactive terminal prompt (as is usually done via input())?

1

1 Answer 1

1

The solution I found is after reading from STDIN via a linux pipe (|) to simply replace sys.stdin with open('/dev/tty') which allows input() to read from my terminal:

echo "hello" | python -c 'import sys; buf = sys.stdin.read(); print(buf); sys.stdin=open("/dev/tty"); buf2=input(); print(buf2)'
Sign up to request clarification or add additional context in comments.

Comments

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.