Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe input to Python program and later get input from user

Tags:

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.

like image 768
Kevin Burke Avatar asked Aug 21 '11 21:08

Kevin Burke


People also ask

How do you get input from a user to your Python program?

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.

Which command is used to get input from the user in Python?

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.

How does Python get input from the command line?

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.


1 Answers

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.

like image 105
agf Avatar answered Sep 28 '22 06:09

agf