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





4 Answers

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).

/usr/bin/env working windows

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.




Not quite the same situation, but the company I work for has an app that can run Python scripts (among its many features). After numerous support issues involving Python installations on various platforms, we decided to just install our own Python interpreter with the app. That way we know exactly where it is installed and what version it is. This approach may be too heavyweight for your needs (the Python package is only about 10% of our app's bits) but it definitely works.




As I understand different distros will be in different locations in your drive. Here are some suggestions that come to mind -

  1. You could use UNIX alias to create shortcuts pointing to the different distros. Eg: alias py2="/usr/bin/python2.X". So when you run your script you could use py2 xx.py
  2. Or other way could be to modify your PYTHON_PATH environment variable.
  3. Or if I am not wrong there is a provision in sys module to get the current python version number. You could get that & deal appropriately.

This should do it...




I believe this will do what you want, namely test for a non-specific version of Python less than 3.x (as long as it doesn't contain a from __future__ import print_function statement).

try:
    py3 = eval('print')
except SyntaxError:
    py3 = False

if py3: exit('requires Python 2')
...

It works by testing to see if print is a built-in function as opposed to a statement, as it is in Python3. When it's not a function, the eval() function will raise an exception, meaning the code is running on a pre-Python 3.0 interpreter with the caveat mentioned above.




Related