2014-10-26 32 views
1

我運行一個java程序作爲子進程,但是當我將stderr重定向到管道時,程序掛起。例如myProcess = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)工程,但myProcess = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr=subprocess.PIPE)掛起。當stderr被傳送時,python子進程掛起

我運行的命令是沿着線的東西:

java -DSomeVals -classpath <somevals> package.Name 

標準錯誤輸出產生大量的,我記得讀書的地方,有殼=真可能會導致死鎖。不幸的是,當我設置shell = False時,我得到一個錯誤消息,文件名太長。

我試過myProcess = subprocess.Popen(['java', args], shell=False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)但是後來java抱怨說它找不到我想要運行的類。

我想管道stderr,因爲它混亂我的程序的輸出。

+0

你以後如何處理來自管道的數據?大部分的python文檔都說要使用通信,但是如果你不關心stderr的內容,那麼可以像stderr = open(「/ dev/null」)這樣那麼它會泄露文件描述符),否則你需要使用'communicate()'這樣的東西來緩衝兩個管道,以防止輸出觸發死鎖。 – Petesh 2014-10-26 18:30:53

+0

我打電話溝通,但只有在該過程已運行約5分鐘後(需要很長時間才能生成我需要的結果)。與此同時,應用程序每隔幾秒就會寫一條日誌消息。 – ventsyv 2014-10-26 22:30:57

回答

1

我想你只需要從管道讀取。管道緩衝區填滿並阻止進程。檢出這個重複「HelloWorld」50,000次的例子。

import subprocess 
import os 

def getLinesFromShellCommand(command): 
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.getcwd()) 
    lines = [] 
    for curLine in p.stdout.readlines(): 
     lines.append(curLine) 
    p.wait() 
    return lines 


print "Starting..." 
lines = getLinesFromShellCommand("printf 'HelloWorld\n%.0s' {1..50000}") 
for curLine in lines: 
    print curLine, 
相關問題