0

My program is quite big and I want all its print statements to be logged so as a result I implemented

F = open('testy.txt','w')
sys.stdout = F

if app.button_press() == True and app.return_data():
    data = app.return_data()
    main(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8])

F.close()

This is what I used to do with small programs with a few print statements but this program has few hundred of them I guess and as I run my program it freezes I think it has a lot of print statements and a memory overflow occurs therefore How could I log all my print statements to a .txt file without affecting the functionality of it?

2
  • 1
    Have you tried with flushing with sys.stdout.flush() ? Commented Aug 27, 2013 at 17:37
  • You should really not be doing this. Set up logging and configure it to log to stdout if you want to see it, and a file if you want to log to a file. Commented Aug 27, 2013 at 17:38

1 Answer 1

2

You shouldn't be using print statements for logging, nor should you be redirecting standard out (or any other standard stream) in production code. Rather, you should be using the logging module to write messages, and setting up whatever handlers, probably a file handler or rotating file handler in your case, that you need to record your log messages to the right place.

If you already have too much existing code printing log messages to refactor in one sitting, I'd suggest implementing logging, using it for all logging going forward, setting up a file-like object that shunts standard out to logging to capture existing log messages, then refactoring out all your print-based logging over time.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you provide an example because I've never used the logging module

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.