Let's say I want to pipe input to a Python program, and then later get input from the user, on the command line.
echo http://example.com/image.jpg | python solve_captcha.py
and the contents of solve_captcha.py
are:
import sys
image_url = sys.stdin.readline()
# Download and open the captcha...
captcha = raw_input("Solve this captcha:")
# do some processing...
The above will trigger a EOFError: EOF when reading a line
error.
I also tried adding a sys.stdin.close()
line, which prompted a ValueError: I/O operation on closed file
.
Can you pipe information to stdin
and then later get input from the user?
Note: This is a stripped down, simplified example - please don't respond by saying "why do you want to do that in the first case," it's really frustrating. I just want to know whether you can pipe information to stdin
and then later prompt the user for input.
There isn't a general solution to this problem. The best resource seems to be this mailing list thread.
Basically, piping into a program connects the program's
stdin
to that pipe, rather than to the terminal.The mailing list thread has a couple of relatively simple solutions for *nix:
Open /dev/tty to replace sys.stdin:
Redirect stdin to another file handle when you run your script, and read from that:
as well as the suggestion to use curses. Note that the mailing list thread is ancient so you may need to modify the solution you pick.
Made this up to emulate
raw_input()
, since I had the same problem as you. The wholestdin
andclear
ugliness is simply to make it look pretty. So that you can see what you are typing.bash has process substitution, which creates a FIFO, which you can treat like a file, so instead of
you can use
You would open first argument to solve_capcha.py as a file, and I think that sys.stdin would still be available to read input from the keyboard.
I updated @Bob's answer to support delete, ctrl + [left, right, home, end] keypresses and simplified the stdout clearing and rewriting.