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.

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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.