簡體   English   中英

使用 Python 將 sys.stdout 寫入多個日志文件?

[英]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 ,代表appendopen() ,如下所示:

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

這可以防止以前重定向的文本被覆蓋,這發生在您的代碼片段中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM