There are several ways to write to stderr:
# Note: this first one does not work in Python 3 print >> sys.stderr, "spam" sys.stderr.write("spam\n") os.write(2, b"spam\n") from __future__ import print_function print("spam", file=sys.stderr)
That seems to contradict zen of Python #13 †, so what's the difference here and are there any advantages or disadvantages to one way or the other? Which way should be used?
†There should be one — and preferably only one — obvious way to do it.
Use the sys.write() method can be used. sys. stderr. write() method prints the message as the given parameter to the stderr .
It is good practice to redirect all error messages to stderr , while directing regular output to stdout . It is beneficial to do this because anything written to stderr is not buffered, i.e., it is immediately written to the screen so that the user can be warned immediately.
Python stderr is known as a standard error stream. It is similar to stdout because it also directly prints to the console but the main difference is that it only prints error messages. Example: import sys sys.stderr.write("This is error msg")
I found this to be the only one short, flexible, portable and readable:
# This line only if you still care about Python2 from __future__ import print_function import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs)
The optional function eprint
saves some repetition. It can be used in the same way as the standard print
function:
>>> print("Test") Test >>> eprint("Test") Test >>> eprint("foo", "bar", "baz", sep="---") foo---bar---baz
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