在使用python开发项目的过程中,python因为版本的原因,有诸多的库在某些特定的python版本才可以运行,我们就需要将单个项目的python环境单独出来,python的虚拟环境管理工具有很多种,venv、virtualenv、pyenv、anacona 等,各式各样,眼花缭乱,都不知道如何选择

那最佳的,最适合我们的是什么?根据我长期的使用,我觉得 virtualenv 是最佳的选择,virtualenv如何使用 ?

1、安装,使用pip安装即可

pip install virtualenv

2、使用

安装好virtualenv就可以直接使用命令创建一个虚拟环境,如下命令创建是创建一个 venv 的虚拟环境

virtualenv venv

同时,virtualenv 也有很多参数,可以使用帮助命令来查看命令说明

virtualenv --h
打开网易新闻 查看精彩图片

其中,经常用的一些参数,我给大家翻一下

Usage: virtualenv [OPTIONS] DEST_DIR Options: --version show program's version number and exit 显示版本号并退出 -h, --help show this help message and exit 显示本帮助信息并退出 -v, --verbose Increase verbosity. 增量信息 -q, --quiet Decrease verbosity. 消除冗长 -p PYTHON_EXE, --python=PYTHON_EXE The Python interpreter to use, e.g., --python=python2.5 will use the python2.5 interpreter to create the new environment. The default is the interpreter that virtualenv was installed with (/usr/share/python3/bin/python3.5) 设定虚拟环境中Python的运行版本 --clear Clear out the non-root install and start from scratch. default behavior. --system-site-packages Give the virtual environment access to the global site-packages. 如果在命令行中运行virtualenv --system-site-packages ENV, 会继承/usr/lib/python2.7/site-packages下的所有库, 最新版本virtualenv把访问全局site-packages作为默认行为 default behavior. --always-copy Always copy files rather than symlinking. --unzip-setuptools Unzip Setuptools when installing it. --relocatable Make an EXISTING virtualenv environment relocatable. This fixes up scripts and makes all .pth files relative. 某些特殊需求下,可能没有网络, 我们期望直接打包一个ENV, 可以解压后直接使用, 这时候可以使用virtualenv -relocatable指令将ENV修改为可更改位置的ENV --no-setuptools Do not install setuptools in the new virtualenv. 不安装setuptools --no-pip Do not install pip in the new virtualenv. 不安装pip --no-wheel Do not install wheel in the new virtualenv.不安装wheel --extra-search-dir=DIR Directory to look for setuptools/pip distributions in. This option can be used multiple times. --download Download preinstalled packages from PyPI. --no-download, --never-download Do not download preinstalled packages from PyPI. --prompt=PROMPT Provides an alternative prompt prefix for this environment. --setuptools DEPRECATED. Retained only for backward compatibility. This option has no effect. --distribute DEPRECATED. Retained only for backward compatibility. This option has no effect. 使virtualenv使用新的基于发行版的包管理系统而不是 setuptools 获得的包。 你现在需要知道的就是 --distribute 选项会自动在新的虚拟环境中安装 pip ,这样就不需要手动安装了。

进入虚拟环境

linux 环境下,使用 source 命令进入虚拟环境

source venv/bin/activete

退出命令则运行如下命令即可

deactivate

windows环境下,进入虚拟环境的方法有所有不同,可以直接运行环境根目录下 Scripts 的 shell 脚本,使用cmd打开的就运行 ****.bat 的脚本,用powershell打开的就是用 ****.ps1脚本

.envScriptsactivate.ps1

退出命令同样是:deactivate

最后我给出使用 virtualenv 的一些使用建议

我们在做项目时候,建议最好一个项目使用一个虚拟环境,放在项目的根目录下,使得在发布项目的时候方便快捷,在项目部署时,使用 pip freeze > requirements.txt 到处依赖包列表。