Running an interactive subprocess with Popen

Diez B. Roggisch deets at nospam.web.de
Fri Apr 10 03:56:11 EDT 2009


David Liang schrieb:
> Hello,
> Sorry for the newbie question. How do I run a program that could
> block, waiting for user input, using subprocess.Popen? For example,
> 
> from subprocess import *
> 
> def foo():
>     a = Popen(['python'] ...)
> 
> I want to be able to get input from the user and send input to the
> subprocess, printing stdout and stderr as data becomes available, then
> return once the subprocess exits. Is it possible to send to the
> subprocess keyboard interrupts, EOF, and such?
> 
> I tried doing stdout=PIPE, stderr=PIPE, stdin=PIPE. I tried using
> communicate(), but could only call it once; subsequent calls raised
> "ValueError: I/O operation on closed file."
> And both a.stdout.read() and a.stderr.read() blocked the program. Any
> help would be much appreciated.


Use pexpect, which emulates a pseudo-terminal speaking with the subprocess.

Diez



More information about the Python-list mailing list