I've been reading about redirect prints to log file, however I did not understand why the accepted answer did not really work as expected.
The original code was in Python2, I've modified it a little bit as I'm working on Python3.
Accepted Answer: https://stackoverflow.com/a/2513511/9013730
import os
def test():
cmd = 'ver'
print("1. Running command:",cmd) # message.log only, NOT in console
os.system(cmd) # This appear in console only, but not in message.log
print('3. Done') # message.log only, NOT in console
import sys
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print("This will be written to message.log") # message.log only, NOT in console
test()
sys.stdout = old_stdout
log_file.close()
Console Output
As you can see, only os.system(cmd)
printed out in console and I did not see it in message.log Output.
Microsoft Windows
message.log Output
When I checked message.log output, os.system(cmd)
was not there.
This will be written to message.log
1. Running command: ver
3. Done
Would it be possible to produce similar (exact) output in both console and message.log?
Desired Output in both console and message.log
This will be written to message.log
1. Running command: ver
Microsoft Windows
3. Done