如何从子进程 python 2.7 和 Apache 读取实时输出

use*_*678 5 apache subprocess pipe python-2.7 ros

我有一个 Apache Web 服务器,我制作了一个 python 脚本来运行命令。我正在运行的命令正在启动一个 ROS 启动文件,该文件无限期地工作。我想实时读取子流程的输出并将其显示在页面中。到目前为止,我的代码只能在终止进程后才能打印输出。我已经尝试了网络上的各种解决方案,但似乎都不起作用

command = "roslaunch package test.launch"
proc = subprocess.Popen(
   command,
   stdout=subprocess.PIPE,
   stderr=subprocess.STDOUT,
   env=env,
   shell=True,
   bufsize=1,
)
print "Content-type:text/html\r\n\r\n"
for line in iter(proc.stdout.readline, ''):
   strLine = str(line).rstrip()
   print(">>> " + strLine)
   print("<br/>")
Run Code Online (Sandbox Code Playgroud)

And*_*bis 6

问题是 的输出roslaunch正在被缓冲。subprocess在这种情况下,并不是实时输出处理的最佳工具,但 Python 中有一个完美的工具可以完成该任务:pexpect. 下面的代码片段应该可以解决问题:

import pexpect

command = "roslaunch package test.launch"
p = pexpect.spawn(command)
print "Content-type:text/html\r\n\r\n"
while not p.eof():
    strLine = p.readline()
    print(">>> " + strLine)
    print("<br/>")
Run Code Online (Sandbox Code Playgroud)