+4  A: 

In order to get around syntax errors you would have to use conditional imports, if you want to mix syntax between versions 2 and 3.

# just psuedocode
if version is x:
   import lib_x # contains version x implementation
else:
   import lib_y # contains version y compatible implementation

It is not advisable to try to maintain compatibility between python3 and older versions. That said, here are several ways of detecting the version of python being used:

While not particularly human friendly, sys.hexversion will work across the widest variety of python versions, since it was added back in version 1.5.2:

import sys
if sys.hexversion == 0x20505f0:
    print "It's version 2.5.5!"

You should be able to get version information from sys.version_info (added in python 2.0):

import sys
if sys.version_info[0] == 2:
    print "You are using version 2!"
else:
    print "You are using version 1, because you would get SyntaxErrors if you were using 3!"

Alternatively you could use the platform module, though that was introduced in python 2.3, and would not be available in older versions (assuming you even care about them):

try:
    import platform
    if platform.python_version().startswith('2'):
        print "You're using python 2.x!"
except ImportError, e:
    print "You're using something older than 2.3. Yuck."
vezult
I suppose it is as simple as this. Of course it must be either print or print(). Thanks!
Hamish Grubijan
sys.version_info is a tuple containing the version X.Y.Z not a function.
cschol
Just in case, I do care about older versions. By the way, your second edit will not work on Python 3.x :(
Hamish Grubijan
The second edit will not work in any Python version. sys.version_info has always been a tuple and not a function. His code is just wrong.
cschol
Since which version is this available?
Hamish Grubijan
First available in version 2.0.
cschol
Please do not mix Python 2 and 3. Please use the 2to3 tool and do it properly.
S.Lott
+3  A: 

FYI, if you ever want to port 2.x scripts to 3.x, you can use 2to3 source conversion tool.

ghostdog74
Is it spotless?
Hamish Grubijan
@hamish : not exactly... but it automates most of the process... see: http://www.diveintopython3.org/porting-code-to-python-3-with-2to3.html
Aviral Dasgupta
Please see a first edit when it appears.
Hamish Grubijan
@Hamish Grubijan: Yes. It's "spotless". If you write your Python 2 correctly (which is very easy to do) The 2to3 tool will convert to Python 3 and you do not have any confusion or any thinking or any maintenance. It is the best way to have code that runs in both environments. You write (and maintain) Python 2 and use the 2to3 tool to create your Python 3.
S.Lott
+1  A: 

The sys module also contains the version info (first available in version 2.0):

import sys

if sys.version_info[0] == 2:
    print "You are using Python 2.x"
cschol
+1  A: 

If the only issue is that you want to use the right print statement to avoid syntax errors, you can avoid the problem altogether by using the print() function in Python 2.6:

if sys.version_info[0:2] == (2,6):           # Or you could use try/except here
    from __future__ import print_function
print("Now you can use print as a function regardless of whether you're on 2.6 or 3.x!")

Of course, if you also want to support earlier versions of Python, this won't work.

mipadi
I want to do a number of things. This is food for thought. Thanks.
Hamish Grubijan
It looks like you want an *unconditional* `from __future__ import print_function` here. That version would still work fine on 2.6, but it wouldn't break with 2.7 like yours does. (This is what I mean when I say trying to handle different versions by checking the version information is fragile.)
Mike Graham
+3  A: 
  • If you want to maintain a codebase that works with Python 2 and 3, you wouldn't try to make code that will run in both, which will be awkward and ugly and bugprone, you would write in Python 2 and use 2to3 to convert. (You can also write in Python 3 and use 3to2 to convert, but I believe that tool is less mature.) 2to3 is not perfect, but making Python 2 code that can be converted by it makes tons more sense than making Python 2 code that will run in a Python 3 interpretter.
  • Another option is Cython, a Python-like language that can be used to create C extension modules. Cython modules can be used with Python 2 and 3.
  • When you support multiple versions of Python, it is generally better to directly check for the capability you want rather than to check a version number. Checking version numbers directly is fragile and indirect.

    For example, if I wanted code that would work with Python pre-2.5, I would say:

    try: 
        any
    except NameError:
        def any(iterable):
            for item in iterable:
                if item:
                    return True
            return False
    

    (note that this is prettymuch the only reason to catch NameError). Similarly, library availability would be checked by catching ImportError.

  • If you want a script to remember what version it is from, like you say, don't bother trying to support multiple versions at all. Put the proper version number binary in the shebang line and run the script based on that.

Mike Graham
+1: Use 2to3, that's what it's for. Write Python 2 that converts properly and don't try to mix syntax.
S.Lott
+2  A: 

On Linux, Mac etc, you should use the standard first line:

#!/usr/bin/env python2

or

#!/usr/bin/env python2.6

or

#!/usr/bin/env python3

On Windows, having such a first line is useful from a documentation point of view, even if Windows doesn't use it to choose the interpreter.

Craig McQueen