0

I have this piece of code:

class Logger(object):
def __init__(self):
    self.terminal = sys.stdout               
    self.log = open("filee.txt", "a")

def write(self, message):        
    self.terminal.write(message)
    self.log.write(message)  


def flush(self):        
    pass    

sys.stdout = Logger() 
print("Hello")
input("How are you today? ")
print("That's nice to hear!")

I want my output to both console and file be the following:

Hello
How are you today? "something that user enters"
That's nice to hear!

When I use mentioned piece of code only things inside of print() and before input() are printed out well. I want to point out that this piece of code works fine when I work ONLY with print() statement but I want everything related to input too be displayed properly. So, I wonder if anyone knows is there a way to achieve that functionality and what would it be?

kika123
  • 31
  • 9

1 Answers1

0

You can use logging to print anything to a log/text file like below:

import logging

#create your log file
logging.basicConfig(filename = 'path\\yourFileName.txt', format = '%(levelname)s:%(message)s', level = logging.INFO)

#print anything you want to your logfile at any point in the code
logging.info('Whatever you need to print')
Mit
  • 679
  • 6
  • 17
  • The thing is that I already have a file containing print() statements as well as input() statements. I want to print everything that shows up on console output(including input texts that say user what to input and values that user enters) to still remain printed on console output and also be printed to some .txt file – kika123 May 07 '20 at 10:10
  • have you tried `sys.stdout` ? – Mit May 07 '20 at 10:15
  • Sorry, it may sound confusing, I want to say that my .py file contains a lot of print and input statements so i want to do something that affects them directly – kika123 May 07 '20 at 10:17
  • I wrote that first piece of code where I redirected stdout to both terminal and file but thing is that it doesnt work properly when somwehere in code is input() – kika123 May 07 '20 at 10:18