0

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
  • How about `python your_program.py > output.log`? – Klaus D. Jan 05 '19 at 05:31
  • Thanks @KlausD. ... the final code will be converted to .exe ... so that's not really the option –  Jan 05 '19 at 05:32
  • 2
    Then I'd say you should use the logging and subprocess modules instead of `print` and `os.system`. – Klaus D. Jan 05 '19 at 05:36
  • I've replaced `os.system(cmd)` with `subprocess.run(cmd, shell=True).stdout` but still can't see it on `message.log` –  Jan 05 '19 at 09:38

0 Answers0