Pipe input to Python program and later get input from user

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.


bash has process substitution, which creates a FIFO, which you can treat like a file, so instead of

echo http://example.com/image.jpg | python solve_captcha.py

you can use

python solve_capcha.py <(echo http://example.com/image.jpg)

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.


You can close stdin and then reopen it to read user input.

import sys, os

data = sys.stdin.readline()
print 'Input:', data
sys.stdin.close()
sys.stdin = os.fdopen(1)
captcha = raw_input("Solve this captcha:")
print 'Captcha', captcha

Tags:

Python

Bash

Stdin