【发布时间】:2015-02-02 12:54:12
【问题描述】:
我有一个进程,我可以像这样在命令行上与之通信:
% process -
input
^D^D
output
所以:我开始这个过程,输入一些输入,然后按两次 Ctrl-D 后,我得到了输出。 我想围绕这个过程制作一个 Python 包装器。我创建了这个:
from subprocess import Popen, PIPE
p = Popen('process -', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
while True:
input = raw_input('Enter input: ')
p.stdin.write(input)
p.stdin.close()
p.wait()
output = p.stdout.read()
print output
这第一次有效,但之后我得到:
Traceback (most recent call last):
File "test.py", line 7, in <module>
p.stdin.write(input)
ValueError: I/O operation on closed file
是否有另一种方法可以在不关闭文件的情况下与此进程进行交互?
【问题讨论】:
-
问题有点复杂。正如我现在所看到的,您必须删除那些结束行,添加
p.stdin.flush()并捕获 SIGINT 信号。当它发生时,您必须将其传递给子进程并然后p.wait()(或更好的p.communicate()),打印输出并关闭进程。
标签: python pipe subprocess