How do I print to stderr in Python?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island
--
Chapters
00:00 Question
00:25 Accepted answer (Score 1482)
00:52 Answer 2 (Score 646)
01:25 Answer 3 (Score 358)
02:20 Answer 4 (Score 188)
02:59 Thank you
--
Full question
https://stackoverflow.com/questions/5574...
Answer 2 links:
http://docs.python.org/3.0/whatsnew/3.0....
Answer 3 links:
[logging]: https://docs.python.org/3.8/library/logg...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #printing #stderr
#avk47
ACCEPTED ANSWER
Score 1599
I found this to be the only one short, flexible, portable and readable:
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
The optional function eprint saves some repetition. It can be used in the same way as the standard print function:
>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz
ANSWER 2
Score 660
import sys
sys.stderr.write()
Is my choice, just more readable and saying exactly what you intend to do and portable across versions.
Edit: being 'pythonic' is a third thought to me over readability and performance... with these two things in mind, with python 80% of your code will be pythonic. list comprehension being the 'big thing' that isn't used as often (readability).
ANSWER 3
Score 411
Python 3:
print("fatal error", file=sys.stderr)
Python 2:
print >> sys.stderr, "fatal error"
Long answer
print >> sys.stderr is gone in Python3.
http://docs.python.org/3.0/whatsnew/3.0.html says:
Old:
print >> sys.stderr, "fatal error"
New:print("fatal error", file=sys.stderr)
For many of us, it feels somewhat unnatural to relegate the destination to the end of the command. The alternative
sys.stderr.write("fatal error\n")
looks more object oriented, and elegantly goes from the generic to the specific. But note that write is not a 1:1 replacement for print.
ANSWER 4
Score 134
For Python 2 my choice is:
print >> sys.stderr, 'spam'
Because you can simply print lists/dicts etc. without convert it to string.
print >> sys.stderr, {'spam': 'spam'}
instead of:
sys.stderr.write(str({'spam': 'spam'}))