2015-05-04 122 views
3

我有一个Apache Web服务器,我制作了一个python脚本来运行命令。我正在运行的命令是启动ROS启动文件,该文件无限期地工作。我想读取子进程的输出并将其显示在页面中。使用我的代码到目前为止,我只能设法在输出结束后打印输出。我已经试过各种来自网络的解决方案,但他们都不工作如何读取子进程python 2.7和Apache的实时输出

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

你试过调用'sys.stdout.flush()'吗? – jfs

+0

是的,它没有工作 – user3906678

+0

你的代码和屏幕之间可能有其他缓冲区。你是否尝试过明显的东西,例如,删除'subprocess'并且只是暂停打印:'print“Content-type:text/html \ r \ n \ r \ n”对于范围(100)中的i:print(“ 02d“%i)* 10000; time.sleep(1)'(也许你应该使用'Transfer-Encoding:chunk') – jfs

回答

0

的问题是,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/>") 
+0

@ user3906678,是否为你工作? –

相关问题