Print to STDERR and STDOUT in Python

In this lesson, I’ll show you how to print the value to standard error (STDERR) or standard output (STDOUT) in Python.

The print statement and function will check whether a value is a string and display it, otherwise, it converts it to a string first.

STDOUT in Python 2

You can use the print statement to the standard output indicating that in the code, but you can also use just print and value will be printed to standard output by default.

This will give us the following result.

None of these statements return error with the int value, because print it works as a wrapper that automatically converts a value to a string.

STDERR in Python 2

If you try to print a message to standard error and then print a message to standard output, the first message displayed in a console will be standard output and the second standard error, even if STDERR is first in code.

STDOUT in Python 3

The previous code won’t work in Python 3, because print there is a function and not a statement.

In Python 3, you can indicate stdout as the second parameter of the print function.

This code will return 11 twice.

In Python 3, you can also use the write function to write to standard output.

This code will return the following result.

The write function returned an error, because it doesn’t convert non-string values to string as print does.

If you change the variable from int to string, all messages will return text to standard output.

The code will return this result every time it executes.

STDERR in Python 3

Modify the code, by changing STDOUT to STDERR.

Run it and check the results. It can give you different output each time you run it.

Example 1

Example 2

Example 3

This means that the standard error messages are sometimes executed before other parts of code and sometimes after code.

In the third example, you can see that both messages are displayed in one code. This happened because the write function doesn’t print the new line as print does.