[英]Writing sys.stdout to multiple log files using Python?
我无法弄清楚我的代码片段在我的控制台中将打印消息写入多个日志文件的问题在做什么。
我在下面发布的代码片段应该创建一个新目录test
,然后将 11 个日志文件、1 个全局日志文件和 10 个循环日志文件写入该目录。 但是,当我运行它时,我的全局日志文件的第一条 2 条打印消息丢失了,我无法弄清楚问题是什么?
import sys
import os
# Create a test folder to store these global and loop log files.
path = os.getcwd()
test_dir_name = 'test'
test_dir_path = os.path.join(path, test_dir_name)
os.mkdir(test_dir_path)
# Keep a reference to the original stdout.
orig_stdout = sys.stdout
# Define global logfile path.
global_log_name = "global-log.txt"
global_log_path = os.path.join(test_dir_path, global_log_name)
# Problematic code-snippet
sys.stdout = open(global_log_path, 'w')
print("This is a global log file.") # Why is my code omitting this line?
print("The loop is now creating 10 individual log files.") # And this one?
sys.stdout.close()
for i in range(10):
sys.stdout = open(global_log_path, 'w')
print("Creating loop log file {}...".format(i))
sys.stdout.close()
loop_log_name = "local-log-{}.txt".format(i)
loop_log_path = os.path.join(test_dir_path, loop_log_name)
sys.stdout = open(loop_log_path, 'w')
print("This is loop log file {}".format(i))
print("Closing this loop log file...")
sys.stdout.close()
sys.stdout = open(global_log_path, 'w')
print("Loops have concluded.") # But then it includes this line.
print("Now closing global log file.") # And this line in the global log file.
sys.stdout.close()
sys.stdout = orig_stdout
print("Back to original console.")
一些帮助将不胜感激。
此代码片段的主要问题是不恰当地使用open(global_log_path, 'w')
到 append 进一步将消息打印到global-log.txt
。 最初执行后:
sys.stdout = open(global_log_path, 'w')
print("This is a global log file.") # Why is my code omitting this line?
print("The loop is now creating 10 individual log files.") # And this one?
随后将stdout
重定向到global-log.txt
需要传递参数a
,代表append到open()
,如下所示:
sys.stdout = open(global_log_path, 'a')
print("Creating loop log file {}...".format(i))
这可以防止以前重定向的文本被覆盖,这发生在您的代码片段中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.