我希望将Python的输出信息同时打印到控制台和文本文件中,包括任何错误信息。
目前我尝试过以下方法: 仅输出到控制台:
假设我有一个可执行文件(来自打印“hello” C 程序)
注意:生成可执行的hello代码
目前我尝试过以下方法: 仅输出到控制台:
# 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在控制台和文件中输出
mystdout.py
脚本没有一个。适合使用的脚本取决于你的环境配置。 - jpmc26