Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
11 views
in Python by (130 points)
edited by

There are many ways to write stderr:

 # Note: this first one does not work in Python 3

 print >> sys.stderr, "spam"

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

os.write(2, b"spam\n")

from __future__ import print_function

print("spam", file=sys.stderr)

That seems to contradict zen of Python #13 †, so what's the difference here and are there any advantages or disadvantages to one way or the other? Which way should be used?

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

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.

2 Answers

+2 votes
by (10.9k points)
edited by

You can refer to this code:

from __future__ import print_function

import sys

def eprint(*args, **kwargs):

print(*args, file=sys.stderr, **kwargs)

This is much easier and flexible than the other methods. Here, the eprint function behaves the same as the print function:

Ex-

>>>print(“Hello”)

Hello

>>>eprint(“Hello”)

Hello

0 votes
by (106k points)

import sys

sys.stderr.write()

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...