9

To create a virtual environment using virtualenv you can specify the Python release and point version like so:

virtualenv --python=python3.6 .venv

How can I achieve this using Python3's venv module (as in python3 -m venv .newvenv)? According to the documentation using venv is the recommended way to create virtual environments but I didn't see how I can choose a virtual environement with a specific Python version.

mjkrause
  • 406
  • 1
  • 7
  • 14

3 Answers3

14

Run venv with whatever Python installation you want to use for the new virtual environment. For example, if you would run your Python 3.6 installation with python3.6, then

python3.6 -m venv whatever

would be how you create a Python 3.6 virtual environment.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 5
    Great. `python3.5 -m venv ...` works without a problem (that came with the distribution), but `python3.6 -m venv whatever` returns `Error: Command '['/home/someuser/dev/somedir/whatever/bin/python3.6', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1.` - not exactly helpful, but it does create a functional Python 3.6 environment nevertheless. – mjkrause Feb 14 '19 at 23:26
  • 2019 and I also have the same issue. @mjkrause were you able to resolve the problem? – Carlos Ferreira Nov 30 '19 at 15:25
  • @CarlosFerreira Solution to a similar problem can be found https://stackoverflow.com/questions/69830431/how-to-use-python3-10-on-ubuntu. – chanp Mar 01 '23 at 17:26
  • Thanks @chanp I've resolved the situation by using PyEnv to define envs with specific Python versions while keep it isolated from the system installation. – Carlos Ferreira Mar 02 '23 at 23:21
7

I thought to add to this answer when one is using pyenv. In my workflow I use pyenv to have multiple python versions but not to manage virtualenvs. I rather have my python virtual environment in the project's root. With pyenv one can install multiple python versions by running pyenv install 3.8.10 and after that pyenv install 3.9.0. When you run pyenv versions you should get something similar to this

  system
* 3.8.10 (set by /Users/<user>/.pyenv/version)
  3.8.10/envs/python-test.venv
  3.9.0

When working on a project and choosing what python version should be used in that project you can do the following.

$ mkdir my_project && cd my_project
$ pyenv global <version>
$ python --version // should be the version you set as global
$ python -m venv .venv
$ source .venv/bin/activate
redeemefy
  • 4,521
  • 6
  • 36
  • 51
3

I was able to avoid error mentioned in the comments by using the option --without-pip. Then after activating the venv, I installed pip manually with the get-pip.py script.

jidicula
  • 3,454
  • 1
  • 17
  • 38
darrenc
  • 31
  • 1