john johnson
john johnson

Reputation: 730

Writing to console and log file for extended amount of time (Python)

I am using this code to log stdout to console and file. This code works and will output "test" to my console.log file. But , if i run my entire script/program and move the writer.close() to the end of my program termination, all the prints that occur in my other code (which could take mins to run) are never written to the log file? is there some time limit on this method? what can i do so that i can run my script/program that might run for 20 mins and log both to the console and to a log file. Again my example below works fine on a quick print then close the writer . but if i print several lines for minutes at time then go to close the writer i don't get any errors but yet the console.log file it empty?

Import sys

class MyWriter:

    def __init__(self, stdout, filename):
        self.stdout = stdout
        self.logfile = open(filename, 'a')

    def write(self, text):
        self.stdout.write(text)
        self.logfile.write(text)

    def close(self):
        self.stdout.close()
        self.logfile.close()

    def flush(self):
        pass


writer = MyWriter(sys.stdout, os.getcwd() + '\\logs\\console.log')
sys.stdout = writer

print("test")

writer.close()
sys.exit()

Upvotes: 0

Views: 80

Answers (1)

cs95
cs95

Reputation: 402872

You'll need to flush your streams once you write to them. You can do that using f.flush() inside write:

self.stdout.flush()  
self.logfile.flush()

Upvotes: 1

Related Questions