在這裏有很多事情在少量的代碼。我會盡量保持簡潔。Python函數捕獲子進程標準輸出和標準錯誤日誌文件
我有一個python函數,它運行一個外部程序,並將stdout和stderr都指向一個日誌文件。
我使用doctest來測試函數。我需要測試輸出捕捉功能。下面的代碼顯示了我編寫函數和測試的嘗試。測試失敗,沒有寫入日誌文件。我不確定問題出在測試或測試代碼中,或者兩者兼而有之。建議?
from __future__ import print_function
import subprocess
def run(command_line, log_file):
"""
# Verify stdout and stderr are both written to log file in chronological order
>>> run("echo text to stdout; echo text to stderr 1>&2", "log")
>>> f = open("log"); out = f.read(); f.close()
>>> print(out.strip())
text to stdout
text to stderr
"""
command_line = "set -o pipefail; " + command_line + " 2>&1 | tee " + log_file
# Run command. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError
subprocess.check_call(command_line, shell=True, executable="bash")
測試結果:
$ python -m doctest testclass.py
text to stdout
text to stderr
**********************************************************************
File "testclass.py", line 10, in testclass.run
Failed example:
print(out.strip())
Expected:
text to stdout
text to stderr
Got:
<BLANKLINE>
**********************************************************************
1 items had failures:
1 of 3 in testclass.run
***Test Failed*** 1 failures.
你嘗試,從產生的bash命令'「set -o pipefail;」+ command_line +「2>&1 | tee」 + log_file'在終端?輸出是什麼樣的? –
發送到終端的文本與此命令一樣:set -o pipefail;將文本回顯到stdout;將文本回顯到stderr 1>&2 2>&1 | tee log – Steve
@ Jean-FrançoisFabre這是大批量生產過程中的一小部分,用於生成用戶檢查處理結果所需的大型日誌文件。 – Steve