wim wim - 3 years ago 368
Python Question

How to print to stderr in Python?

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

import sys

print >> sys.stderr, 'spam'


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.

Answer Source

I found this to be the only one short + flexible + portable + readable:

from __future__ import print_function
import sys


def warning(*objs):
    print("WARNING: ", *objs, file=sys.stderr)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download