To get around syntax errors, you will 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 recommended that you try to maintain compatibility between python3 and older versions. However, here are a few ways to discover which version of python is being used:
While sys.hexversion not particularly human-friendly, it will work in a wide variety of versions of python since it was added back to version 1.5.2:
import sys if sys.hexversion == 0x20505f0: print "It version 2.5.5!"
You can 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 can use the platform module, although this was introduced in python 2.3 and will not be available in older versions (if 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."
source share