In Python, the stderr stands for “standard error”. It is utilized to display/print information that may occur during program execution and is not meant to be part of the program’s output, like exceptions, errors, warnings, etc. Users can display that information separately on a console or in a specific file using the stderr. It gets the error information from the program and provides an efficient way for a particular program to communicate with users.
Print to stderr in Python
To print to stderr in Python, the following methods can be utilized:
- Method 1: Print to stderr Using “sys.stderr.write()” Function
- Method 2: Print to stderr Using “print()” Function With “file=sys.stderr” Parameter
- Method 3: Print to stderr Using Logging Module
Method 1: Print to stderr Using “sys.stderr.write()” Function
The “sys.stderr.write()” function is a file object that can be used to write a string to stderr. This is a convenient approach to display warnings, error messages, etc, to the console.
Syntax
import sys
sys.stderr.write("This is an error message")
This will show the following output:
The above syntax can be used in any Python program to print to stderr.
Example
We have a “testFile.txt” file and we will open it in read mode. We are using the try-except block for the exception handling and printing to stderr using the “sys.stderr.write()” function:
import sys
file_name = "testFile.txt"
try:
with open(file_name, "r") as f:
pass
except FileNotFoundError:
sys.stderr.write(f"ERROR: {file_name} NOT FOUND.\n")
sys.exit(1)
Here:
- The “try” block will test the code block. It will check whether the desired file exists for reading or not.
- The “except” block will handle the error and show the specific error message.
As the specified file does not exist, it has displayed the error message to the console:
Method 2: Print to stderr Using “print()” Function With “file=sys.stderr” Parameter
The “print()” function shows/displays the output messages either on the console or to a specific file. By default, the “print()” function writes output to the stdout. Although, users can redirect output to the stderr (standard error stream) by specifying the file argument as “sys.stderr”.
Syntax
import sys
print("This is an error message", file=sys.stderr)
The following output will be shown to the console:
Users can also redirect the output to the specific file by specifying it as seen below:
import sys
sys.stderr = open('errorFile.txt', 'w')
print("This is an error message", file=sys.stderr)
By doing so, the “errorFile.txt” file will be created and and it will show the output in it:
Note: In the case of Python 2, use the following syntax:
import sys
print >> sys.stderr, 'Hello world'
Now, check out the following example to see how this syntax can be used in the Python program to print to stderr.
Example
We are using the “file=sys.stderr” parameter in the “print” function to redirect the output to the specified file:
import sys
def total_cost(pr, quant):
if pr <= 0 or quant <= 0:
sys.stderr = open('myErrorFile.txt', 'w')
print("Error: Invalid Input", file=sys.stderr)
else:
t_cost = pr * quant
print(f"Total cost: ${t_cost}", file=sys.stderr)
return t_cost
total_cost(-6, 3)
In the case of invalid input, the “if” statement will be true and its block of code will be executed. This will create the “myErrorFile.txt” file and show the error message in it:
As the “if” statement was true, the specified file was created and the error message can be seen in it:
In the case of valid input, the “else” statement will be true and it will show the following output in the console as well as in the “myErrorFile.txt” file:
Method 3: Print to stderr Using Logging Module
The logging module is a part of the standard Python library that can be used to print to stderr. It offers a way to emit log messages from the program and write them to stderr. It can also be utilized in multi-threaded programs without any problem. Moreover, it supports various log levels, such as INFO, ERROR, DEBUG, WARNING, etc.
Syntax
The basic syntax of using a logging module to print to stderr is given below:
import logging
logging.basicConfig(filename="Error.log",
filemode='w',
force=True)
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
logger.error("IT'S AN ERROR MESSAGE")
Here:
- “import logging” imports the “logging” module.
- “logging.basicConfig()” is used to create and configure a logger including filename, file mode, etc.
- “logging.getLogger()” creates a logger object.
- “logger.setLevel(logging.ERROR)” sets the logger’s level to ERROR which means that it will print the error messages.
- “logger.error()” method displays an error message to stderr (“Error.log” file).
This will create the “Error.log” file and show the error message in it as seen below:
Let’s consider the following example and use the above syntax in the Python program to print to stderr.
Example
Here, we are using the logging module in a simple if else Python program to calculate the total cost with respect to price and quantity. In the case of invalid input, the “if” statement will be true and its block of code will be executed, otherwise, the “else” statement will be executed:
import logging
logging.basicConfig(filename="newError.log",
filemode='w',
force=True)
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
def total_cost(pr, quant):
if pr <= 0 or quant <= 0:
logger.error("Invalid Input")
else:
t_cost = pr * quant
print(f"Total cost: ${t_cost}")
return t_cost
total_cost(-9, 3)
As the “if” condition is true, the “newError.log” file has been created and the error message has been redirected to it as seen below:
The “newError.log” file shows the following error message:
In the case of valid input, the “else” statement will be true and it will show the output on the console as seen below:
We have efficiently explained all the methods to print to stderr in Python.
Conclusion
In Python programming language, different methods can be utilized to print to stderr. Users can use the “sys.stderr.write()” function, “print()” function with the “file=sys.stderr” parameter, or use the logging module. However, the “print()” function with the “file=sys.stderr” parameter is the most efficient and effective method to handle large numbers of errors as it redirects the error messages to the specific file. Using the logging module is an advanced method that is useful in complex scripts or larger applications. This blog has exemplified different methods to print stderr in Python.