How to read output from python 2.7 and Apache subprocess

I have an Apache web server and I created a python script to run a command. The command I'm running runs a ROS startup file that runs endlessly. I would like to read the output from a subprocess live and display it on a page. With my code so far, I could only draw the output to be printed after the process finished. I've tried all kinds of solutions from the internet but none of them 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/>")

      

+3


source to share


1 answer


The problem is that the output is roslaunch

buffered. subprocess

- not the best tool for processing the output in real time in such a situation, but there is a perfect tool for this task in the 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/>")

      

0


source







All Articles