查看子流程手动的。您可以选择subprocess
能够重定向stdin
, stdout
, and stderr
您调用自己的流程的信息。
from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print grep_stdout
您还可以逐行与流程交互。鉴于此prog.py
:
import sys
print 'what is your name?'
sys.stdout.flush()
name = raw_input()
print 'your name is ' + name
sys.stdout.flush()
您可以通过以下方式与其逐行交互:
>>> from subprocess import Popen, PIPE, STDOUT
>>> p = Popen(['python', 'prog.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
>>> p.stdout.readline().rstrip()
'what is your name'
>>> p.communicate('mike')[0].rstrip()
'your name is mike'
编辑:在python3中,它需要是'mike'.encode()
.