I am writing a program that should work with both python2 and python3. For this, I would like to have a function for writing to stderr that works with both versions of python.
Ideally, I think it would be something like:
def writeStdErr(message): if sys.version_info >= (3, 0): print(message, end = "", file = sys.stderr) else: sys.stderr.write(message)
the problem with this is that python2 is that printing is not a function, so I get
print(message, end = "", file = sys.stderr) ^ SyntaxError: invalid syntax
I could get rid of this by simply adding eval:
def writeStdErr(message): if sys.version_info >= (3, 0): eval('print(message, end = "", file = sys.stderr)') else: sys.stderr.write(message)
however, I do not like this decision; I think this is generally a bad idea to use eval.
Does anyone know something better / have a better solution?
EDIT:
For those who have the same problem in the future, the following things look:
def writeStdErr(message): sys.stderr.write(message)
or
from __future__ import print_function import sys def writeStdErr(message): print(message, file=sys.stderr)
Thanks to all the answers