2013-02-10 100 views
1

我需要啓動進程並在進程運行時讀取該進程的輸出。我希望能夠打印輸出(可選)並在處理完成時返回輸出。以下是我迄今爲止(從其他答案在計算器合併​​):在進程運行時讀取進程的輸出

def call(command, print_output): 
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    out = "" 

    while True: 
     line = process.stdout.readline().rstrip().decode("utf-8") 
     if line == '': 
      break 

     if print_output: 
      print(line) 

     out += line + "\n" 

    process.wait() 

    return process.returncode, out 

這段代碼在窗口(與Windows 7,蟒蛇3.3測試)的偉大工程,但在Linux失敗(Ubuntu的12.04,蟒蛇3.2)。在linux中,腳本掛在線上

line = process.stdout.readline().rstrip().decode("utf-8") 

當過程結束時。

代碼有什麼問題?我試着檢查process.poll()是否已經完成,但是在Linux下它總是返回None。

+0

在我的Linux上運行良好,3.2,並沒有關閉封閉的FD似乎是一個非常不可能的錯誤。當你對Python程序進行分離時,你會看到什麼?另外,你可以包含你使用的'command'的值嗎? – phihag 2013-02-10 20:33:11

+1

感謝您的評論!問題實際上是命令,它是一個「svn export ...」,svn進程第一次需要用戶輸入(login,passwort)。對不起,... – osiris81 2013-02-10 23:20:46

回答

0

文檔說

Warning Use communicate() rather than 
.stdin.write, .stdout.read or .stderr.read to 
avoid deadlocks due to any of the other OS pipe buffers filling 
up and blocking the child process. 

我知道我以前對Windows中的問題。

我假設命令以某種方式在非緩衝模式下運行。

該文檔有使用子過程的食譜你的聽起來像shell-backquote但你使用subprocess是不同的。

相關問題