83

How do I, in the main.py module (presumably), tell Python which interpreter to use? What I mean is: if I want a particular script to use version 3 of Python to interpret the entire program, how do I do that?

Bonus: How would this affect a virtualenv? Am I right in thinking that if I create a virtualenv for my program and then tell it to use a different version of Python, then I may encounter some conflicts?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jesuis
  • 1,926
  • 2
  • 17
  • 17

9 Answers9

65

You can add a shebang line the to the top of the script:

#!/usr/bin/env python2.7

But that will only work when executing as ./my_program.py.

If you execute as python my_program.py, then the whatever Python version that which python returns will be used.

In re: to virtualenv use: virtualenv -p /usr/bin/python3.2 or whatever to set it up to use that Python executable.

Tom Carrick
  • 5,287
  • 11
  • 48
  • 74
Jon Clements
  • 124,071
  • 31
  • 219
  • 256
  • 10
    To make this answer complete, it might be worth describing the appropriate she-bang syntax, given that the question is worded in a way that doesn't imply that knowledge. – JBentley Jun 15 '17 at 21:31
  • What if the path is too long for the shebang? It allows just 128 characters. Should we set an alias for python in some `install.py`? – Lukas Sep 09 '20 at 09:52
  • Can I debug this somehow? It doesn't work for me and I don't see why... Does it work on windows too? Seems like Unix syntax... – Brambor Jan 10 '21 at 17:14
56

Perhaps not exactly what you asked, but I find this to be useful to put at the start of my programs:

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")
Gravity Grave
  • 2,305
  • 1
  • 23
  • 35
  • Isn't the bracket style function call new to python3? Does this code work as expected in all versions of python? – TamaMcGlinn Apr 23 '20 at 15:01
  • 1
    @TamaMcGlinn Not sure exactly what you mean by that; the [0] means it's referencing the first entry in the array (which in this case means the first digit of the Python version, e.g. in 2.7.3 this would be 2), not making a function call. AFAIK this works in all versions of Python. – Gravity Grave Apr 24 '20 at 16:51
  • The reason I found out about the difference between python2 and python3 is trying to make `print "hello world"` compile. I think it's just the print statement itself that changed, hence my confusion. Thanks for clarifying that this works in all versions of Python since that's essential. – TamaMcGlinn Apr 24 '20 at 18:31
21

I would use the shebang #!/usr/bin/python (first line of code) with the serial number of Python at the end ;)

Then run the Python file as a script, e.g., ./main.py from the command line, rather than python main.py.

It is the same when you want to run Python from a Linux command line.

auspicious99
  • 2,413
  • 1
  • 26
  • 40
Andrew
  • 855
  • 11
  • 21
  • 7
    So, if I wanted python 2.7.3 I would use #!/usr/bin/python2.7.3 – jesuis Jun 23 '12 at 16:26
  • @MikeHalpin have a look at whats in your /usr/bin. You need to reference an existing executable. If you have 2.7.3 installed then I believe you would be correct. – Endophage Jun 23 '12 at 16:47
  • Not that there should be any reason to specify 2.7.3 specifically -- all the 2.X should be mostly compatible and 2.7.X fully. – Erik Jun 23 '12 at 19:02
  • yes, so like python2.7 filename.py for all/any python 2.7.x versions – geekidharsh Jul 27 '17 at 16:39
  • 2
    Note that this will not work if you execute the script as you normally do when you run a python script, i.e. by running `python ` form the terminal. – HelloGoodbye Jun 21 '18 at 11:33
  • @HelloGoodbye since you specified explicitly which python you are using by the `python` command (python --version), the shebang is ignored. This feature is useful only if you change script mode to executable. – Andrew Jun 22 '18 at 08:28
15

While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.

Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.

In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py

However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.

For example, you might run: C:\Python2.5.2\python.exe mymodule

Yet, the environment variables may point to the wrong version as such:

PYTHONPATH = D:\Python27

PYTHONLIB = D:\Python27\lib

Loads of horrible fun!

So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.

Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py

launch_mymodule.py

import sys
import subprocess
if sys.argv[2] == '272':
  env272 = {
    'PYTHONPATH': 'blabla',
    'PYTHONLIB': 'blabla', }
  launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)

if sys.argv[1] == '252'
  env252 = {
    'PYTHONPATH': 'blabla',
    'PYTHONLIB': 'blabla', }
  launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)

I have not tested this.

ljden
  • 151
  • 6
DevPlayer
  • 4,761
  • 1
  • 22
  • 19
  • 1
    Here is a MS batch script, non-virtualenv, safe pre-app-launch Python [version check](http://pastebin.com/aAuJ91FQ) – DevPlayer May 14 '15 at 14:41
  • @DevPlayer Excellent and explanatory BATCH script (in the link). Another `con` is that you actually have to write a custom python script for every version of python that you want to test for. This is not the same as the OP of using the script's preferred version of python. – Jesse Chisholm Jul 12 '18 at 16:04
0

You can't do this within the Python program, because the shell decides which version to use if you a shebang line.

If you aren't using a shell with a shebang line and just type python myprogram.py it uses the default version unless you decide specifically which Python version when you type pythonXXX myprogram.py which version to use.

Once your Python program is running you have already decided which Python executable to use to get the program running.

virtualenv is for segregating python versions and environments, it specifically exists to eliminate conflicts.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • So if I want to use python 2.7.3 to run a program, I would in the terminal write: python 2.7.3 main.py? – jesuis Jun 23 '12 at 16:28
  • Also, about virtualenv: yes, but if the virtualenv is setup for all the dependencies of one python version and then I use another to run the program it houses, wouldn't there be the possibility of conflicts? – jesuis Jun 23 '12 at 16:29
  • read the documentation on `virtualenv` it has all the details about what problem it solves. –  Jun 23 '12 at 17:17
0

For those using pyenv to control their virtual environments, I have found this to work in a script:

#!/home/<user>/.pyenv/versions/<virt_name>/bin/python

DO_STUFF
Chris Hanning
  • 113
  • 1
  • 7
-1

put at the start of my programs its use full for work with python

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

This code will help full for the progress

-1

I had this problem and just decided to rename one of the programs from python.exe to python2.7.exe. Now I can specify on command prompt which program to run easily without introducing any scripts or changing environmental paths. So i have two programs: python2.7 and python (the latter which is v.3.8 aka default).

-2

While working with different versions of Python on Windows,

I am using this method to switch between versions.

I think it is better than messing with shebangs and virtualenvs

1) install python versions you desire

2) go to Environment Variables > PATH

(i assume that paths of python versions are already added to Env.Vars.>PATH)

3) suppress the paths of all python versions you dont want to use

(dont delete the paths, just add a suffix like "_sup")

4) call python from terminal

(so Windows will skip the wrong paths you changed, and will find the python.exe at the path you did not suppressed, and will use this version after on)

5) switch between versions by playing with suffixes

GMG
  • 1