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!