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.
In Python, Using the input() function, we take input from a user, and using the print() function, we display output on the screen. Using the input() function, users can give any information to the application in the strings or numbers format.
To receive information through the keyboard, Python uses the input() function. This function has an optional parameter, commonly known as prompt, which is a string that will be printed on the screen whenever the function is called.
Python provides developers with built-in functions that can be used to get input directly from users and interact with them using the command line (or shell as it is often called). In Python 2, raw_input() and in Python 3, we use input() function to take input from Command line.
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:
sys.stdin = open('/dev/tty')
a = raw_input('Prompt: ')
Redirect stdin to another file handle when you run your script, and read from that:
sys.stdin = os.fdopen(3)
a = raw_input('Prompt: ')
$ (echo -n test | ./x.py) 3<&0
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With