I would like to capture the console output at the end of a Python script. That is, I want to both print to console as normal and, at the end of execution, save the console output to a file.
I have seen various related SO questions 1, 2, 3 though they either simply redirect the output and not display it or use logging
. From what I can tell from reading the logging
doc you can only log output from the code you've written.
The issue with all the links above is console output from code you have not written that also prints to console. I want the entire console output of the program at the end of execution.
My first instinct was something along the lines of
logFile = open('LogFile.txt', 'w')
def print_log(msg):
print(msg)
logFile.write(msg)
print_log('Hello World!')
logFile.close()
But this would still fail to capture console output from other code and libraries in use. Is there a way to save a python script's console output at the end of execution? I feel like there should be a simple way to do this but all my research has led to no appropriate solution.