【问题标题】:Python: stdout to both console and textfile including errorsPython:控制台和文本文件的标准输出,包括错误
【发布时间】:2016-11-15 06:46:45
【问题描述】:

我想将 python 的输出打印到控制台和包含错误(如果有)的文本文件。

到目前为止,我的尝试如下:

使用控制台:

# mystdout.py
# note that it has missing ) sign
print("hello


# in the terminal:
chmod a+x mystdout.py; ./mystdout.py 2>&1 | tee output.txt
# does not print to oputut.txt if mystout.py has syntax errors

打印到文件(python3):

with open('out.txt', 'a') as f:  
    print('hello world', file=f)
    # this does not print to console, only to the file

定义一个名为“Tee”的类

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author    : Bhishan Poudel
# Date      : Jul 12, 2016


# Imports
import sys
import subprocess

##=============================================================================
class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() 
    def flush(self) :
        for f in self.files:
            f.flush()

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
##=============================================================================
print('This works good, prints all the output to both console and to a file')
print("This does not print output to file in case of syntax errors")
print("This does not print output of subprocess.call")

问题 假设我有一个可执行文件(来自打印 hello 的 C 程序)

subprocess.call('./hello')
# How to print output of this executable to both console and outputfile?

注意:生成可执行 hello 的代码

// gcc -o hello hello.c
#include<stdio.h>

int main() {
    printf("hello\n");
return 0; }

相关链接:
How to redirect 'print' output to a file using python?
http://linux.byexamples.com/archives/349/how-to-redirect-output-to-a-file-as-well-as-display-it-out/
Output on the console and file using python

【问题讨论】:

  • 您的 Python 脚本没有 shebang。系统如何确定让 Python 执行它?
  • @jpmc26,我的 python 脚本有 shebang,在脚本的顶部,#!/usr/bin/env python 或者,我应该使用:#!/usr/bin/python 吗?跨度>
  • 您在这个问题中的示例mystdout.py 脚本没有。使用哪一种取决于您的环境配置。

标签: python file-io


【解决方案1】:

如果您使用的是 bash(最低版本 4),您可以运行:./mystdout |&amp; tee output.txt。否则你的建议 ./mystdout 2&gt;&amp;1 | tee output.txt 也应该有效。

【讨论】:

  • 即使你使用|&amp;?
  • 这没有bash语法错误:chmod a+x mystdout.py; ./mystdout.py 2>&1 | tee output.txt 但在出现错误时不起作用
  • ./mystdout2.py |& tee output.txt bash:意外标记 `&' 附近的语法错误
  • 我已经为|&amp;添加了最低版本的bash,抱歉。你可以编辑你的问题来解释“但在错误的情况下不起作用”吗?您应该显示在终端中显示但在 output.txt 中缺失的输出。
  • bash --version GNU bash,版本 3.2.53(1)-release (x86_64-apple-darwin13),我们可以让它适用于 bash 3.2 吗?
【解决方案2】:

@Pierre 的解决方案应该有效。 否则,我建议从外部进程中截取 stdout/stderr 并使用两个处理程序进行日志记录:一个用于控制台,另一个用于特定文件。 这里是和example的日志配置。

【讨论】:

  • 如果您正在编写“生产”代码而不仅仅是一个快速脚本,这一点很重要:到目前为止,这个答案是比我的更好的长期答案。
【解决方案3】:

我正在使用 bash 3.2.53。不幸的是,皮埃尔的解决方案对我不起作用。 grundic 提到的解决方案对我来说太复杂了。

所以,我想出了一个简单的解决方案:
当python运行没有错误时,这个方法对我有用:

python3 a.py | tee aout.txt

# to test other example
echo hello this is a test | tee hello.txt

# Like this it works for every commands.

【讨论】: