我正在测试与子进程的通信。我必须启动服务器,定期发送数据。最终目标是获取气象数据和绘图服务器的进程。采样率是数量级或分钟......我写了这两个代码片段来理解 python 中 ipc 的基础知识,但我什至无法让它们工作。 同步不是问题。
主要流程
import sys, time
from subprocess import Popen, PIPE
print 'starting'
proc = Popen (['python.exe',
'C:\Documents and Settings\Administrator\Desktop\sub.py'],
stdin = PIPE, stdout = PIPE)
print 'launched'
w = 0
while True:
w += 1
time.sleep (2)
print 'writing', w
proc.stdin.write (repr(w))
proc.stdin.flush()
print proc.stdout.read()
子进程:
import sys, time
print 'reading'
v = 0
while True:
v = sys.stdin.read()
sys.stdout.write('ACK')
sys.stdout.flush ()
time.sleep (4)
主进程阻塞,显然子进程没有读取-发送 ACK。 我哪里错了???谢谢
最佳答案
sys.stdin.read()
的调用会阻塞,因为它试图读取整个 流,因此在流关闭之前它无法返回.
尝试使用 sys.stdin.readline()
并在使用 sys.stdout.write()
写入时添加换行符(在两个进程中),例如sys.stdout.write('ACK\n')
。这应该确保读取命令只会阻塞,直到读取一行。
关于python-2.7 - 连续向子进程发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15587155/