Search code examples
pythonversionvirtualenv

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?


Solution

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