Are there situations in which sys.stdout.write() is preferable to print?
(Examples: better performance; code that makes more sense)
Join Stack Overflow to learn, share knowledge, and build your career.
|
See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement In Python 3.x,
See https://docs.python.org/3/library/functions.html#print In Python 2.6+,
Update: There is a little difference between the print function and the print statement (and more generally between a function and a statement) pointed by Bakuriu in comments. In case of error when evaluating arguments:
|
|||||||||||||||||||||
|
For example I'm working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end="" to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.
|
|||
|
|
|
There's at least one situation in which you want When you want to overwrite a line without going to the next line, for instance while drawing a progress bar or a status message, you need to loop over something like
And since print adds a newline, you are better off using |
|||
|
|
|
Here's some sample code based on the book Learning Python by Mark Lutz that addresses your question:
Opening log.txt in a text editor will reveal the following:
|
|||||||||
|
If you're writing a command line application that can write to both files and stdout then it is handy. You can do things like:
It does mean you can't use the |
||||
|
|
After finishing developing a script the other day, I uploaded it to a unix server. All my debug messages used This is a case where you may need |
|||||||||
|
|
"print" first converts the object to a string (if it is not already a string). It will also put a space before the object if it is not the start of a line and a newline character at the end. When using stdout, you need to convert the object to a string yourself (by calling "str", for example) and there is no newline character. So
is equivalent to:
|
|||||||||||||||||
|
|
In 2.x, the
|
|||
|
|
sys.stdout.write()andprint(and/or why Python has both) is a perfectly reasonable question and does not need examples. OP did not say the command syntax was confusing. – smci Jan 20 '15 at 22:07