0

I am going off of this thread.

First, I added import sys to the top of my file. The print statement that I want to log is inside of an if/else statement, specifically in the else portion. It looks like this:

else:
    sys.stdout = open('logfile', 'w')
    print("hi")

This does create a file called logfile in the same directory as the .py file, but it is emtpy and does not include "hi".

NaN
  • 643
  • 1
  • 8
  • 21
  • why don't you use the file argument for the print function? Also do you close the file at the end? – MSeifert Jan 07 '18 at 21:12
  • @MSeifert Can you elaborate on what you mean by using the file argument, and no I do not close it at the end. – NaN Jan 07 '18 at 21:17
  • 1
    Could be that an unclosed file doesn't flush and doesn't really write them to the file (depends a bit on the OS). Might want to test if it works if you close it. – MSeifert Jan 07 '18 at 21:18
  • Additionally to what @MSeifert says, you should verify you actually want to redirect standard out. Logging in this manner will disable your ability to output anything to the user prompt, the conventional target of stdout. You could just create the file with open, write whatever you want, and leave stdout alone. Closing the file is important though, with either technique. – schulmaster Jan 07 '18 at 21:23
  • 1
    @schulmaster I don't need any output to the user prompt, as I'm running this file automatically with cron on a remote server. Sometimes, I'd like to be able to "check in" and see the logs to see if it's running properly. – NaN Jan 07 '18 at 21:57

0 Answers0