import sys #1
idlestdout = sys.stdout #2
outfile = open('outfile.txt','w') #3
sys.stdout = outfile #4
print 'hello world' #5
outfile.flush() #6
outfile.close() #7
sys.stdout = idlestdout #8
How this works - Line by Line
Note that this code redirects the standard output from a file back to any IDE, not just idle.
import sys #1
This imports the sys module which comes standard
idlestdout = sys.stdout #2
This defines the variable idlestdout as the current output. You need to do this so that Python later knows what to redirect its output back to.
outfile = open('outfile.txt','w') #3
This defines the variable outfile as a file called "outfile.txt" that we will be writing to.
sys.stdout = outfile #4
This redirects the standard output to the file defined in line #3
print 'hello world' #5
This prints "hello world" to the standard output memory, or in this case, the outfile
outfile.flush() #6
This writes all of the pending text (line #5) to the outfile
outfile.close() #7
This closes the outfile file
sys.stdout = idlestdout #8
This redirects the sys.stdout back to the IDE.
No comments:
Post a Comment