如何从子进程python 2.7和Apache读取实时输出 [英] How to read live output from subprocess python 2.7 and Apache

查看:123
本文介绍了如何从子进程python 2.7和Apache读取实时输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an Apache web server and I made a python script to run a command. Command that I'm running is launching a ROS launch file, that is working indefinitely. I would like to read output from the subprocess live and display it in the page. With my code so far I could only manage to make output to be printed after I terminate the process. I've tried all kinds of solutions from the web but none of them seem to work

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/>")

推荐答案

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

The problem is that the output of roslaunch is being buffered. subprocess is not the best tool for real-time output processing in such situation, but there is a perfect tool for just that task in Python: pexpect. The following snippet should do the trick:

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/>")

这篇关于如何从子进程python 2.7和Apache读取实时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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