My problem is similar as redirect prints to log file
When I started coding with Python last year, I didn't know about logging
till now.
The problem is the code is getting bigger and bigger.
I've been trying solutions given, but none of them work properly as this code contains input()
, print()
, and os.system()
The closest solution was from shx2
in his answer to How to duplicate sys.stdout to a log file?
Let's say this is the code
import os, sys
class multifile(object):
def __init__(self, files):
self._files = files
def __getattr__(self, attr, *args):
return self._wrap(attr, *args)
def _wrap(self, attr, *args):
def g(*a, **kw):
for f in self._files:
res = getattr(f, attr, *args)(*a, **kw)
return res
return g
sys.stdout = multifile([ sys.stdout, open('log.txt', 'w') ])
name = input("\nWhat is your name: ")
print("Your name is",name)
age = input("\nHow old are you: ")
print("You're ",age)
print("\nYour IP Address is: ")
os.system('ipconfig | findstr IPv4')
Console Output
C:\>python script.py
What is your name: ABC
Your name is ABC
How old are you: 10
You're 10
Your IP Address is:
IPv4 Address. . . . . . . . . . . : 127.0.0.1
C:\>
print
output from the console was redirected to log.txt
without any problem, but not the input
and os.system
log.txt
output
What is your name: Your name is ABC
How old are you: You're 10
Your IP Address is:
Would it be possible to get everything (exactly the same) on the console to log.txt
?