【问题标题】:Writing sys.stdout to multiple log files using Python?使用 Python 将 sys.stdout 写入多个日志文件?
【发布时间】:2021-03-03 15:28:20
【问题描述】:

我无法弄清楚我的代码 sn-p 用于将控制台中的打印消息写入多个日志文件的问题。

我在下面贴的代码sn-p应该是创建一个新目录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.")

我们将不胜感激。

【问题讨论】:

  • 这样会更容易使用logging...

标签: python stdout


【解决方案1】:

此代码 sn-p 的主要问题是不恰当地使用 open(global_log_path, 'w') 将进一步的打印消息附加到 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? 

stdoutglobal-log.txt 的后续重定向需要传递参数 a,代表 appendopen(),如下所示:

sys.stdout = open(global_log_path, 'a')
print("Creating loop log file {}...".format(i))

这可以防止以前重定向的文本被覆盖,这在您的代码 sn-p 中发生。

【讨论】:

    猜你喜欢
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2017-09-25
    • 1970-01-01
    • 2012-04-06
    • 2018-09-10
    • 2023-03-31
    相关资源
    最近更新 更多