在不破坏管道的情况下与进程多次通信?

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)

这篇关于在不破坏管道的情况下与进程多次通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在不破坏管道的情况下与进程多次通信?

基础教程推荐