Skip to content

Instantly share code, notes, and snippets.

@mt3o
Created May 14, 2019 13:21
Show Gist options
  • Save mt3o/e7358000ffbf410d6d6abdcf9e661a8c to your computer and use it in GitHub Desktop.
Save mt3o/e7358000ffbf410d6d6abdcf9e661a8c to your computer and use it in GitHub Desktop.
#Here's some sample code based on the book Learning Python by Mark Lutz that addresses your question:
import sys
temp = sys.stdout # store original stdout object for later
sys.stdout = open('log.txt', 'w') # redirect all prints to this log file
print("testing123") # nothing appears at interactive prompt
print("another line") # again nothing appears. it's written to log file instead
sys.stdout.close() # ordinary file object
sys.stdout = temp # restore print commands to interactive prompt
print("back to normal") # this shows up in the interactive prompt
#Opening log.txt in a text editor will reveal the following:
#testing123
#another line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment