Answer to the question is : There are different way to print stderr in python but that depends on
1.) which python version we are using
2.) what exact output we want.
The differnce between print and stderr's write function:
stderr : stderr (standard error) is pipe that is built into every UNIX/Linux system, when your program crashes and prints out debugging information (like a traceback in Python), it goes to the stderr pipe.
print: print is a wrapper that formats the inputs (the input is the space between argument and the newline at the end) and it then calls the write function of a given object, the given object by default is sys.stdout, but we can pass a file i.e we can print the input in a file also.
Python2:
If we are using python2 then
>>> import sys
>>> print "hi"
hi
>>> print("hi")
hi
>>> print >> sys.stderr.write("hi")
hi
Python2 trailing comma has in Python3 become a parameter, so if we use
trailing commas to avoid the newline after a print, this will in
Python3 look like print('Text to print', end=' ') which is a syntax
error under Python2.
http://python3porting.com/noconv.html
If we check same above sceario in python3:
>>> import sys
>>> print("hi")
hi
Under Python 2.6 there is a future import to make print into a
function. So to avoid any syntax errors and other differences we
should start any file where we use print() with from future import
print_function. The future import only works under Python 2.6 and
later, so for Python 2.5 and earlier you have two options. You can
either convert the more complex print to something simpler, or you can
use a separate print function that works under both Python2 and
Python3.
>>> from __future__ import print_function
>>>
>>> def printex(*args, **kwargs):
... print(*args, file=sys.stderr, **kwargs)
...
>>> printex("hii")
hii
>>>
Case: Point to be noted that sys.stderr.write() or sys.stdout.write()
( stdout (standard output) is a pipe that is built into every
UNIX/Linux system) is not a replacement for print, but yes we can use
it as a alternative in some case. Print is a wrapper which wraps the
input with space and newline at the end and uses the write function to
write. This is the reason sys.stderr.write() is faster.
Note: we can also trace and debugg using Logging
#test.py
import logging
logging.info('This is the existing protocol.')
FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset", extra=d)
https://docs.python.org/2/library/logging.html#logger-objects