How do I print to stderr in Python?

Better Stack Team
Updated on February 3, 2023

In Python, you can use the print() function to print to stderr by passing the value file=sys.stderr as a keyword argument. For example:

import sys

print("This is an error message", file=sys.stderr)

This will print the string "This is an error message" to the standard error stream.

Alternatively, you can use the sys.stderr.write() method to write a string to the standard error stream:

import sys

sys.stderr.write("This is an error message\n")

This will have the same effect as the print() function above.

Got an article suggestion? Let us know
BY NC SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Explore more