【发布时间】:2017-05-19 14:43:57
【问题描述】:
这里有很多事情发生在少量的代码中。我会尽量保持简洁。
我有一个运行外部程序并将标准输出和标准错误发送到日志文件的 python 函数。
我正在使用 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.
【问题讨论】:
-
您是否尝试过终端中
"set -o pipefail; " + command_line + " 2>&1 | tee " + log_file产生的bash 命令?输出是什么样的? -
发送到终端的文本与此命令的预期一致:set -o pipefail;将文本回显到标准输出;将文本回显到标准错误 1>&2 2>&1 |三通日志
-
@Jean-FrançoisFabre 这是生成用户检查处理结果所需的大型日志文件的大型批处理过程的一小部分。
-
好的我现在明白了:)
-
是的,所以这就是原因。您有两个单独的命令,第一个是
echo text to stdout,您不重定向,然后是echo text to stderr,您将其重定向(管道)到tee。如果在命令序列周围放置一对括号,则会打开一个子shell,在其中执行整个命令序列。子 shell 本身被父 shell 视为一个命令,因此现在您的重定向按预期工作。
标签: python bash subprocess io-redirection tee