Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 738
Chris Eberle Avatar asked Jan 20 '23 11:01

Chris Eberle


2 Answers

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")
like image 74
Pwnna Avatar answered Jan 22 '23 02:01

Pwnna


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

like image 20
Sam Dolan Avatar answered Jan 22 '23 02:01

Sam Dolan