【发布时间】: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脚本没有。使用哪一种取决于您的环境配置。