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.
Python3
import sysdef 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:

Example 2:Writing to the stdout
Python3
import sysdef 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:

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course



