簡體   English   中英

如何使子進程按順序獲取stdout和stderr?

[英]How can I make subprocess get the stdout and stderr in order?

示例測試文件(print.py):

import sys
print('stdout')
print('stderr', file=sys.stderr)

運行它的代碼(x.py):

import subprocess
cmd = ['python', 'print.py']
print(subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT))

如果我從shell運行print.py,它首先打印stdout。 但是,如果我運行x.py,它會先打印stderr。 有沒有辦法讓我以正確的順序獲得輸出?

您的代碼正在緩沖(即延遲)其輸出。 緩沖區過程的詳細信息根據輸出是控制台還是管道而有所不同。

嘗試這個:

cmd = ['python', '-u', 'print.py']

參考: https//docs.python.org/3.5/using/cmdline.html#cmdoption-u

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM