Printing a Line to STDERR and STDOUT in Python

Posted on In QA

In Python, how to print a string as a line to STDOUT? That is, the string and the newline character, nicely?

And similarly, how to print the line to STDERR?

In Python, to print a string str with a new line to STDOUT:

print str

In Python to print a line to STDERR:

import sys
print >> sys.stderr, "your message here"

An example:

$ python 2>/tmp/stderr
>>> import sys
>>> print >> sys.stderr, "your message here"
>>> exit()
$ cat /tmp/stderr 
Python 2.7.5 (default, Nov  6 2016, 00:28:07) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
your message here

In Python 3:

To print to STDOUT

print("your message")

To print to STDERR

print("your message", file=sys.stderr)

To use Python 3 style print in Python 2:

In Python 2:

To print to STDOUT

from __future__ import print_function

print("your message")

To print to STDERR

from __future__ import print_function

print("your message", file=sys.stderr)

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

2 comments

Leave a Reply

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