parent.py
:
import subprocess
import sys
p = subprocess.Popen([sys.executable, 'sub.py'], stdin=subprocess.PIPE)
p.stdin.write('foo') # not even a newline seems to be required for this to work, oddly
# p.stdin.flush() # optional; seems like not required
_, _ = p.communicate() # this is required--otherwise it just seems to block
sub.py
:
print raw_input()
然后按预期运行parent.py
输出。foo
如果您关心 的返回值communicate()
,只需替换_, _
为out, err
(或者例如out, _
,如果您只关心 STDOUT);我只是喜欢用 标记未使用的变量_
,虽然可以简单地完全忽略communicate()
... 的返回值,但它看起来就像communicate
什么都不返回。
请参阅:http ://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate
更新:
看起来你也可以:
p = subprocess.Popen([sys.executable, 'sub.py'], stdin=subprocess.PIPE)
_, _ = p.communicate(input='foo')