from sys import stdout
stdout = open('file', 'w')
print 'test'
stdout.close()
does create the file, but it contains nothing.
I had to use
import sys
sys.stdout = open('file', 'w')
print 'test'
sys.stdout.close()
But wouldn’t the from ... import... automatically make the name available? Why do I still have to use sys.stdout instead of stdout?
The problem is this:
printis equivalent tosys.stdout.write().So when you do
from sys import stdout, the variablestdoutwon’t be used byprint.But when you do
it actually writes to
sys.stdoutwhich is pointing to thefileyou opened.Analysis
Conclusion
This works…