How to read live output from subprocess python 2.7 and Apache

房东的猫 提交于 2019-12-07 11:55:07

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/30026045/how-to-read-live-output-from-subprocess-python-2-7-and-apache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!