Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print to stderr in Python?

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.

like image 368
wim Avatar asked Apr 07 '11 00:04

wim


People also ask

How do you write to stderr in Python?

Use the sys.write() method can be used. sys. stderr. write() method prints the message as the given parameter to the stderr .

When can I print to 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.

What is stderr Python?

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")


1 Answers

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 
like image 103
MarcH Avatar answered Oct 10 '22 17:10

MarcH