如何为指定版本的Python创建虚拟环境?


当前回答

是的,上面的答案是正确的,在基于Unix的系统(如Linux和MAC OS X)上运行良好。

我尝试使用以下命令为Python2&Python3创建virtualenv。

这里我分别使用了venv2和venv3作为Python2和Python3的名称。

蟒蛇2»

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$ 

蟒蛇3»

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$ 

检查Python安装位置

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$ 

其他回答

假设我想使用python 3.8,而我使用的是MacOS。

brew install python@3.8

然后

python3.8 -m venv venv
virtualenv -p python3 myenv

创建virtualenv的链接

virtualenv --python=/usr/bin/python2.6 <path/to/myvirtualenv>

您可以使用所需的python版本调用virtualenv。例如:

python3 -m virtualenv venv

或者直接指向虚拟路径。例如,对于窗口:

c:\Python34\Scripts\virtualenv.exe venv

通过运行:

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

您可以看到安装在虚拟环境中的python版本

仅适用于windows

在电脑中安装特定版本的python转到要创建虚拟环境的目录在文件资源管理器的位置栏中键入cmd并按enter键在cmd类型->pip上安装virtualenv然后在cmd中键入以下命令,使用virtualenv库创建虚拟env。->virtualenv-p=“C:\location of python\python.exe”<virtualenv_name>