Printing to Standard Error (stderr) in Python

By default, the print function prints a string to standard output (stdout), but you can specify a different output destination with the file argument. When you pass sys.stderr as this argument, the print function prints the string to standard error. You can also use the write method of sys.stderr to output, but unlike the print function, it does not automatically insert a newline.

How to output to standard error (stderr)

Pass standard error “sys.stderr” as the “file” argument of the print function. The following sample program uses the print function to output a string to standard error.
import sys

# Output to standard error (stderr)
print('An error has occurred.', file=sys.stderr)

If you use the write method of sys.stderr, it will look like this: unlike the print function, it does not automatically insert a newline, so we use ‘\n’ to output a newline.

import sys

# Output to standard error (stderr)
sys.stderr.write('An error has occurred.\n')

What is sys.stderr?

sys.stderr is a file object for reading and writing to standard error. For example, if you write to a file object that opens a text file, it writes the contents to that file. sys.stderr does not write to a file, it writes to standard error.

What is stderr?

Standard error is a place where messages such as errors or warnings that occur during program execution are output. Normally, standard error is displayed on the screen such as console or terminal, but you can also redirect or pipe it to another location. You can separate the output destination by printing normal program operation to standard output and errors to standard error. For example, you can save standard output to a file and display standard errors on the screen.

References

Test Environment