与子进程通信,无需等待子进程在 Windows 上终止 [英] Communicate with subprocess without waiting for the subprocess to terminate on windows

查看:94
本文介绍了与子进程通信,无需等待子进程在 Windows 上终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 echoprocess.py:

I have a simple echoprocess.py:

import sys

while True:
    data = sys.stdin.read()
    sys.stdout.write("Here is the data: " + str(data))

还有一个 parentprocess.py

And a parentprocess.py

from subprocess import Popen, PIPE

proc = Popen(["C:/python27/python.exe", "echoprocess.py"],
             stdin = PIPE,
             sdtout = PIPE)

proc.stdin.write("hello")
print proc.stdout.read()

这会一直挂起,直到 echoprocess.py 终止.我想多次与这个子进程通信而不必再次重新启动它.Windows 上的 Python 子进程模块是否可以进行这种进程间通信?

This just hangs until echoprocess.py is terminated. I want to communicate with this subprocess multiple times without having to restart it again. Is this kind of interprocess communication possible with the Python subprocess module on Windows?

推荐答案

主要问题是线路...

print proc.stdout.read()

read() 方法不带参数使用时会读取所有数据直到 EOF,直到子进程终止才会发生.

The read() method when used with no parameters will read all data until EOF, which will not occur until the subprocess terminates.

您可能会接受逐行阅读,因此您可以使用...

You'll probably be okay with line-by-line reading, so you can use...

proc.stdin.write("hello\n")
print proc.stdout.readline()

...否则,您将不得不想出一些其他方法来分隔消息".

...otherwise you'll have to work out some others means of delimiting 'messages'.

您必须对 echoprocess.py 进行类似的更改,即更改...

You'll have to make a similar change to echoprocess.py, i.e. change...

data = sys.stdin.read()

...到...

data = sys.stdin.readline()

您可能还存在输出缓冲问题,因此可能需要在写入后flush()缓冲区.

You may also have issues with output buffering, so it may be necessary to flush() the buffer after doing a write.

将所有这些放在一起,如果您将 echoprocess.py 更改为...

Putting all this together, if you change echoprocess.py to...

import sys

while True:
    data = sys.stdin.readline()
    sys.stdout.write("Here is the data: " + str(data))
    sys.stdout.flush()

...和 ​​parentprocess.py 到...

...and parentprocess.py to...

from subprocess import Popen, PIPE

proc = Popen(["C:/python27/python.exe", "echoprocess.py"],
             stdin = PIPE,
             stdout = PIPE)

proc.stdin.write("hello\n")
proc.stdin.flush()
print proc.stdout.readline()

...它应该按照您期望的方式工作.

...it should work the way you expect it to.

这篇关于与子进程通信,无需等待子进程在 Windows 上终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆