【问题标题】:Python function capturing subprocess stdout and stderr to log filePython函数捕获子进程stdout和stderr到日志文件
【发布时间】: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&gt;&amp;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


【解决方案1】:

由于使用shell=True 执行subprocess.check_call,使用 2 个 stdout/stderr 重定向和 tee 并不是执行命令和捕获输出的最佳方式(实际上它最接近最差 方式),我对它失败并不感到惊讶。

我的解决方案是删除 set -o pipefail 作为初学者(您不需要在此处检查返回代码)并将两个命令包装在括号中,否则重定向 / tee 仅适用于最后一个(我仍然不明白为什么老实说,你没有得到任何输出):

command_line = "(" + command_line + ") 2>&1 | tee " + log_file

如果您必须恢复 pipefail 的内容,请在括号内执行:

command_line = "(set -o pipefail; " + command_line + ") 2>&1 | tee " + log_file

【讨论】:

  • 我认为他根本没有输出,因为他实际上只是将stderr 文本传送到日志文件中,而日志文件可能只是空的。
  • @ThomasKühn 但他正在做echo text to stderr 1&gt;&amp;2:应该将文本发布到stderr。
  • 对,我错过了那部分。没有例子就很难测试。嗯,现在解决了;)
猜你喜欢
  • 2018-08-05
  • 2020-06-23
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 2011-07-07
  • 2018-01-11
  • 2014-10-14
相关资源
最近更新 更多