Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print vs stderr

Are there any specific advantages or disadvantages to either print or stderr?

like image 200
Tyler Avatar asked Jun 02 '09 14:06

Tyler


People also ask

What is print to stderr?

Stderr is the standard error message that is used to print the output on the screen or windows terminal. Stderr is used to print the error on the output screen or window terminal. Stderr is also one of the command output as stdout, which is logged anywhere by default.

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.

How do I print to stderr in python 2?

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


2 Answers

print can print on any file-like object, including sys.stderr.

print >> sys.stderr, 'Text' 

The advantages of using sys.stderr for errors instead of sys.stdout are:

  • If the user redirected stdout to a file, she still sees errors on the screen.
  • It's not buffered, so if sys.stderr is redirected to a log file there are less chance that the program may crash before the error was logged.

This answer written with Python 2 in mind. For Python 3, use print('Text', file=sys.stderr) instead.

like image 181
Bastien Léonard Avatar answered Sep 22 '22 13:09

Bastien Léonard


They're just two different things. print generally goes to sys.stdout. It's worth knowing the difference between stdin, stdout, and stderr - they all have their uses.

In particular, stdout should be used for normal program output, whereas stderr should be reserved only for error messages (abnormal program execution). There are utilities for splitting these streams, which allows users of your code to differentiate between normal output and errors.

like image 33
Dan Lew Avatar answered Sep 22 '22 13:09

Dan Lew