Related Articles

Related Articles

How to print to stderr and stdout in Python?
  • Last Updated : 17 May, 2020

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

python-stderr

Example 2:Writing to the stdout



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

python-stdout

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :