开发者

Forward-compatible print statement in python 2.5

OK, maybe I'm just having an off day. This seems like something a lot of people must be asking, but Google is failing me horribly. The closest thing I found was this which doesn't exactly address this issue.

At work I run Arch 开发者_开发知识库on my desktop (which is python 3 by default), and Debian Lenny on my company's servers (which is python 2.5). I want to write a single python script that will work in both python 2 and 3. It's a very simple script, not much to it (mostly it just calls off to git using subprocess). Everything already works in both versions of python EXCEPT for the damned print statements.

Everyone out there seems to suggest the from __future__ import print_function trick. However this was introduced in python 2.6, and I'm stuck with 2.5.

So what are my options? How can I call print in both 2.5 and 3 using the same script? I was thinking maybe some kind of wrapper function, but this might not be the most "pythonic" way of doing things. Your thoughts? And no, upgrading the server to 2.6 isn't an option.

Thanks!


print("hi") works on both py 2 and 3 without from __future__ in py 2.5

alternatively, although not recommended:

import sys
sys.stdout.write("hi")


Why don't you just use the logging framework? It mitigates your issue, and is much better than print statements littered throughout the code.


This works for me:

import sys
if sys.version_info[0] == 2:
    def print_(*args):
        w = sys.stdout.write
        w( ', '.join(str(a) for a in args) )
        w( '\n' )
else:
    print_ = getattr(__builtins__, 'print')

If you need the full featured print functionality, you're better off using the print_ from six. In this case,

from six import print_
// replace all "print ..." by "print_(...)"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜