Python 子进程多个非阻塞通信

Python subprocess multiple non blocking communicates

我开始一个脚本:

t = subprocess.Popen('rosrun ros_pkg ros_node', shell=True, 
                     stdout = subprocess.PIPE, 
                     stdin = subprocess.PIPE, universal_newlines=True)

然后我想像这样与该进程通信:

stdout = t.communicate('new command')[0]
print(stdout)
if stdout == []:
   logic
stdout = t.communicate('new command')[0]
....

问题是在 t.commincate 子进程关闭后

有类似问题的解决方案,但对我没有任何帮助,请帮助

使用t.communicate()将在发送数据后关闭输入管道,这意味着它只能被调用一次才能向子进程发送数据。

然而,您可以使用 t.stdin.write() 在不关闭管道的情况下进行顺序写入,然后使用 t.stdin.readline() 获取输出。这些工作方式与 open() 返回的处理程序相同。

import subprocess


t = subprocess.Popen("cat", stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True, shell=True)

#These calls will have their results written to the output pipe
t.stdin.write('hi there ')
t.stdin.write('hi again\n')
#However the input data is buffered first, so call flush() before reading
t.stdin.flush()

#Read from the pipe
a = t.stdout.readline()
print(a)

t.stdin.write('hi back at you\n')
t.stdin.flush()


a = t.stdout.readline()
print(a)

我现在从使用子流程切换到使用 pexpect。 我的语法现在如下:

child = pexpect.spawn('rosrun ros_pkg ros_node')
command = child.sendline('new command')
output = child.read_nonblocking(10000, timeout=1)
....
logic
....
command = child.sendline('new command')
output = child.read_nonblocking(10000, timeout=1)

非常感谢 reddit 上的 novel_yet_trivial:https://www.reddit.com/r/learnpython/comments/2o2viz/subprocess_popen_multiple_times/