我正在寻找一种将输出打印到日志文件中的方法,但我也想在我的 pycharm 调试器中看到。
我找到了这个,但它只打印到文件中:
log = open("myprog.log", "a")
sys.stdout = log
>>> print("Hello")
>>> # nothing is printed because it goes to the log file instead.
有什么办法吗?
如果可以的话,避免更换
sys.stdout
,在这里你可以。
log_file = open('myprog.log', 'a')
def log(text):
print(text)
log_file.write(str(text) + '\n')
log('hello')
以与@PiMarillion答案相同的方式,但更简洁(使用
with open
)并且可用,即使该函数是在另一个文件中定义的:
def log_text(log_file_path, verbose, text):
"""
Function to print text in console and add it to a log file.
:param log_file_path: path of the log file
:param verbose: boolean parameter, when True text is printed to terminal
:param text: string of the message to print and write
:return: nothing
"""
if verbose:
print(text)
with open(log_file_path, "a") as lf:
lf.write(text + "\n")
return
请注意,
verbose
参数是可选的,拥有这种参数只是很方便。
然后您可以在代码中的任何位置调用此函数。