Are there situations in which sys.stdout.write() is preferable to print?
(Examples: better performance; code that makes more sense)
Are there situations in which sys.stdout.write() is preferable to print?
(Examples: better performance; code that makes more sense)
It is preferable when dynamic printing is useful, for instance, to give information in a long process:
import time, sys
Iterations = 555
for k in range(Iterations+1):
# Some code to execute here ...
percentage = k / Iterations
time_msg = "\rRunning Progress at {0:.2%} ".format(percentage)
sys.stdout.write(time_msg)
sys.stdout.flush()
time.sleep(0.01)
A difference between print and sys.stdout.write to point out in Python 3, is also the value which is returned when executed in the terminal. In Python 3, sys.stdout.write returns the length of the string whereas print returns just None.
So for example running following code interactively in the terminal would print out the string followed by its length, since the length is returned and output when run interactively:
>>> sys.stdout.write(" hi ")
hi 4
>>> sys.stdout.write(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1
Observing the example above:
sys.stdout.write won't write non-string object, but print will
sys.stdout.write won't add a new line symbol in the end, but print will
If we dive deeply,
sys.stdout is a file object which can be used for the output of print()
if file argument of print() is not specified, sys.stdout will be used
Are there situations in which sys.stdout.write() is preferable to print?
I have found that stdout works better than print in a multithreading situation. I use a queue (FIFO) to store the lines to print and I hold all threads before the print line until my print queue is empty. Even so, using print I sometimes lose the final \n on the debug I/O (using the Wing Pro IDE).
When I use std.out with \n in the string, the debug I/O formats correctly and the \n's are accurately displayed.
In Python 3 there is valid reason to use print over sys.stdout.write, but this reason can also be turned into a reason to use sys.stdout.write instead.
This reason is that, now print is a function in Python 3, you can override this. So you can use print everywhere in a simple script and decide those print statements need to write to stderr instead. You can now just redefine the print function, you could even change the print function global by changing it using the builtins module. Off course with file.write you can specify what file is, but with overwriting print you can also redefine the line separator, or argument separator.
The other way around is. Maybe you are absolutely certain you write to stdout, but also know you are going to change print to something else, you can decide to use sys.stdout.write, and use print for error log or something else.
So, what you use depends on how you intend to use it. print is more flexible, but that can be a reason to use and to not use it. I would still opt for flexibility instead, and choose print. Another reason to use print instead is familiarity. More people will now what you mean by print and less know sys.stdout.write.
In Python 2, if you need to pass around a function, then you can assign os.sys.stdout.write to a variable. You cannot do this (in the REPL) with print.
>import os
>>> cmd=os.sys.stdout.write
>>> cmd('hello')
hello>>>
That works as expected.
>>> cmd=print
File "<stdin>", line 1
cmd=print
^
SyntaxError: invalid syntax
That does not work. print is a magical function.
One of the differences is the following, when trying to print a byte into its hexadecimal appearance. For example, we know that the decimal value of 255 is 0xFF in hexadecimal appearance:
val = '{:02x}'.format(255)
sys.stdout.write(val) # Prints ff2
print(val) # Prints ff
You asked,
What is the difference between
sys.stdout.writeand
The best way I know how to explain it is to show you how to write print in terms of sys.stdout
Below I have provided three different ways to implement python's print function:
import sys
def print(*args, sep=" ", file=sys.stdout, end="\n") -> None:
# implementation One
file.write(sep.join(str(arg) for arg in args))
file.write(end)
def print(*args, sep=" ", file=sys.stdout, end="\n") -> None:
# Implementation 2
file.write(str(args[0]))
for arg in args[1:]:
file.write(sep)
file.write(str(arg))
file.write(end)
return
def print(*args, sep=" ", file=sys.stdout, end="\n") -> None:
# implementation 3
it = iter(args)
arg = next(it)
file.write(str(arg))
try:
while True:
arg = next(it)
file.write(sep)
file.write(str(arg))
except StopIteration:
pass
file.write(end)
return None