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
Mary-Kate OlsenOriginal
2024-12-22 04:45:09188browse

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

Then, instantiate a Tee object:

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

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

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)

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!

Statement:
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