How to print a line to STDERR and STDOUT in Python?

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
Answered by dtivl.

In Python 3:

To print to STDOUT

print("your message")

To print to STDERR

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

To use Python 3 style print in Python 2:

In Python 3:

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.stdout)

Leave a Reply

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