Python:stdout到控制台和文本文件,包括错误

时间:2016-07-12 21:02:29

标签: python file-io

我想将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")

问题 假设我有一个可执行文件(来自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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

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

答案 2 :(得分:0)

我正在使用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.
相关问题