这不是我第一次遇到这个问题,它真的让我烦恼。 每当我使用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]
的这里的问题是,第二次,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
是否允许多个通信?
对于psql,有很多现有的Python包装:http://wiki.python.org/moin/PostgreSQL – 2012-06-13 12:16:13