The version of Linux I am working on has python 2.6 by default, and we installed 2.7 on it in a separate folder.
If I want to run a .py script, how do I tell it to use 2.7 instead of the default?
解决方案
Sorry for "stealing" answers, but I feel that there is a little bit of chaos here.
There are different ways to achieve that, it depends on at what level the decision is taken.
System Level
[Credit to @WoLy]
Use the update-alternatives feature of the system. Specifically, use
$ update-alternatives --config python
and you can choose the specific version.
Result: Once you do this, everything that uses "python" will use the python2.7 binary. This will happen in the whole system, for all users.
User Level
This is a little bit trickier. Credit to @TheFlyingProgrammer
The basic approach would be to change the .bashrc file in order to change the path and/or add an alias. Problem is if you are relying on the "shebang" of the file:
#!/usr/bin/python
This kind of file will be unaffected of your changes. However:
#!/usr/bin/env python
or executions like
$ python name_of_script.py
will use the interpreter of choice (the one forced at the .bashrc file).
Result: The owner of the modified .bashrc file will use, by default, the interpreter of choice. But some sheband will behave differently. So it is a bit trickier. So, be cautious.
Script Level
[Credit to @Anony-Mousse]
The "shebang" approach, modifying the first line. The idea is using the full path in the first line of the python source file:
#!/usr/bin/python2.7
You can use python, python2 or python2.7 and you will be more or less specific in the version. The problem would be if you want it to be portable. A similar approach would be to use full specification of version but without path:
#!/usr/bin/env python2.7
Note that if the PATH is not correctly set, this won't work. This gives some power to the user (when setting the PATH). You can, for instance, choose #!/usr/bin/env python2 to force some Python 2.x flavour, but maybe the specific binary will change from user to user.
In addition to that, keep in mind that if you plan to use virtual environments, using /usr/bin/env python is advisable (if I'm not mistaken).
Result: Well, it depends whether you use the env binary or not. But, in any case, you are putting the semantic in the file, which makes sense in many cases (e.g. if there is an incompatibility, it is at the script level).
Execution Level
[Credit to @Prune]
This is the simplest approach:
$ /path/to/your/python/bin/python2.7 my_script.py
You change, for this specific execution, which binary will be using (the Python interpreter ignores the shebang, because it is a comment).
Result: You override all other choices by cherry-picking your Python binary. Very good approach to test behaviour, but not very maintainable or shareable.