When you issue a print statement such as above, you typically also have to describe where exactly you want the printing to happen. By default, this happens in the standard output (or stdout) channel which is usually your monitor or screen. To be explicit and understand that this is what is happening, you can specify:
This program will give the same output as before.
How to print to stderr
Let us suppose you are writing a division program to take two numbers as input and output a message. Successful program execution results are typically displayed on stdout whereas error messages are displayed on stderr.
Note how in the above program the two print statements have different destinations. When you use repl.it you can see that these channels are different by the way repl highlights the results. A correct execution leads to:
An incorrect execution leads to:
Such messages sent to stderr can be collected in a separate file in a specific location. In fact this is how error messages in various programs, e.g., browsers, are collected so that when something goes wrong we can debug them by inspecting the error log.
Using sys.stderr.write() to print to stderr
An alternative way to print to stderr is to use the write() method provided as part of the sys package. Here is the above program rewritten using this approach:
It produces the same output:
Note that this approach, unlike the print command, does not automatically add a newline so an additional write will continue from where it left off. So you will need to update the program as follows:
The output is:
What is the difference between print() and write() to stderr?
One key difference between these two approaches is that sys.stderr.write() is limited in that it can only output string messages. Suppose, in addition to outputting the helpful division-by-zero message above we also wish to reproduce the divisor and dividend, we try:
Interestingly, the first “Err: Divisor is zero” message is printed by us to stderr and the remaining lines are also printed to stderr (but by the Python interpreter). To be able to print lists, the print command is more versatile:
The output will now be:
You have learnt all about the Python stderr channel and how you can use it to output error messages, warnings, and other useful information in the course of your program execution. Next time you interact with a program you can use your understanding to distinguish between messages sent to stdout versus those sent to stderr.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.