Function to write to stderr using python2 and python3

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

+6
source share
1 answer

If you are using Python2.7, you can import the new behavior:

 from __future__ import print_function 

This should be the first line of code (but can go after shebang).

Another option compatible with earlier versions is to create it in an external module.

 if sys.version_info >= (3, 0): from print_sderr3 import writeStdErr else: from print_stderr2 import writeStdErr 

where you implemented each of them accordingly.

To answer your question BUT , you can just use sys.stderr.write for both. The only difference is that in Python 3, it seems, the number of characters written is returned. If you do this interactively:

 >>> sys.stderr.write('aaaa\n') aaaa 5 

You get an extra 5 , but this is only the return value.

 >>> a = sys.stderr.write('aaaa\n') aaaa >>> a 5 
+6
source

Source: https://habr.com/ru/post/970876/


All Articles