Initially, I've a simple program to print out the whole output to the console.

Initial Code to display output in the console only

import os, subprocess

print("1. Before")
os.system('ver')                            
subprocess.run('whoami')        
print('\n2. After')

Output in console

1. Before

Microsoft Windows [Version 10]
user01

2. After

Then, I decided to have a copy on a log file (log.txt) too while maintaining the original output to the console.

So, this is the new code.

import os, subprocess, sys

old_stdout = sys.stdout
log_file = open("log.txt","w")
sys.stdout = log_file

print("1. Before")          # This appear in message.log only, but NOT in console
os.system('ver')            # This appear in console only, but NOT in message.log
subprocess.run('whoami')    # This appear in console only, but NOT in message.log
print('\n2. After')         # This appear in message.log only, but NOT in console

sys.stdout = old_stdout
log_file.close()

Unfortunately, this didn't really work as expected. Some of the output only displayed on the console (os.system('ver') and subprocess.run('whoami')) while the print() function was only displayed on log.txt file and not in the console anymore.

Output in console

Microsoft Windows [Version 10]
user01

Output in log.txt file

1. Before

2. After

I was hoping to get similar output on both console and log.txt file. Is this possible?
What's wrong with my new code? Please let me know how to fix this.

Desired Output in both console and log.txt file

1. Before

Microsoft Windows [Version 10]
user01

2. After

I'd change this to print to a file what I want as well as the screen. As in, don't use that line where you wrote sys.stdout = log_file.

Just buckle down and write more lines of code to get what you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.