gpt4 book ai didi

Python:控制台和文本文件的标准输出,包括错误

转载 作者:太空宇宙 更新时间:2023-11-03 13:36:48 25 4
gpt4 key购买 nike

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

最佳答案

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

关于Python:控制台和文本文件的标准输出,包括错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38338823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com