Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 318
jesuis Avatar asked Jun 23 '12 15:06

jesuis


People also ask

How do I switch between versions in Python?

Now any time you want to run particular version, just change its order (path) and move it to top of other version, and then restart the cmd and type python this time, you will see that only that particular version of python will run.

What is __ version __ in Python?

It provides a __version__ attribute. It provides the standard metadata version. Therefore it will be detected by pkg_resources or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345).


2 Answers

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.

like image 117
Jon Clements Avatar answered Oct 11 '22 14:10

Jon Clements


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.") 
like image 24
Gravity Grave Avatar answered Oct 11 '22 12:10

Gravity Grave