How do I print to stderr in Python?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping
--
Chapters
00:00 How Do I Print To Stderr In Python?
00:19 Answer 1 Score 660
00:42 Answer 2 Score 134
01:07 Accepted Answer Score 1599
01:29 Answer 4 Score 411
02:12 Thank you
--
Full question
https://stackoverflow.com/questions/5574...
--
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'}))