Home » Python » How to print to stderr in Python 2?

How to print to stderr in Python 2?

Posted by: admin August 15, 2018 Leave a comment

Questions:

I’ve come across at least three ways to print to stderr:

 import sys

 print >> sys.stderr, 'spam'

 sys.stderr.write('spam\n')

 from __future__ import print_function
 print('spam', file=sys.stderr)

It seems to contradict zen of Python #13 , so what’s the preferred way to do it? Are there any advantages or disadvantages to one way or the other?

There should be one — and preferably only one — obvious way to do it.

Answers: