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
?
Python's print() function is typically used to display text either in the command-line or in the interactive interpreter, depending on how the Python program is executed. However, we can change its behavior to write text to a file instead of to the console.
One of the reasons of why your Python script does not show any output is because it buffers stdout and stderr steams instead of printing them. This also can happen if you execute the Python script from a CI/CD pipeline (e.g. using Jenkins, Gitlab-CI, TeamCity, etc.) or if you run it using a Dockerfile .
The problem is this: print
is equivalent to sys.stdout.write()
.
So when you do from sys import stdout
, the variable stdout
won't be used by print
.
But when you do
import sys
print 'test'
it actually writes to sys.stdout
which is pointing to the file
you opened.
Analysis
from sys import stdout
stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the terminal
stdout.close()
import sys
sys.stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the file
sys.stdout.close()
Conclusion
This works...
from sys import stdout
stdout = open('file', 'w')
stdout.write('test')
stdout.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With