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?

asked Jun 5 by dtivl (2,500 points)

1 Answer

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 Jun 5 by dtivl (2,500 points)
How to flush STDOUT buffer in Python? asked Sep 6 by Eric Z Ma (43,400 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...