How do I tell a Python script to use a particular version How do I tell a Python script to use a particular version python python

How do I tell a Python script to use a particular version


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.


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

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


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.