在不中断管道的情况下与一个进程多次通信? [英] Communicate multiple times with a process without breaking the pipe?
问题描述
这不是我第一次遇到这个问题,而且确实困扰着我.
每当我使用Python subprocess
模块打开管道时,如文档指定的那样,我只能使用它communicate
一次:Read data from stdout and stderr, until end-of-file is reached
It's not the first time I'm having this problem, and it's really bugging me.
Whenever I open a pipe using the Python subprocess
module, I can only communicate
with it once, as the documentation specifies: Read data from stdout and stderr, until end-of-file is reached
proc = sub.Popen("psql -h darwin -d main_db".split(),stdin=sub.PIPE,stdout=sub.PIPE)
print proc.communicate("select a,b,result from experiment_1412;\n")[0]
print proc.communicate("select theta,zeta,result from experiment_2099\n")[0]
这里的问题是Python第二次不高兴.确实,他决定在第一次交流后关闭文件:
The problem here is that the second time, Python isn't happy. Indeed, he decided to close the file after the first communicate:
Traceback (most recent call last):
File "a.py", line 30, in <module>
print proc.communicate("select theta,zeta,result from experiment_2099\n")[0]
File "/usr/lib64/python2.5/subprocess.py", line 667, in communicate
return self._communicate(input)
File "/usr/lib64/python2.5/subprocess.py", line 1124, in _communicate
self.stdin.flush()
ValueError: I/O operation on closed file
是否允许进行多种通讯?
Are multiple communications allowed?
推荐答案
我认为您误会了沟通...
I think you misunderstand communicate...
http://docs.python.org/library/subprocess. html#subprocess.Popen.communicate
communicate向另一个进程发送一个字符串,然后等待它完成...(就像您说的那样,等待EOF监听stdout& stderror)
communicate sends a string to the other process and then waits on it to finish... (Like you said waits for the EOF listening to the stdout & stderror)
相反,您应该做的是:
proc.stdin.write('message')
# ...figure out how long or why you need to wait...
proc.stdin.write('message2')
(如果需要获取stdout或stderr,则可以使用proc.stdout或proc.stderr)
(and if you need to get the stdout or stderr you'd use proc.stdout or proc.stderr)
这篇关于在不中断管道的情况下与一个进程多次通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!