Is there a standard way to make sure a python script will be interpreted by python2 and not python3? Is there a standard way to make sure a python script will be interpreted by python2 and not python3? python python

Is there a standard way to make sure a python script will be interpreted by python2 and not python3?


http://docs.python.org/library/sys.html#sys.version_info

using the sys module you can determine the version of python that is running and raise an exception or exit or whatever you like.

UPDATE:

You could use this to call the appropriate interpreter. For example, set up a small script that does the checking for you, and use it in the shbang. It would check the python version running, and if not what you want, looks for one you want. Then it would run the script in that version of python (or fail if nothing good was found).


This is a bit of a messy issue during what will be a very long transition time period. Unfortunately, there is no fool-proof, cross-platform way to guarantee which Python version is being invoked, other than to have the Python script itself check once started. Many, if not most, distributions that ship Python 3 are ensuring the generic python command is aliased by default to the most recent Python 2 version while python3 is aliased to the most recent Python 3. Those distributions that don't should be encouraged to do so. But there is no guarantee that a user won't override that. I think the best practice available for the foreseeable future is to for packagers, distributors, and users to assume python refers to Python 2 and, where necessary, build a run-time check into the script.


Using sys.version_info you can do a simple value test against it. For example if you only want to support version 2.6 or lower:

import sysif sys.version_info > (2,6):    sys.exit("Sorry, only we only support up to Python 2.6!")