Thursday, April 7, 2022

[SOLVED] Pipe input to script and later get input from user

Issue

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.


Solution

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.



Answered By - agf
Answer Checked By - Terry (WPSolving Volunteer)