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, 2017 by dtivl (2,500 points)

2 Answers

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

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)
answered Dec 15, 2017 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Related questions

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

...