virtualenv 的使用
声明
本文 virtualenv 版本号为 : 16.4.3
安装
安装虚拟环境 :
pip3 install virtualenv
查看命令列表
virtualenv -h
创建虚拟环境 :
virtualenv -p python3 venv
命令 virtualenv 创建了一个独立的 Python3 运行环境,其中 venv 为虚拟环境名称 , 可以看到当前目录下多了 venv 目录 。
-p python3 为指定使用的 python 版本为 python3 , 这里笔者之前配置了 python3 指向 python 3.7 , 读者要根据需要创建的 python 版本指定 。
以前的博客大多加上了参数 --no-site-packages,这样,已经安装到系统 Python 环境中的所有第三方包都不会复制过来,就得到了一个不带任何第三方包的“干净”的Python运行环境。需要指出的是新版本的 virtualenv --no-site-packages 参数已经被废弃 , 默认创建的虚拟环境不会复制系统环境 :
$ virtualenv -h
--no-site-packages DEPRECATED. Retained only for backward compatibility.
Not having access to global site-packages is now the
default behavior.
同时虚拟环境默认解释器 Python 版本为安装 virtualenv 的 Python . 如下 :
$ virtualenv -h
-p PYTHON_EXE, --python=PYTHON_EXE
The Python interpreter to use, e.g.,
--python=python3.5 will use the python3.5 interpreter
to create the new environment. The default is the
interpreter that virtualenv was installed with
(/usr/local/bin/python3.7)
因此大多数情况下 , 创建虚拟环境的步骤可以简化为 :
virtualenv venv
激活虚拟环境
$ source venv/bin/activate
退出虚拟环境
deactivate