How to print to stderr and stdout in Python

Hello techies, Today we are going to learn about how to print to stdout and std err.
In this tutorial, we will try to cover all about stderr and stdout using python.

Why do we need them ?
Often programmers want to keep track all about the error that occurred and console outputs, So we can use stderr and stdout to write all errors and console outputs to dedicated files.

How to print to stderr and stdout in Python

The stderr and stdout are file objects which are used by python interpreter for standard output and standard errors.

1.  stderr

We will return stderr in 2ways:

  •  Using stderr in print statement
  •  Using stderr.write() function

Using stderr in print statement

import sys 

# stderr
print("Error generated in print statement",file=sys.stderr)


Output

Error generated in print statement

Using stderr.write() function

import sys
# using write function from stderr
sys.stderr.write("Error generated through stderr file handle")

Output

Error generated through stderr file handle.

2. stdout

We will return stdout in 2ways

  • Using  print statement
  • Using stdout.write() function

Using print statement

# using print statement to print to stdout
print("printing through print statement")

Output

printing through print statement

Using stdout.write() function

import sys
#stdout
# sys.stdout.write("printing through stdout statement\n")

Output

printing through stdout statement
  • while using stdout.write function to print the information we have to explicitly use newline character at the end.

Finally, We will try to implement writing console outputs and errors in to respective files.

Implementation

import sys

# stdout
sys.stdout = open('console_output.txt', 'a')

# stdout
sys.stderr = open('console_errors.txt', 'a')

print("This is standard output") # print to stdout

print("This is an error", file=sys.stderr)# Print to stderr

# Close the files
sys.stdout.close()
sys.stderr.close()

Explanation

  • We have assigned the standard errors and standard output to two different files in append mode.
  • If file doesn’t exist it will create one.
  • Then errors and output statements will be automatically written in their respective files.

 

 

Leave a Comment

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

Scroll to Top