通过流程多次沟通而不会破坏管道?

Man*_*nux 26 python subprocess pipe

这不是我第一次遇到这个问题,这真的让我烦恼.每当我使用Python subprocess模块打开管道时,我只能communicate使用它一次,因为文档指定: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]
Run Code Online (Sandbox Code Playgroud)

这里的问题是,第二次,Python并不开心.实际上,他决定在第一次沟通后关闭文件:

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
Run Code Online (Sandbox Code Playgroud)

是否允许多次通信?

Ter*_*les 22

我觉得你误解了沟通......

http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate

communication将字符串发送到另一个进程,然后等待它完成...(就像你说等待EOF听stdout和stderror)

你应该做的是:

proc.stdin.write('message')

# ...figure out how long or why you need to wait...

proc.stdin.write('message2')
Run Code Online (Sandbox Code Playgroud)

(如果你需要获取stdout或stderr,你可以使用proc.stdout或proc.stderr)


gil*_*esc 6

我以前遇到过这个问题,据我所知,你不能这样做subprocess(我同意,如果这是真的,那是非常违反直觉的)。我最终使用了pexpect(可从 PyPI 获得)。