The stderr in Python is short for Standard error is used to display information that is not intended to be part of the program’s regular output, for example, errors or exceptions. To print stderr in Python, we can use sys.stderr.write() function, besides this, there are other ways as well which we will discuss in this article.
Related: Python Read from stdin with Examples
1. Quick Examples of Printing stderr in Python
These examples will give you ideas to print to stderr, we will discuss each method in more detail in upcoming sections.
# Method 1: using sys.stderr.write()
import sys
sys.stderr.write(“This is an error message n”)
# Method 2: using print() – Output Standard Error
print(“This is an error message”, file=sys.stderr)
# Method 3: Print stderr with logging module
import logging
logging.basicConfig(level=logging.ERROR)
logging.error(“This is an error message”)
2. What is stderr in Python?
The term stderr stands for “standard error” and is used to display error messages, warnings, and diagnostic information that may occur during Python program execution.
stderr is one of the three standard streams in a Unix-like operating system (including Linux and macOS) that provides a way for programs to communicate with the user.
Unlike the regular output stream stdout, which displays regular output, stderr is used to print information that is not intended to be part of the program’s normal output and is often displayed separately from regular output.
3. Print to stderr in Python
Whenever you review experts’ code, you will probably find the sys.stderr.write() function in their codes. They use it to write a string to the standard error stream (stderr). This is a simple way to print error messages, warnings, and diagnostic information to the console or log file.
The write() function takes a single argument, a string containing the message to be printed, and returns the number of characters written.
Basic Syntax:
# sys module needs to be imported
import sys
# This will print to stderr
sys.stderr.write(“message to be printed to stderrn”)
Using the above basic syntax we can use the sys.stderr.write() function in any program to print to stderr. See the following example.
# Program that open “textfile.txt”
import sys
import os
filename = “testfile.txt”
# Handle the exceptions
try:
with open(filename, “r”) as f:
# Your code here
pass
except FileNotFoundError:
# Print error message to stderr
sys.stderr.write(f”Error: {filename} not found.n”)
# Exit with non-zero status code
sys.exit(1)
4. print() – Output Standard Error
You can use the print() function in Python to output messages to the console or to a file. By default, print() writes its output to the standard output stream (stdout). However, you can redirect its output to the standard error stream (stderr) by specifying the file argument as sys.stderr.
See the basic syntax of the print() function to print to stderr in Python:
# Using print() function to print to stderr
import sys
print(“message to be printed to stderr”, file=sys.stderr)
Using the same syntax we have developed our program that will print error using the print() function.
# Program for the illustration
import sys
# Calculate the total cost
def calculate_total_cost(price, quantity):
if price <= 0 or quantity <= 0:
# Print the error to stderr
print(“Error: invalid input”, file=sys.stderr)
return None
else:
total_cost = price * quantity
print(f”Total cost: ${total_cost}”, file=sys.stderr)
return total_cost
calculate_total_cost(-10, 5)
5. Print stderr with logging module
The logging module in Python provides a way to output log messages to various destinations, including the console, files, and network sockets. By default, the logging module writes Error log messages to the standard error stream (stderr).
import logging
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger()
logger.error(“This is an error message”)
The logging module is thread-safe, which means that you can use it in multi-threaded programs without causing race conditions or other synchronization issues.
It supports multiple log levels, including DEBUG, INFO, WARNING, ERROR, and CRITICAL. By default, It only log messages with a severity level of WARNING or higher.
6. Summary and Conclusion
In this article, you have learned how to print standard errors using stderr in python. We have discussed 3 different methods for printing stderr in python. I hope this article was helpful. If you have any questions, please leave them in the comment section.
Happy Coding!
The stderr in Python is short for Standard error is used to display information that is not intended to be part of the program’s regular output, for example, errors or exceptions. To print stderr in Python, we can use sys.stderr.write() function, besides this, there are other ways as well which we will discuss in this Read More Python, Python Tutorial, Python File Handling