python shebang - Is there a standard way to make sure a python script will be interpreted by python2 and not python3?
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.
Is there a standard way to make sure a python script will be interpreted by python2 and not python3? On my distro, I can use #!/usr/bin/env python2 as the shebang, but it seems not all distros ship "python2". I could explicitly call a specific version (eg. 2.6) of python, but that would rule out people who don't have that version.
It seems to me that this is going to be increasingly a problem when distros will start putting python3 as the default python interpreter.
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 sys if sys.version_info > (2,6): sys.exit("Sorry, only we only support up to Python 2.6!")
Depends on how you're distributing it, I guess.
If you're using a normal
setup.py file to manage your distribution, have it bomb out if the user is trying to install it in Python 3.
Once it's installed, the shebang of the console script created by (say) setuptools will likely be linked to the specific interpreter used to install it.
If you're doing something weird for your installation, you can in whatever installation script you're using look for python interpreters and store a choice. You might first check whether whatever is called "python" is a 2.x. If not, check for "python2.7", "python2.6", etc to see what's available.
You can use the autotools to pick a Python 2 interpreter. Here is how to do that. Guaranteeing a correct shebang may be tricky to do elegantly; here is one way to do that. It may be easier to simply have a light Bash wrapper script,
wrapper.sh.in that looks something like:
#!/bin/bash PYTHON2="@[email protected]" #That first link enables this autotool variable "$PYTHON2" "[email protected]" #Call the desired Python 2 script with its arguments
wrapper.sh (after a
./wrapper.sh my_python2_script.py --an_option an_argument