简体   繁体   中英

Writing sys.stdout to multiple log files using Python?

I am having trouble figuring out what the issue with my code snippet for writing print messages in my console to multiple log-files is doing.

The code snippet I have posted below is supposed to create a new directory test , then write 11 log-files, 1 global log file, and 10 loop log files to this directory. However, the 1st 2 print messages to my global log file is missing when I run this and I cannot figure out what the issue is?

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.")

Some assistance would be greatly appreciated.

The principal issue with this code snippet is the inappropriate use of open(global_log_path, 'w') to append further print messages to global-log.txt . After you have initially executed:

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? 

Subsequent redirections of stdout to global-log.txt instead require passing the argument a , standing for append to open() like so:

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

This prevents previously redirected text from being overwritten, which was happening with your code snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM