我想要类似于
tee
命令在基于 Linux 的系统中执行的操作,但是是在纯 Python 代码中。
我尝试过使用这个片段:
import sys
# Define the file name for logging
log_file_name = 'output.log'
# Open the file in append mode
log_file = open(log_file_name, 'a')
# Function to log output to both console and file
def log(message):
# Write to console
print(message)
# Write to file
log_file.write(message + '\n')
# Flush the buffer to ensure the message is written immediately
log_file.flush()
# Redirect stdout and stderr to the log function
sys.stdout.write = log
sys.stderr.write = log
print("Hello world!")
但是我收到此错误:
object address : 0x7f88e6b1c1c0
object refcount : 2
object type : 0x9e14c0
object type name: RecursionError
object repr : RecursionError('maximum recursion depth exceeded')
lost sys.stderr
每当我在
log
函数中注释掉 print 语句时,它都会将消息记录到日志文件中 但不会将消息输出到控制台。为什么会发生这种情况以及如何解决它?
这是一种方法:
import sys
_print = print
def print(*args, **kwargs):
_print(*args, **kwargs, file=open('output.log','w'))
_print(*args, **kwargs)
print("Hello world!")