Communicate multiple times with a process without breaking the pipe?(在不破坏管道的情况下与进程多次通信?)
问题描述
这不是我第一次遇到这个问题,而且真的很困扰我.每当我使用 Python subprocess
模块打开管道时,我只能与它 communicate
一次,如文档所述:从 stdout 和 stderr 读取数据,直到结束-of-file 到达
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;
")[0]
print proc.communicate("select theta,zeta,result from experiment_2099
")[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
")[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
是否允许多次通信?
推荐答案
我觉得你误解了沟通...
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)
这篇关于在不破坏管道的情况下与进程多次通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在不破坏管道的情况下与进程多次通信?
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01