How to use python print to stderr

How to use python print to stderr : Know Various Cases

We can use python print to stderr by parameter in “file=sys.stderr” with print() function in Python 3.  We can use a separator with it as a param. But in python 2, print function works without parenthesis.


Python print to stderr Example-

In python 3, we can use the below syntax for stderr.

print("fatal error", file=sys.stderr)



In python 2, We can use the below syntax for print to stderr. We also need to import sys module as strerr is part of this module.

import sys
print >> sys.stderr, "Provide your msg"

Using print to stderr inside a function-

Case 1: Single Parameter

We can define any custom function where we can use this in the function body. Let’s see the below syntax-

def fun(*msg): 
  print(*msg, file = sys.stderr) 
fun("Here is the msg") 
print to stderr custom function example
print to stderr custom function example


In the above example, We are using *msg for passing parameter str.

Case 2: Multiple Parameter

It is quite similar to the above section with changes in the number of parameters. Here we will see how can we leverage *args, **kwargs. Firstly let’s see an implementation.

def fun(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

fun("A", "B", "C", sep="--")
print to stderr custom function multiple parameter
print to stderr custom function multiple parameter

Here we have multiple strings as *args and sep=”–” as **kwargs. We can add more kwargs as per the requirement and choices.



Stderr, also known as the standard error. Different system process runs and prints Stderr on error occurrence. This really helps in dubbing the application.  It provides a strong information base flow for analysts. Stderr  and Stdout both works in the same way but with different purposes.

It’s not a replacement for the log module. So please be careful while designing the system traces. Now I hope you are clear with syntax. Specially the syntax difference for it in Python 2 and Python 3. Please comment below for any queries. We love to interact with our readers. You may also add some thoughts as enhancement of this article too.


Data Science Learner Team



Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner