[파이썬] `sys.stderr`: 표준 에러 출력

In Python, the sys.stderr object is used for outputting error messages and diagnostics. It provides a way to redirect the error output to a specific destination, allowing you to handle and display error messages in a more controlled manner.

Using sys.stderr

To use sys.stderr, you need to import the sys module at the beginning of your Python script. Here’s an example:

import sys

try:
    # Some code that may raise an exception
    result = 10 / 0
except ZeroDivisionError as e:
    # Output the error message to stderr
    print("An error occurred:", str(e), file=sys.stderr)

In the above code snippet, we import the sys module and then attempt to divide 10 by 0, which raises a ZeroDivisionError. We catch the exception using a try-except block and use print to output the error message to sys.stderr. This ensures that the error message is displayed as an error and not as a regular output.

Redirecting sys.stderr

By default, sys.stderr points to the console or terminal where the script is executed. However, you can redirect it to a file or a different output stream if needed. This can be useful when you want to log error messages to a file or send them to another component or system.

To redirect sys.stderr, you can assign a different file-like object to it. Here’s an example:

import sys

# Open a file for error logging
error_log = open("error.log", "a")

# Redirect stderr to the error log file
sys.stderr = error_log

try:
    # Some code that may raise an exception
    result = 10 / 0
except ZeroDivisionError as e:
    # Output the error message to stderr
    print("An error occurred:", str(e), file=sys.stderr)

# Close the error log file
error_log.close()

In this example, we open a file named “error.log” in append mode ("a") and assign it to the error_log variable. We then redirect sys.stderr to point to this file by assigning error_log to sys.stderr. Now, any error messages printed to sys.stderr will be logged to the file instead of being displayed on the console.

Conclusion

The sys.stderr object in Python provides a convenient way to handle and display error messages and diagnostics. By redirecting sys.stderr to a specific destination, you can control where error messages are logged or displayed. This can be useful for debugging, error logging, and building robust applications.