적은 양의 코드로 많은 일이 진행되고 있습니다. 나는 이것을 간결하게 유지하려고 노력할 것이다.
외부 프로그램을 실행하고 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.
을하고 이후 subprocess.check_call
에 shell=True
이 표준 출력 / 표준 오류 리디렉션과 함께, tee
명령 및 캡처 출력을 실행하는 가장 좋은 방법은 아니다 (실제로는 가장 근접한 최악의 방법), 나는 정말 실패 놀라게하고 있지 않다.
내 해결책은 set -o pipefail
for starters (여기에서 반환 코드를 확인할 필요가 없음)를 삭제하고 두 명령을 괄호로 묶고 그렇지 않으면 리디렉션 / tee는 마지막 명령에만 적용됩니다 (나는 여전히 출력이없는 이유에 대해 의아해합니다. , 솔직히 말해서) :
command_line = "(" + command_line + ") 2>&1 | tee " + log_file
복원해야하는 경우 pipefail
괄호 안에 수행하십시오.
command_line = "(set -o pipefail; " + command_line + ") 2>&1 | tee " + log_file
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다