2015-05-04 54 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,是否爲你工作? –

相關問題