杰瑞科技汇

Python如何用print输出到stderr?

Of course! In Python, the standard way to print to standard error (stderr) is by using the built-in sys module. Here’s a complete guide, from the simplest method to more advanced and recommended practices.

Python如何用print输出到stderr?-图1
(图片来源网络,侵删)

The Short and Direct Answer

Use the sys.stderr object from the sys module.

import sys
print("This message goes to standard output (stdout).", file=sys.stderr)

Understanding Standard Streams (stdout vs. stderr)

Before diving into code, it's crucial to understand the difference between stdout (Standard Output) and stderr (Standard Error).

  • stdout (Standard Output): This is the default stream for normal program output. It's where print() sends data by default. When you run a script in a terminal, stdout is usually displayed directly on your screen. It's also commonly used to pipe output to other programs.

  • stderr` (Standard Error): This stream is intended for diagnostic messages—errors, warnings, and other system-related information. By default, it also goes to your screen, but it can be redirected separately from stdout. This is extremely useful for logging and debugging.

    Python如何用print输出到stderr?-图2
    (图片来源网络,侵删)

Why is this separation important? Imagine you have a script that processes a list of files and outputs the results to a file. You'd redirect stdout to a file like this: python my_script.py > results.txt

If an error occurs (e.g., a file is not found), you want that error message to appear on your screen, not get mixed into the results.txt file. Because error messages go to stderr, they will still be displayed in your terminal, while the normal output is safely saved to the file.


How to Print to stderr

Here are the most common methods.

Method 1: The sys.stderr Object (Classic)

This is the most straightforward and direct way. You can pass the sys.stderr object as the file argument to the print() function.

Python如何用print输出到stderr?-图3
(图片来源网络,侵删)
import sys
print("This is an error message.", file=sys.stderr)

Example: Let's run this from the command line and see the redirection in action.

Create a file named test_stderr.py:

import sys
print("This is normal output to stdout.")
print("This is an error message to stderr.", file=sys.stderr)

Now, run it and redirect stdout to a file:

python test_stderr.py > output.log

After running this, your terminal will show:

This is an error message to stderr.

And the file output.log will contain only:

This is normal output to stdout.

This perfectly demonstrates the separation of the two streams.

Method 2: The logging Module (Highly Recommended)

For any real application, the logging module is the best practice. It's more flexible, powerful, and provides features like log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), timestamps, and easy configuration.

By default, the logging module sends messages of level WARNING and higher to stderr.

import logging
# The basicConfig() call sets up a simple logger.
# level=logging.DEBUG means all messages will be handled.
logging.basicConfig(level=logging.DEBUG)
# These will go to stderr by default
logging.debug("This is a debug message.")
logging.info("This is an informational message.")
logging.warning("This is a warning message.")
logging.error("This is an error message.")
logging.critical("This is a critical message.")

Output when you run this script:

DEBUG:root:This is a debug message.
INFO:root:This is an informational message.
WARNING:root:This is a warning message.
ERROR:root:This is an error message.
CRITICAL:root:This is a critical message.

All of this output is being sent to stderr.

You can easily configure logging to send different levels to different places (e.g., INFO and above to a file, ERROR and above to the console).

Method 3: The warnings Module

The warnings module is specifically for issuing warning messages. These are also typically sent to stderr.

import warnings
warnings.warn("This is a warning, it will go to stderr.", UserWarning)

Writing Directly to sys.stderr

While using print(file=sys.stderr) is common, you can also write to sys.stderr directly using its write() method. This is useful if you want to avoid the automatic newline character (\n) that print() adds.

import sys
sys.stderr.write("This is an error message without a newline at the end.")
sys.stderr.flush() # It's good practice to flush the buffer

Output:

This is an error message without a newline at the end.

Notice there's no line break after the message.


Summary: Which Method Should You Use?

Method When to Use Pros Cons
print(file=sys.stderr) Quick and simple scripts, when you just need to send a specific line to stderr. Simple, easy to remember. Lacks structure and features like log levels.
sys.stderr.write() When you need fine-grained control over the output (e.g., avoiding newlines, building a message character by character). Direct, no extra formatting. More verbose, requires manual flushing.
logging Module Recommended for almost all applications. Best Practice. Provides levels, timestamps, formatting, and easy redirection to files/networks. Requires a bit more initial setup.

Final Recommendation:

  • For a quick script or a simple script, print(file=sys.stderr) is perfectly fine.
  • For any serious application, library, or long-running script, use the logging module. It will save you a lot of time and trouble in the long run.
分享:
扫描分享到社交APP
上一篇
下一篇