Python:将stdout输出到控制台和文本文件,包括错误信息

3
我希望将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 程序)

问题

假设我有一个可执行文件(来自打印“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; }

相关链接:
如何使用Python将“print”输出重定向到文件?
如何将输出重定向到文件并在屏幕上显示(Linux)
使用Python在控制台和文件中输出


你的Python脚本没有shebang。系统如何确定要使用Python来执行它? - jpmc26
@jpmc26,我的Python脚本在顶部有shebang,是 #!/usr/bin/env python 还是应该使用 #!/usr/bin/python ? - BhishanPoudel
你在这个问题中提供的 mystdout.py 脚本没有一个。适合使用的脚本取决于你的环境配置。 - jpmc26
3个回答

3

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


即使您使用 |& 也是如此吗? - Pierre
这段代码没有bash语法错误:chmod a+x mystdout.py; ./mystdout.py 2>&1 | tee output.txt,但是在出现错误的情况下无法正常工作。 - BhishanPoudel
./mystdout2.py |& tee output.txt bash:'&' 附近有语法错误。 - BhishanPoudel
我已经添加了bash的最低版本以支持|&,抱歉。你能否编辑你的问题来解释“但在错误情况下不起作用”?你应该展示在终端中显示但在output.txt中缺失的输出。 - Pierre
bash --version GNU bash,版本3.2.53(1)-release(x86_64-apple-darwin13),我们能让它在bash 3.2上工作吗? - BhishanPoudel
"|&" 不起作用,但是 "2>&1 |" 应该可以。如之前所要求的:您能否编辑您的问题来解释“但在错误情况下不起作用”?您应该显示在终端中显示的输出,但在 "output.txt" 中缺失。 - Pierre

3
@Pierre提供的解决方案应该可以解决问题。 否则,我建议从外部进程拦截stdout / stderr并使用日志记录,其中包含两个处理程序:一个用于控制台,另一个用于特定文件。 这是一个日志配置的示例链接:example

如果你正在编写“生产”代码而不仅仅是一个快速脚本,那么这个答案绝对是一个比我的更好的长期答案。 - Pierre

0

我正在使用bash 3.2.53。不幸的是,Pierre提供的解决方案对我没有用。而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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接