Home > Backend Development > Python Tutorial > How Can I Simultaneously Display Program Output to the Console and Log It to a File?

How Can I Simultaneously Display Program Output to the Console and Log It to a File?

Mary-Kate Olsen
Release: 2024-12-22 04:45:09
Original
192 people have browsed it

How Can I Simultaneously Display Program Output to the Console and Log It to a File?

Teeing System Output to a Log File

Issue:

How to simultaneously display output to the console while also logging it to a file, including system call output?

Solution:

Utilize the Tee class to duplicate system output to a log file without redirection.

First, import the necessary libraries:

import sys
Copy after login

Then, instantiate a Tee object:

tee = Tee("my_log.txt", 'w')
Copy after login

This will open the specified log file and duplicate all subsequent stdout output to both the file and the console.

Finally, ensure you revert stdout back to its original state when finished:

del tee
Copy after login

Example Usage:

with Tee("my_log.txt", 'w'):
    print("foo bar")
    os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
    os.execve("/bin/ls", ["/bin/ls"], os.environ)
Copy after login

This code will print "foo bar" to the console and log it to "my_log.txt", as well as logging any output from the executed system commands.

The above is the detailed content of How Can I Simultaneously Display Program Output to the Console and Log It to a File?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template