gpt4 book ai didi

Python,记录打印语句,同时将它们打印到标准输出

转载 作者:太空狗 更新时间:2023-10-29 20:33:47 25 4
gpt4 key购买 nike

我有一个经常使用 print 语句的长 python 脚本,我想知道是否可以添加一些代码来将所有 print 语句记录到文本文件或类似文件中。当用户在整个程序中得到提示时,我仍然希望所有打印语句都转到命令行。如果可能的话,记录用户的输入也是有益的。

我发现这在一定程度上回答了我的问题,但使“打印”语句不再打印到命令行

Redirect Python 'print' output to Logger

最佳答案

您可以将其添加到您的脚本中:

import sys
sys.stdout = open('logfile', 'w')

这将使打印语句写入logfile

如果你想要打印到 stdout 和文件的选项,你可以试试这个:

class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)

f = open('logfile', 'w')
backup = sys.stdout
sys.stdout = Tee(sys.stdout, f)

print "hello world" # this should appear in stdout and in file

要恢复到只打印到控制台,只需恢复“备份”

sys.stdout = backup

关于Python,记录打印语句,同时将它们打印到标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17866724/

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