How do I use different Python version in venv from standard library? (Not virtualenv!)

George Sovetov picture George Sovetov · Mar 27, 2014 · Viewed 22.7k times · Source

I have installed Python 3.4.0 and created virtual environment with python -m venv myenv. How can I change Python version in my virtual environment? Documentation says:

Each virtual environment has its own Python binary (allowing creation of environments with various Python versions) and can have its own independent set of installed Python packages in its site directories.

UPDATE

Please, note that I ask about venv from standard library, not about virtualenv. Let me provide some links.

I don't see something like a --python flag in venv.

Are venv and virtualenv absolutely similar? Is venv is so unpopular and no one uses it so that virtualenv remains the standard?

Answer

Rotareti picture Rotareti · Nov 6, 2016

On Linux/Mac you can easily install multiple versions of Python next to the main one and you can use the venv package from the standard library to create virtual environments from each version >= 3.3.

Create venv

$ python3.3 -m venv myvenv_foo  # Create a python3.4 venv named 'myvenv_foo'
$ python3.4 -m venv myvenv_bar  # Create a python3.4 venv named 'myvenv_bar'
$ python3.5 -m venv myvenv_baz  # Create a python3.5 venv named 'myvenv_baz'
# etc...

Activate venv

source myvenv_foo/bin/activate  # Activates venv 'myvenv_foo'

Deactivate venv

deactivate

Notice: python vs pythonX.X

If you have multiple Python versions installed, you can access each one by adding the version num to the command e.g. python3.5, python3.6, etc. But keep in mind that when you activate a venv, you bind it to the clean/versionless python command, for as long as it's activated. E.g:

$ python -V # Use the *clean* 'python' command to show the main version of the OS.
Python 2.7.6 
$ python3.5 -m venv myvenv_foo # Create a new venv from 'python3.5'.
$ source myvenv_foo/bin/activate # Activate venv.
$ python -V # The *clean* 'python' command is now bound to your activated venv.
Python 3.5.2 
$ deactivate  # Deactivate venv.
$ python -V  # Now the *clean* command is bound back to the main version.
Python 2.7.6 

Note

I suggest using Pipenv to create/handle virutal environments over the venv package.

From the offical docs:

Managing multiple virtual environments directly can become tedious, so the dependency management tutorial introduces a higher level tool, Pipenv, that automatically manages a separate virtual environment for each project and application that you work on.