Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the following python code does not print to file

Tags:

python

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?

like image 701
Qiang Li Avatar asked Jan 27 '13 06:01

Qiang Li


People also ask

Can Python print to file?

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.

Why Python is not giving output?

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 .


1 Answers

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()
like image 157
ATOzTOA Avatar answered Oct 06 '22 00:10

ATOzTOA