1677

How do I create a virtual environment for a specified version of Python?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Ulf
  • 17,492
  • 5
  • 19
  • 13
  • 11
    Just mentioning that you can do this using virtualenvwrapper too. – bias May 28 '10 at 03:25
  • 21
    Worth noting that in python 3, there is a built-in virtualenv equivalent: [venv](https://docs.python.org/3/library/venv.html). – naught101 Sep 01 '14 at 12:47
  • 6
    Is it not possible to switch python version in the current environment without creating a new environment? – Charlie Parker Aug 28 '16 at 23:38
  • https://www.youtube.com/watch?v=N5vscPTWKOk This video recommended in virtualenv documentation goes over the entire process step. – AnandShiva Dec 26 '20 at 08:58
  • 2
    whenever i'm using sudo inside an already created virtual env to install some utilities like docker-compose it is picking the root python and pip version(3.6), not the one with which the virtual environment was created(3.7). Why is this so? but when I'm doing the python version inside virtual env. it is coming correctly (3.7). – y_159 Sep 21 '22 at 11:51
  • This worked for me: py -3.9 -m venv .venv – Paul Beloff Nov 11 '22 at 09:37

41 Answers41

1972

NOTE: For Python 3.3+, see The Aelfinn's answer below.


Use the --python (or short -p) option when creating a virtualenv instance to specify the Python executable you want to use, e.g.:

virtualenv --python="/usr/bin/python2.6" "/path/to/new/virtualenv/"
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 178
    I figured I'd mention that this works for virtualenvwrappers too: mkvirtualenv -p python2.6 env – bias May 28 '10 at 03:24
  • 102
    I'm missing something here - doesn't this require that 2.6 already be installed on the system? I thought the *point* of virtualenv was that I could have a version of python other than the main one (in my case, 2.4 on CentOS). I was assuming I could install virtualenv, *then* install Python 2.6 under it for packages in the env to make use of? – John C May 24 '11 at 14:31
  • 51
    @John yes, you are. That isn't the point of virtualenv: the point of that is to create a sandboxed environment for Python. You will need to install that version first - you can install it locally for your user, though. – Daniel Roseman May 24 '11 at 14:47
  • 10
    @JohnC You can use pythonbrew to install alternative pythons. – ashwoods Dec 01 '11 at 22:03
  • 1
    @John C Yes (to Daniel's point), it seems the point of virtualenv is to take a global Python executable and maintain separate _sets of packages_. This is different from, say, Ruby's RVM, which is designed to keep a separate version of Ruby as well as a set of gems in one environment. – Derek Morrison May 19 '13 at 00:38
  • 77
    If you are a tad lazy: `virtualenv -p \`which python2.6\` ` – blaze Oct 16 '13 at 00:57
  • 5
    pythonbrew is no longer maintained, use pyenv instead. – DanH Mar 26 '15 at 09:51
  • 2
    When using pip after the duel installation do you have to specify which python pip is to use? (example 'python2.7 -m pip install SomePackage # specifically Python 2.7') or will pip in that virtualenv automatically know which one to use? – user1807271 Jan 12 '16 at 17:32
  • 3
    The `-p / --python` option also works with `virtualenvwrapper` functions, like `mkproject`. – Chris Johnson Aug 05 '16 at 20:37
  • See my answer below for an equivalent solution using environment variables. That approach means you don't have to remember to use `-p`. – Chris Johnson Aug 05 '16 at 20:58
  • 5
    Is there no solutions that switches between python versions without requiring to create a new virtual environment? – Charlie Parker Aug 28 '16 at 22:27
  • 2
    virtualenv -p $(which python3) – Michael Nov 20 '16 at 15:30
  • If you are in Ubuntu 16.04 or other and getting errors please see the accepted answer here - https://stackoverflow.com/questions/37495375/python-pip-install-throws-typeerror-unsupported-operand-types-for-retry It works and does not harm the OS (usually any uninstall of python in ubuntu is bad) – Alex Punnen Nov 14 '17 at 13:54
  • Perfect, it works, if you want to keep always the brew version make sure you use path "/usr/local/bin/python", thank you – Radek Aug 01 '18 at 18:17
  • if not sure, go like virtualenv --python=`which python3` venvdir # can be existing one, even with pycharm project loaded in the ide –  Dec 26 '18 at 01:01
  • II like to add `virtualenv --no-site-packages --python=/usr/bin/python3.6 .` – m.a.d.cat Apr 21 '19 at 06:20
  • use `which python` or `which python3` to find the path of the python. – Gokul Aug 05 '19 at 13:18
  • 1
    This is the best solution even for Python 3 or newer. – Rahul Bali May 09 '20 at 09:52
  • 1
    If you are a lot lazy, just: ` -m venv ` – Stefan Dec 08 '20 at 19:48
  • this will work work for Windows https://stackoverflow.com/a/22793687/15435022 – mattsmith5 Apr 26 '21 at 01:20
596

Since Python 3, the documentation suggests creating the virtual environment using:

python3 -m venv "my_env_name"

Also, if we want a particular version of python, lets say 3.6, then we can install as

python3.6 -m venv "my_env_name"

Make sure to install the referenced version of python along with your existing system python. For example, if the installed version in your system is python 3.8 only, you will encounter an error stating that "Command 'python3.6' not found".

Obsolete information

The pyvenv script can be used to create a virtual environment:

pyvenv "/path/to/new/virtual/environment"

Deprecated since Python 3.6.

STerliakov
  • 4,983
  • 3
  • 15
  • 37
The Aelfinn
  • 13,649
  • 2
  • 54
  • 45
  • 17
    Glad you pointed that out, it needs more promotion. One minor nit: they are now advocating running it as `python3 -m venv ` to prevent needing stub scripts for everything. – Paul Everitt Nov 20 '16 at 16:08
  • 7
    In fact the `pyvenv` script is [deprecated](https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features) in Python 3.6+, though the underlying `venv` module itself is not. So use `python 3 -m venv ` as @PaulEveritt says. – RichVel Dec 20 '16 at 08:47
  • 6
    Be warned that `pyvenv` or `python3 -m venv ...` do NOT install the `python-config` script. This means that even after activating your Python3 environment the system-wide `python-config` will be invoked with confusing consequences. See this bug report from 2011 https://github.com/pypa/virtualenv/issues/169 and my question https://stackoverflow.com/questions/42020937/why-pyvenv-does-not-install-python-config?rq=1 – András Aszódi Feb 23 '18 at 11:16
  • 2
    "Please note that `venv` does not permit creating virtualenv with other versions of Python." -- Are you sure this is true? It seems to work just fine for me if I create it with a specific Python version, e.g. `python3.5 -m venv ` (provided that I have that version of Python available). – Dominick Pastore May 29 '19 at 16:04
  • 46
    Confirming that @Nick's observation works: The way to create a `venv` with a specific Python version is by using that version when setting it up. For example: `python3.5 -m venv venv` – tanius Oct 21 '19 at 21:35
  • 12
    It's still possible to use a different python version with `venv`. Instead of providing an argument, like with `virtualenv`, you just be sure to use the appropriate python version to run `venv`. Example with `py` the python launcher: `py -3.3 -m venv my_venv` will create a virtual environment using python 3.3. – cowlinator May 12 '20 at 20:22
  • 1
    What does the "-m" mean? – BenjaminK May 06 '21 at 07:49
  • What I did was I ran the command after navigating to and using the `python.exe` of the different installed version, and that created a venv according to that python version associated with the run `python.exe`, as desired. – Rafs Jul 23 '21 at 10:47
  • @tanius So if you need to switch versions after creating the venv you need to delete the existing venv? – AlxVallejo Aug 08 '21 at 23:27
  • @BenjaminK [`-m` stands for ``](https://docs.python.org/3/using/cmdline.html#cmdoption-m) that will be executed. – Dmitriy Zub Dec 14 '21 at 07:17
  • additional note to previous comments. assume I am going to use "python 3.10". linux version is `python3.10 -m venv env` while windows version is `py -3.10 -m venv env` – Talha Sengul Jan 31 '23 at 20:14
  • Another additional note. On certain OS, there is a required step to do before invoke `python3.X -m venv`: a user is required to install python3.X-venv via APT first. See [a problem when trying to run `python3.10 -m venv` Ubuntu 20.04](https://stackoverflow.com/questions/69830431/how-to-use-python3-10-on-ubuntu) – chanp Mar 01 '23 at 16:39
  • "Make sure to install the referenced version of python along with your existing system python." How to do this safely without messing up with your existing system python? – FNia May 16 '23 at 00:58
224

These are the steps you can follow when you are on a shared hosting environment and need to install & compile Python from source and then create venv from your Python version. For Python 2.7.9. you would do something along these lines:

mkdir ~/src
wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
cd Python-2.7.9
mkdir ~/.localpython
./configure --prefix=$HOME/.localpython
make
make install

virtual env

cd ~/src
wget https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz#md5=0ed59863994daf1292827ffdbba80a63
tar -zxvf virtualenv-15.0.2.tar.gz
cd virtualenv-15.0.2/
~/.localpython/bin/python setup.py install
virtualenv ve -p $HOME/.localpython/bin/python2.7
source ve/bin/activate   

Naturally, this can be applicable to any situation where you want to replicate the exact environment you work and deploy on.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
zzart
  • 11,207
  • 5
  • 52
  • 47
  • 5
    Could you elaborate on why to do it that way: Why install python locally? And more importantly **why install virtualenv using the python version you want to use with it**? – lajarre Oct 08 '12 at 19:46
  • 21
    sure. If you are on virtual hosting environment and the server provides older versions of python that you are not happy with - that was my case scenario. Also if you happen to develop projects on different servers and you want to replicate these environments on your local machine.... Virtualenv creates hard links to python libs . so it's really important with version of python you are using to install and create Virtualenv from. – zzart Oct 11 '12 at 20:15
  • 9
    Or if you are like me and am on a locked down machine at work with no sudo privileges. Local copies of libraries, SQL databases, languages and compilers galore! Thanks! – zachd1_618 Jan 24 '13 at 18:03
  • 6
    Under virtualenv 1.9.1, I had to use `~/.localpython/bin/virtualenv` instead of just `virtualenv` for setup to complete without errors. In addition, use `source ve/bin/activate` instead of `source activate`. – Saul Apr 10 '13 at 07:40
  • 3
    Another reason to do this would be to try out betas before they go main to make sure your projects and their dependencies still work without risking breaking your package management by clobbering something and leaving dangling files all over the place. I like this answer. – RobotHumans Dec 29 '13 at 14:02
  • the line 'tar -zxvf Python-2.7.2.tar.gz' should be 'tar -zxvf Python-2.7.2.tgz' – snuggles Jun 04 '15 at 16:12
  • Good answer! There may be other packages that need to be installed (for support of certain "bits" as the python make calls them). I found this page had a good list of most, if not all, of them: https://renoirboulanger.com/blog/2015/04/upgrade-python-2-7-9-ubuntu-14-04-lts-making-deb-package/ – Joe D'Andrea Feb 11 '16 at 21:08
  • Much simpler alternative is to [use pyenv](http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/43828665#43828665) which includes virtualenv support. – RichVel May 07 '17 at 07:25
  • 1
    @zzart I had use `./configure --prefix=$HOME/.localpython ` but getting configure: error: in `/home/education/public_html/Python-3.5.2': configure: error: no acceptable C compiler found in $PATH – Surya prakash Patel Aug 11 '18 at 01:56
  • This worked for me, I´m using CENTOs 7, and an alternative python 3.8.14 compiled from source, my particular path for python was: `/usr/local/bin/python3.8` thank you. – aletelecomm Sep 28 '22 at 13:57
211

There is an easier way,

virtualenv venv --python=python2.7

Thanks to a comment, this only works if you have python2.7 installed at the system level (e.g. /usr/bin/python2.7).

Otherwise, if you are using homebrew you can use the path to give you what you want.

virtualenv venv --python=/usr/local/bin/python

You can find the path to your python installation with which python (Linux) or py -0p (Windows)

This will also work with python 3.

which python3
>> /usr/local/bin/python3
virtualenv venv --python=/usr/local/bin/python3

Ultimately condensing to:

virtualenv venv -p `which python`
virtualenv venv -p `which python3`
Pux
  • 421
  • 3
  • 18
Daniel Lee
  • 7,189
  • 2
  • 26
  • 44
115
virtualenv --python=/usr/bin/python2.6 <path/to/myvirtualenv>
Jan
  • 1,231
  • 2
  • 13
  • 19
iElectric
  • 5,633
  • 1
  • 29
  • 31
  • 3
    See my answer below for an equivalent solution using environment variables. That approach means you don't have to remember to use `-p`. – Chris Johnson Aug 05 '16 at 20:58
  • 6
    Is there no solutions that switches between python versions without requiring to create a new virtual environment? – Charlie Parker Aug 28 '16 at 22:27
  • 4
    Would this work, if you want to install a python version that is not installed on your system? Say you want to test out `python3.6` but dont want to touch `python3.5` installed on your computer? – alpha_989 Jul 31 '18 at 03:53
  • 2
    @alpha_989 are you find the solution to do this? – Danil Nov 28 '19 at 11:23
85

Under Windows for me this works:

virtualenv --python=c:\Python25\python.exe envname

without the python.exe I got WindowsError: [Error 5] Access is denied I have Python2.7.1 installed with virtualenv 1.6.1, and I wanted python 2.5.2.

balazs
  • 5,698
  • 7
  • 37
  • 45
42

Mac OSX 10.6.8 (Snow Leopard):

1) When you do pip install virtualenv, the pip command is associated with one of your python versions, and virtualenv gets installed into that version of python. You can do

 $ which pip   

to see what version of python that is. If you see something like:

 $ which pip
 /usr/local/bin/pip

then do:

$ ls -al /usr/local/bin/pip
lrwxrwxr-x  1 root  admin  65 Apr 10  2015 /usr/local/bin/pip ->
../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip

You can see the python version in the output.

By default, that will be the version of python that is used for any new environment you create. However, you can specify any version of python installed on your computer to use inside a new environment with the -p flag:

$ virtualenv -p python3.2 my_env  
Running virtualenv with interpreter /usr/local/bin/python3.2  
New python executable in my_env/bin/python  
Installing setuptools, pip...done.  

virtualenv my_env will create a folder in the current directory which will contain the Python executable files, and a copy of the pip [command] which you can use to install other packages.

http://docs.python-guide.org/en/latest/dev/virtualenvs/

virtualenv just copies python from a location on your computer into the newly created my_env/bin/ directory.

2) The system python is in /usr/bin, while the various python versions I installed were, by default, installed into:

 /usr/local/bin

3) The various pythons I installed have names like python2.7 or python3.2, and I can use those names rather than full paths.

========VIRTUALENVWRAPPER=========

1) I had some problems getting virtualenvwrapper to work. This is what I ended up putting in ~/.bash_profile:

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/django_projects  #Not very important -- mkproject command uses this
#Added the following based on: 
#http://stackoverflow.com/questions/19665327/virtualenvwrapper-installation-snow-leopard-python
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python2.7 
#source /usr/local/bin/virtualenvwrapper.sh
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

2) The -p option works differently with virtualenvwrapper: I have to specify the full path to the python interpreter to be used in the new environment(when I do not want to use the default python version):

$ mkvirtualenv -p /usr/local/bin/python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3
New python executable in my_env/bin/python
Installing setuptools, pip...done.
Usage: source deactivate

removes the 'bin' directory of the environment activated with 'source
activate' from PATH. 

Unlike virtualenv, virtualenvwrapper will create the environment at the location specified by the $WORKON_HOME environment variable. That keeps all your environments in one place.

7stud
  • 46,922
  • 14
  • 101
  • 127
  • `which pip` doesn't tell me the version of Python. It gives me this- `/usr/local/bin/pip`. – Sankalp Mar 16 '18 at 02:36
  • @Sankalp, If you cd to `/usr/local/bin` and do `$ ls -al pip`, you should see something like: `pip -> ../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip` – 7stud Mar 16 '18 at 02:44
  • Already somewhat noted in answer, but `mkproject` is the command to use if you want it to create both the project directory and a virtual environment of a given python version. `mkproject -p /usr/bin/python3.6 myNewPython36Project` – Jim Factor Jan 24 '19 at 05:13
  • @7stud when i cd to `/usr/local/bin` and do `ls -al pip` i get this `-rwxr-xr-x 1 root admin 266 23 Mar 09:40 pip` – kd12345 Mar 24 '21 at 07:39
  • @kd12345, Then maybe don't rely on the default and specify the python version that you want to use with `virtualenv -p`. – 7stud Mar 24 '21 at 15:10
  • @7stud when i run `which -a python3` i get `/Library/Frameworks/Python.framework/Versions/3.8/bin/python3` `/usr/local/bin/python3` `/usr/bin/python3` in that order what does this mean? – kd12345 Mar 25 '21 at 04:40
  • @kd12345, `which -a` lists all the executables in your `PATH` environment variable--not just the first one found--that match `python3`. If you do `ls -al /usr/local/bin/python3` you will probably see that `/usr/local/bin/python3` is a link to `/Library/Frameworks/Python.framework/Versions/3.8/bin/python3` – 7stud Mar 25 '21 at 23:36
  • @kd12345, The executable `/usr/bin/python3` might be a python that came installed on your system. – 7stud Mar 25 '21 at 23:42
  • @7stud does it matter which one to choose? – kd12345 Mar 28 '21 at 13:27
36

[November 2019] I needed to install a Python 3.7 environment (env) on my Python 3.8-based Arch Linux system. Python 3.7 was no longer on the system, so I could not downgrade Python, to install a package that I needed.

Furthermore, I wanted to use that package / Python 3.7 inside a virtual environment (venv). This is how I did it.


Download Python version source files:

I downloaded the Python 3.7.4 source files from

https://www.python.org/downloads/source/

to

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4.tgz

I then extracted that archive (source files) to

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4/


Installation:

[Note: in my system env, not a venv.]

cd /mnt/Vancouver/apps/python_versions/src/Python-3.7.4/
time ./configure                 ## 17 sec
time make                        ## 1 min 51 sec
time sudo make install           ## 18 sec
time make clean                  ## 0.3 sec

Examine installed Python versions:

$ which python
/usr/bin/python

$ python --version
Python 3.8.0

$ which python3.7
/usr/local/bin/python3.7

$ python    ## Python 3.8 [system / env]
Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

$ python3.7    ## newly-installed Python 3.7 package
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0]
>>>

$ python3.7 --version                                                                                                 
Python 3.7.4

How to create a venv for a specific Python version:

https://docs.python.org/3/tutorial/venv.html

12.2. CREATING VIRTUAL ENVIRONMENTS

The module used to create and manage virtual environments is called venv. venv will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want.

To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path:

python3 -m venv tutorial-env

This will create the tutorial-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files. ...


Create Python 3.7 venv [on a Python 3.8 operating env / system]:

python3.7 -m venv ~/venv/py3.7      ## create Python 3.7-based venv
source ~/venv/py3.7/bin/activate    ## activate that venv
deactivate                          ## deactivate that venv (when done, there)

Added to ~/.bashrc:

alias p37='echo "   [Python 3.7 venv (source ~/venv/py3.7/bin/activate)]" && source ~/venv/py3.7/bin/activate'

Test Python 3.7 venv:

$ p37                                                                                                                 
[Python 3.7 venv (source ~/venv/py3.7/bin/activate)]

(py3.7)$ python --version
Python 3.7.4

(py3.7)$ python
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] 
>>>
Victoria Stuart
  • 4,610
  • 2
  • 44
  • 37
  • 1
    This is an extremely thorough answer! :) I encounter this issue every time I need to transfer something from Arch Linux to any other (e.g. Debian-ish) system. – Robbie Capps Dec 18 '19 at 00:53
  • 1
    @Victoria Stuart, thank you very much. This is exactly what I was looking for. – daddyodevil Feb 01 '20 at 18:17
  • 1
    Here are good step-by-step instructions for how to install Python 3.7 from source on Debian https://linuxize.com/post/how-to-install-python-3-7-on-debian-9/. But as usual, it suggests `sudo make altinstall` and I would strongly recommend to install as a normal user instead, e.g., `./configure --prefix=~/my-python-3.7 && make -j8 && make install`. Then you can do `~/my-python-3.7/bin/python -m venv myvirtualenv` – oseiskar Jul 01 '20 at 12:30
30

You should have that Python version installed. If you have it then basically,

With virtualenv,

virtualenv --python=python3.8 env/place/you/want/to/save/to

with venv

python3.8 -m venv env/place/you/want/to/save/to

The above examples are for python3.8, you can change it to have different versions of virtual environments given that they are installed in your computer.

CrmXao
  • 937
  • 2
  • 16
  • 19
  • how to install specific version of python using above command? – Chandan Feb 03 '21 at 06:45
  • if you have for example python3.8 installed within your computer, the example above will create python3.8 environment. – CrmXao Feb 03 '21 at 11:23
  • yes it's working as you said but I need a different version means in my pc python3.9 is installed but i need to create virtual env for python3.6. – Chandan Feb 03 '21 at 12:15
  • Anyone ever tried or checked what happens if you create a venv from a specific conda environments python version? Based on what I see and read (here) that could add a lot of flexibility to the use of different Python versions when creating a venv? – GWD Jul 05 '22 at 21:23
29

Suppose you currently have python 2.7 installed in your virtualenv. But want to make use of python3.2, You would have to update this with:

$ virtualenv --python=/usr/bin/python3.2 name_of_your_virtualenv

Then activate your virtualenv by:

$ source activate name_of_your_virtualenv

and then do: python --version in shell to check whether your version is now updated.

kmario23
  • 57,311
  • 13
  • 161
  • 150
  • See my answer below for an equivalent solution using environment variables. That approach means you don't have to remember to use `-p`. – Chris Johnson Aug 05 '16 at 20:58
23

These two commands should work fine.

virtualenv -p python2 myenv (For python2)

virtualenv -p python3 myenv (For python3)

Quint
  • 1,146
  • 12
  • 12
Sachin Kolige
  • 363
  • 2
  • 7
  • 1
    The flag -p python2 works equivalent to looking for /usr/bin/python2. Use : virtualenv -p python2.7 myenv for 2.7 etc. – Yash Sharma Dec 28 '18 at 02:05
18

You can call virtualenv with python version you want. For example:

python3 -m virtualenv venv

Or alternatively directly point to your virtualenv path. e.g. for windows:

c:\Python34\Scripts\virtualenv.exe venv

And by running:

venv/bin/python

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

you can see the python version installed in virtual environment

Nima Soroush
  • 12,242
  • 4
  • 52
  • 53
13

The -p approach works well, but you do have to remember to use it every time. If your goal is to switch to a newer version of Python generally, that's a pain and can also lead to mistakes.

Your other option is to set an environment variable that does the same thing as -p. Set this via your ~/.bashrc file or wherever you manage environment variables for your login sessions:

export VIRTUALENV_PYTHON=/path/to/desired/version

Then virtualenv will use that any time you don't specify -p on the command line.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
  • This worked beautifully. Any idea why setting `export VIRTUALENVWRAPPER_PYTHON=/path/to/desired/version` per the [virtualenvwrapper docs](http://virtualenvwrapper.readthedocs.io/en/latest/install.html#python-interpreter-virtualenv-and-path) didn't work but this solution did work? – YPCrumble Nov 08 '16 at 22:37
  • That env var controls which Python `virtualenvwrapper` uses when run, nothing to do with installs. – Chris Johnson Nov 09 '16 at 01:47
  • This worked for me. No longer have to use -p every time I create a new virtualenv. Thanks! – nedblorf Apr 10 '19 at 15:29
10

On the mac I use pyenv and virtualenvwrapper. I had to create a new virtualenv. You need homebrew which I'll assume you've installed if you're on a mac, but just for fun:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"


brew install pyenv
pyenv install 2.7.10
pyenv global 2.7.10
export PATH=/Users/{USERNAME}/.pyenv/versions/2.7.10/bin:$PATH
mkvirtualenv -p ~/.pyenv/versions/2.7.10/bin/python  {virtual_env_name}

I also froze my requirements first so i could simply reinstall in the new virtualenv with:

pip install -r requirements.txt
silverdagger
  • 1,124
  • 13
  • 37
  • Command should be `mkvirtualenv -p ~/.pyenv/versions/2.7.10/bin/python {virtual_env_name}` versions, not version. If SO allowed short edits, I woulda fixed it. – Martin Burch Sep 04 '15 at 04:30
  • `pyenv` includes virtualenv support through the `pyenv-virtualenv` plugin, so I find I don't really need virtualenvwrapper. More details in [my pyenv answer](http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/43828665#43828665). – RichVel May 07 '17 at 07:26
  • I definitely agree with @RichVel, using the provided pyenv-virtualenv with pyenv is the most seemless experience we could ask for ! ( cf https://realpython.com/intro-to-pyenv/#virtual-environments-and-pyenv ) – bluu Dec 01 '20 at 10:59
8

Even easier, by using command substitution to find python2 for you:

virtualenv -p $(which python2) <path/to/new/virtualenv/>

Or when using virtualenvwrapper :

mkvirtualenv -p $(which python2) <env_name>

Gerard
  • 2,832
  • 3
  • 27
  • 39
8

As already mentioned in multiple answers, using virtualenv is a clean solution. However a small pitfall that everyone should be aware of is that if an alias for python is set in bash_aliases like:

python=python3.6

this alias will also be used inside the virtual environment. So in this scenario running python -V inside the virtual env will always output 3.6 regardless of what interpreter is used to create the environment:

virtualenv venv --python=pythonX.X
PetarMI
  • 390
  • 1
  • 7
  • 15
7

For Mac(High Sierra), install the virtualenv on python3 and create a virtualenv for python2:

 $ python3 -m pip install virtualenv
 $ python3 -m virtualenv --python=python2 vp27
 $ source vp27/bin/activate
 (vp27)$ python --version
 Python 2.7.14
Zihao Zhao
  • 439
  • 5
  • 9
7

These seem a little overcomplicated for Windows. If you're on Windows running python 3.3 or later, you can use the python launcher py to do this much more easily. Simply install the different python version, then run:

py -[my version] -m venv env

This will create a virtual environment called env in your current directory, using python [my version]. As an example:

py -3.7 -m venv env
./env/Scripts/activate

This creates a virtual environment called env using python3.7 and activates it. No paths or other complex stuff required.

Cole Smith
  • 150
  • 1
  • 7
6

I utilized this answer for Windows

https://stackoverflow.com/a/22793687/15435022

py -3.4 -m venv c:\path\to\wherever\you\want\it
mattsmith5
  • 540
  • 4
  • 29
  • 67
5

On windows:

py -3.4x32 -m venv venv34

or

py -2.6.2 -m venv venv26

This uses the py launcher which will find the right python executable for you (assuming you have it installed).

jnnnnn
  • 3,889
  • 32
  • 37
5

I use pyenv to manage my python version.

pyenv install 3.7.3
pyenv local 3.7.3

Check your python version:

$ python --version
Python 3.7.3

Create the virtual environment with venv:

python -m venv .

Then activate the Virtual Environment:

source bin/activate

Check your python version:

$ python --version
Python 3.7.3

You may need to remove the previous virtual environment

rm -rf bin
brandonbanks
  • 1,125
  • 1
  • 14
  • 21
  • 1
    As mentionned in a comment to another answer: it's even easier to use the provided pyenv-virtualenv with pyenv (cf https://realpython.com/intro-to-pyenv/#virtual-environments-and-pyenv ) – bluu Dec 01 '20 at 11:01
  • I had to run a **pyenv shell** for the selected python version: `pyenv shell 3.11.3` and then run `python -m venv env` to create the virtual environment. This creates a virtual environment with the name `env` that uses python 3.11.3. To install python versions use `pyenv install 3.11.2`. And in order to use the shell you might need to follow prompted configuration steps when using it for the first time with the command `pyenv shell 3.11.3`. – TomasLangebaek Apr 19 '23 at 20:57
4

In windows subsystem for linux:

  1. Create environment for python3:

    virtualenv --python=/usr/bin/python3 env
    
  2. Activate it:

    source env/bin/activate
    
Marcin Rapacz
  • 616
  • 8
  • 12
4

End of 2020:

The most seamless experience for using virtualenv (added benefit: with any possible python version) would be to use pyenv and its (bundled) pyenv-virtualenv plugin (cf https://realpython.com/intro-to-pyenv/#virtual-environments-and-pyenv)

Usage: pyenv virtualenv <python_version> <environment_name>

Installation:

cf https://github.com/pyenv/pyenv-installer

That being said, nowadays the best possible alternative instead of using virtualenv (and pip) would be Poetry (along with pyenv indicated above, to handle different python versions).

Another option, because it's supported directly by the PyPA (the org behind pip and the PyPI) and has restarted releasing since the end of May (didn't release since late 2018 prior to that...) would be Pipenv

bluu
  • 542
  • 3
  • 13
4

This worked for my usage in Windows 10, where I have Python 3.7 and want to downgrade for a project in Python 3.6.6:

I used "venv" to create a new environment called "venv", I downloaded from https://www.python.org/downloads/windows/ ; install "Download Windows x86-64 executable installer-" ; then I used the following command line in the directory where I want to create my environment

>C:\Users\...\Python\Python36\python.exe -m venv venv

Finally, I activated the environnent using the command line:

>venv\Scripts\activate.bat

And check the python version by calling:

>python --version Python 3.6.6

4

On Linux Ubuntu 21.04 (currently Python 3.9.5) I needed to get a virtualenv of Python 3.7.8. Full steps to get working:

Find the Python version source you want, for example 3.7.8 is here: https://www.python.org/downloads/release/python-378/

Download the Gzipped source tarball

Unzip it with tar zxvf Python-3.7.8.tgz (amend as required with your version number if different from 3.7.8)

Copy the unzipped folder to /usr/bin with: sudo cp -r Python-3.7.8 /usr/bin

cd /usr/bin/Python-3.7.8/

Check the contents if you wanted to see what you have so far: ls

sudo time ./configure
sudo time make
time sudo make install
time make clean

Check how your python is set up and reporting:

which python
python --version

Should be all relating to your primary install (Python 3.9.5 for me)

To check your new install:

which python 3.7
python3.7 --version

Should be all relating to your 3.7.8 install

If you want to run it to check, do:

python3.7
exit()

Install venv:

sudo apt install venv

To create a venv (maybe in your repo, if so, add .venv to .gitignore):

python3.7 -m venv .venv

To activate your venv:

source .venv/bin/activate

Check your version:

python --version
Leigh Mathieson
  • 1,658
  • 2
  • 17
  • 25
  • Why using "time" in the configure and compilation part? Could not see any such instruction in the Build instruction in README.rst. – Alexander Oct 11 '21 at 07:16
  • Why is venv so far behind anaconda in ease of use when it comes to targeting an environment toward a particular version of python? – user3673 Dec 09 '21 at 20:56
  • Not only did it not work, but it also set my system's default python version to 3.7 :-( – Celso França Nov 22 '22 at 16:26
4

Answer to this question shouldn't be that complicated...

TL,DR:

install as many versions of python you prefer on your system and use:

/c/path/to/any/version/of/python -m venv my_venv

============================================

I use venv to install virtual environments with

python -m venv <where/to/and/name_of_venv>

if you try which python you will see which python you are referring to, when saying "python". for example, for me it is:

which python

result: /c/Program Files/Python36/python

So, now you have the answer! you can install any version of python on your system and have multiple of them at the same time. So, for example I installed Python3.7 in this directory: "C:\Program Files\Python37". So, instead of using 'python' now I specify which python by /c/Program\ Files/Python37/python:

 /c/Program\ Files/Python37/python -m venv my_venv

(don't forget to escape the space in the path)

That's it!

3

Yes, the above answers are correct and works fine on Unix based systems like Linux & MAC OS X.

I tried to create virtualenv for Python2 & Python3 with the following commands.

Here I have used venv2 & venv3 as their names for Python2 & Python3 respectively.

Python2 »

MacBook-Pro-2:~ admin$ virtualenv venv2 --python=`which python2`
Running virtualenv with interpreter /usr/local/bin/python2
New python executable in /Users/admin/venv2/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv2/bin/
activate        easy_install        pip2.7          python2.7
activate.csh        easy_install-2.7    python          wheel
activate.fish       pip         python-config
activate_this.py    pip2            python2
MacBook-Pro-2:~ admin$ 

Python3 »

MacBook-Pro-2:~ admin$ virtualenv venv3 --python=`which python3`
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/admin/venv3/bin/python3
Also creating executable in /Users/admin/venv3/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv3/bin/
activate        easy_install        pip3.6          python3.6
activate.csh        easy_install-3.6    python          wheel
activate.fish       pip         python-config
activate_this.py    pip3            python3
MacBook-Pro-2:~ admin$ 

Checking Python installation locations

MacBook-Pro-2:~ admin$ which python2
/usr/local/bin/python2
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ which python3
/usr/local/bin/python3
MacBook-Pro-2:~ admin$ 
hygull
  • 8,464
  • 2
  • 43
  • 52
3

I use Windows so I should use .exe on the pthon path

virtualenv -p=C:\Python27\python2.exe <envname>
Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
3

Suppose I want to use python 3.8 and I'm using MacOS.

brew install python@3.8

Then,

python3.8 -m venv venv
Data
  • 689
  • 7
  • 23
2

It worked for me

sudo apt-get install python3-minimal

virtualenv --no-site-packages --distribute -p /usr/bin/python3 ~/.virtualenvs/py3
Dadaso Zanzane
  • 6,039
  • 1
  • 25
  • 25
2
virtualenv -p python3 myenv

Link to Creating virtualenv

Aseem
  • 5,848
  • 7
  • 45
  • 69
2

This was a bug with virtualenv. Just upgrading your pip should be the fix.

pip install --upgrade virtualenv

Mohit
  • 43
  • 4
1

For Debian (debian 9) Systems in 2019, I discovered a simple solution that may solve the problem from within the virtual environment.

Suppose the virtual environment were created via:

python3.7 -m venv myenv

but only has versions of python2 and python2.7, and you need the recent features of python3.7.

Then, simply running the command:

(myvenv) $ python3.7 -m venv --upgrade /home/username/path/to/myvenv/

will add python3.7 packages if they are already available on your system.

1

It worked for me on windows with python 2 installation :

  1. Step 1: Install python 3 version .
  2. Step 2: create a env folder for the virtual environment.
  3. Step 3 : c:\Python37\python -m venv c:\path\to\env.

This is how i created Python 3 virtual environment on my existing python 2 installation.

1

Yes you just need to install the other version of python, and define the location of your other version of python in your command like :

virtualenv /home/payroll/Documents/env -p /usr/bin/python3

1

Here is the stepbystep how to create the Virtual environment in Visual Studio Code folder: I used Powershell (Administrator mode):
1. I create a VSCode folder - "D:\Code_Python_VE" where I want to create Virtual environment.
2. Next I type the command - "pip3 install virtualenv". (D:\Code_Python_VE> pip3 install virtualenv) 3. D:\Code_Python_VE> python3 -m venv project_env
4. D:\Code_Python_VE>project_env\Scripts\activate.bat
5. D:\Code_Python_VE> ls - This will list a new directory "project_env".
6. D:\Code_Python_VE> code . This will start Visual Studio Code. Make sure the command is (code .).
7. Create launch.jason with following content:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "python",
            "request": "launch",
            "name": "Python: Current File (Integrated Terminal 1)",
            "program": "${file}"
        },
        {
            "name": "Python: Current File (Integrated Terminal 2)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

(Please search how to go to Debug window and Add new Configuration in VS Code).

  1. Press F1 in Visual studio code and the command pallet will open - Select Python Interpreter and select the virtual environment project_env.
  2. Add test.py file with one statement print("Hello World").
  3. Run this program.
  4. In Visual studio Code terminal -
    (project_env) d:\Code_Python_VE>python -m pip install --upgrade
    I hope this helps.
TanuAD
  • 656
  • 6
  • 12
1

UBUNTU 19.04 / Global Python 3.7.

This worked for me, enabling a Python 3.8 environment using the recommended venv for python 3 development.

Install 3.8 and 3.8 venv module: $ sudo apt install python3.8 python3.8-venv
plus any other modules you need

Create your Virtual Env using the python version you want in that env

$ /usr/bin/python3.8 -m venv python38-env

switch into your virtual env

$ source python38-env/bin/activate

python -V = python 3.8
Hrvoje
  • 13,566
  • 7
  • 90
  • 104
Simon P
  • 337
  • 3
  • 8
1

Surprised that no one has mentioned conda so far. I have found this is a lot more straightforward than the other methods mentioned here. Let's say I have python 3.9 and python 2.7 and a project I am working on was python 3.5.4, I could simply create the isolated virtual env for 3.5.4 with the conda command without downloading anything else.

To see a list of available python versions first, use the command

conda search "^python$"

To create the virtual environment for python version x.y.z, use the command

conda create -n yourenvname python=x.y.z

Activate venv with

conda activate yourenvname

Deactivate with

conda deactivate

To delete the virtual environment when done, use the command

conda remove -n yourenvname --all

sparker
  • 1,245
  • 11
  • 17
1

Simple:

Linux

virtualenv venv --python=/usr/bin/python3.9

Windows

virtualenv venv --python=C:\Users\username\AppData\Local\Programs\Python\Python\python.exe
nhaht
  • 1,005
  • 12
  • 21
1

for windows only

  1. install the specific version of python in your pc
  2. go the directory where you want to create the virtual environment
  3. type cmd in the location bar in file explorer & hit enter
  4. on cmd type ->pip install virtualenv
  5. then create the virtual env using the virtualenv library by typing the below command in cmd. -> virtualenv -p="C:\location of python\python.exe" <virtualenv_name>
0

sudo add-apt-repository ppa:deadsnakes/ppa

sudo apt update

sudo apt install python_version (ex: sudo apt install python3.8)

python_version -m venv env (ex: python3.8 -m venv env)

. env/bin/activate

This Above steps will solve your python version for env issue.

Fenil
  • 39
  • 3
  • It is not clear how this would solve the problem given that it the original question implies that the author would like to have two different versions of python. And your answer suggests installing an outdated version of python (3.6 is no longer supported). – Jason Harrison Jul 08 '22 at 22:30
  • used 3.6 for just an example, thanks for the correction. Here if the programmer has a universal python version set and the programmer wants to work on some specific version for the project then this way it is possible without affecting the universal python version on his system. – Fenil Jul 11 '22 at 09:46