How to print to stderr and stdout in Python?



How to print to stderr and stdout in Python?

In Python, whenever we use print() the text is written to Python’s sys.stdout, whenever input() is used, it comes from sys.stdin, and whenever exceptions occur it is written to sys.stderr. We can redirect the output of our code to a file other than stdout. But you may be wondering why one should do this? The reason can be to keep a log of your code’s output or to make your code shut-up i.e. not sending any output to the stdout. Let’s see how to do it with the below examples.

Example 1: Writing to stderr instead of stdout.

import sys
def print_to_stderr(*a):
    # Here a is the array holding the objects
    # passed as the argument of the function
    print(*a, file = sys.stderr)
print_to_stderr("Hello World")

Output:
python-stderr

 

Example 2:Writing to the stdout

import sys
def print_to_stdout(*a):
    # Here a is the array holding the objects
    # passed as the argument of the function
    print(*a, file = sys.stdout)
print_to_stdout("Hello World")

Output:
python-stdout

Last Updated on November 13, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs