也許以前有人可以幫我解決這個問題。 (我已經看到了一些類似的問題在SO上,但沒有處理標準錯誤和標準錯誤,或處理與我的情況相當,因此這個新問題。)如何在不失真的情況下打印和顯示子處理stdout和stderr輸出?
我有一個python函數打開一個子進程,等待它完成,然後輸出返回代碼,以及標準輸出和標準錯誤管道的內容。在進程正在運行的同時,我還想在填充它們時顯示兩個管道的輸出。我的第一次嘗試導致了這樣的事情:
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = str()
stderr = str()
returnCode = None
while True:
# collect return code and pipe info
stdoutPiece = process.stdout.read()
stdout = stdout + stdoutPiece
stderrPiece = process.stderr.read()
stderr = stderr + stderrPiece
returnCode = process.poll()
# check for the end of pipes and return code
if stdoutPiece == '' and stderrPiece == '' and returnCode != None:
return returnCode, stdout, stderr
if stdoutPiece != '': print(stdoutPiece)
if stderrPiece != '': print(stderrPiece)
雖然有一些問題。由於read()
的讀數爲EOF
,因此while
循環的第一行將不會返回,直到子進程關閉管道。
我可以替換read()
轉而使用read(int)
,但打印的輸出會失真,在讀取的字符結束時會被截斷。我可以用readline()
作爲替代,但是當兩者同時出現很多時,打印的輸出會以交替的輸出線和錯誤線扭曲。可能有read-until-end-of-buffer()
變種,我不知道?或者,也許它可以實施?
也許最好按answer to another post的建議實施sys.stdout
包裝?然而,我只想在這個函數中使用包裝器。
社區的其他想法?
我很感激幫助! :)
編輯:解決方案確實應該是跨平臺的,但如果您有不是的想法,請分享它們以保持頭腦風暴。
對於我的蟒蛇頭子的刮管另外一個,看看我的另一問題上accounting for subprocess overhead in timing。
你可能想看看像pexpect。 –
爲什麼不只是創建一個StringIO並將同一個實例傳遞給子進程的stdout和stderr? –
@NathanErnst:因爲那不行。 'stdout'和'stderr'必須是真實的OS級文件描述符。 –