gpt4 book ai didi

python - 如何让 'print()' 、 'os.system()' 和 'subprocess.run()' 输出显示在控制台和日志文件中?

转载 作者:可可西里 更新时间:2023-11-01 14:02:10 26 4
gpt4 key购买 nike

最初,我有一个简单的程序来将整个输出打印到控制台。

仅在控制台中显示输出的初始代码

import os, subprocess

print("1. Before")
os.system('ver')
subprocess.run('whoami')
print('\n2. After')

控制台输出

1. Before

Microsoft Windows [Version 10]
user01

2. After

然后,我决定在日志文件 (log.txt) 上也有一个副本,同时保持控制台的原始输出。

所以,这是新代码。

import os, subprocess, sys

old_stdout = sys.stdout
log_file = open("log.txt","w")
sys.stdout = log_file

print("1. Before") # This appear in message.log only, but NOT in console
os.system('ver') # This appear in console only, but NOT in message.log
subprocess.run('whoami') # This appear in console only, but NOT in message.log
print('\n2. After') # This appear in message.log only, but NOT in console

sys.stdout = old_stdout
log_file.close()

不幸的是,这并没有真正按预期工作。某些输出仅显示在控制台上(os.system('ver')subprocess.run('whoami')),而 print() 函数只显示在 log.txt 文件中,不再显示在控制台中。

控制台输出

Microsoft Windows [Version 10]
user01

输出到log.txt文件

1. Before

2. After

我希望在控制台和 log.txt 文件中得到类似的输出。这可能吗?我的新代码有什么问题?请告诉我如何解决此问题。

控制台和 log.txt 文件中的所需输出

1. Before

Microsoft Windows [Version 10]
user01

2. After

最佳答案

处理此问题的最合适方法是使用日志记录。这是一个例子:

这是 python 2.6+ 和 3.x 版本的操作方法。 (在 2.6 之前不能覆盖 print())

log = logging.getLogger()
log.setLevel(logging.INFO)

# How should our message appear?
formatter = logging.Formatter('%(message)s')

# This prints to screen
ch = log.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
log.addHandler(ch)

# This prints to file
fh = log.FileHandler('/path/to/output_file.txt')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)

def print(*args, **kwargs):
log.DEBUG(*args)

该选项允许您使用日志级别。例如,您可以在整个代码中放置调试日志记录,以了解应用程序何时开始表现不佳。将 logLevel 换成 logging.DEBUG 突然间,您将该输出显示在屏幕上。请注意,在上面的示例中,我们有 2 个不同的日志记录级别,一个用于屏幕,另一个用于文件。是的,这将为每个目的地产生不同的输出。您可以通过将两者更改为使用 logging.INFO(或 logging.DEBUG 等)来解决此问题。 ( See full docs relating to log levels here. )

在上面的示例中,我已经覆盖了 print(),但我建议您只使用 log.DEBUG('Variable xyz: {}' .format(xyz))log.INFO('您要打印的一些内容。)

Full logging documentation.

还有另一种更简单的覆盖方法,但不是那么健壮:

try:
# Python 2
import __builtin__
except ImportError:
# Python 3
import builtins as __builtin__
logfile = '/path/to/logging_file.log'

def print(*args, **kwargs):
"""Your custom print() function."""
with open(logfile) as f_out:
f_out.write(args[0])
f_out.write('\n')
# Uncomment the below line if you want to tail the log or something where you need that info written to disk ASAP.
# f_out.flush()
return __builtin__.print(*args, **kwargs)

关于python - 如何让 'print()' 、 'os.system()' 和 'subprocess.run()' 输出显示在控制台和日志文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051774/

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