Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function to write on stderr with python2 and python3

I'm writing a program that ought to work with both python2 and python3. For this, I would like to have a function to write to stderr that works with both python versions.

Ideal I think 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 that python2 is, that print isn't a function, so I get

    print(message, end = "", file = sys.stderr)
                       ^
SyntaxError: invalid syntax

I could get rid of this by just 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 dislike this solution; I think it's general a bad idea to use eval.

Does anyone knows something better/has a better solution?

EDIT:

For anyone having the same problem in future, the following things seem works:

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 answers

like image 384
quant Avatar asked Jun 15 '14 20:06

quant


1 Answers

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

from __future__ import print_function

That should be the first line of code (but could go after a shebang).

Another alternative 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 have implemented each one accordingly.

That is to answer your question, BUT, you can just use sys.stderr.write for both. The only difference is that in Python 3 it seems to return the number of characters written. If you do it on interactive mode:

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

You get an extra 5, but that is just the return value.

>>> a = sys.stderr.write('aaaa\n')
aaaa
>>> a
5
like image 70
Davidmh Avatar answered Jan 20 '23 12:01

Davidmh