這不是我第一次遇到這個問題,它真的讓我煩惱。 每當我使用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