作者:雷霰霆
-
virtualenv是什么
``` virtualenv is a tool to create isolated Python environments.
``` 这是 文档 给出的定义 从定义我们可以看出,这个神器是用来构建python独立开发环境的。 当你需要管理的应用变多的时候,那么如何保持各个应用之间相互独立,保持干净的系统就显得特别重要了。
-
安装 神器很强大,我们如何来安装呢
-
我们可以使用python的另一个神器pip来安装
``` $ [sudo] pip install virtualenv
``` * 可以直接从源代码安装
``` $ curl -O https://pypi.python.org/packages/source/v/virtualenv/virtualenv-X.X.tar.gz $ tar xvfz virtualenv-X.X.tar.gz $ cd virtualenv-X.X $ [sudo] python setup.py install
``` X.X 是virtualenv的版本,具体可以看 virtualenv的github地址
-
-
使用
在终端使用一下命令来查看:
``` 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/local/opt/python/bin/python2.7) --clear Clear out the non-root install and start from scratch. --no-site-packages DEPRECATED. Retained only for backward compatibility. Not having access to global site-packages is now the default behavior. --system-site-packages Give the virtual environment access to the global site-packages. --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. --no-setuptools Do not install setuptools in the new virtualenv. --no-pip Do not install pip in the new virtualenv. --no-wheel Do not install wheel in the new virtualenv. --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.
```
让我们实际来操作一下 第一步,先创建一个目录:
``` mkdir test cd test
```
第二步,在该文件夹下创建一个独立python环境:
``` virtualenv test_env
```
成功输出
``` New python executable in /Users/zchziosdev1/Desktop/python/test/test_env/bin/python2.7 Also creating executable in /Users/zchziosdev1/Desktop/python/test/test_env/bin/python Installing setuptools, pip, wheel...done.
```
我们还可以如此创建
``` virtualenv --no-site-packages test_env
``` --no-site-packages:不复制安装到系统Python环境中的所有第三方包
第三步,开启:
``` source test_env/bin/activate
``` 开启之后,终端变成了
(test_env) ╭─zchziosdev1@zchzdeiMac ~/Desktop/python/test ╰─$
开启之后,就可以进行正常开发了
第四步,关闭:
``` deactivate
```
-
总结
virtualenv为我们提供了一个很强大的隔离环境的功能,特别是在多应用、多版本的情况下,其威力不言而喻,这里我只是简单的写了 virtualenv的一些最基本的东西。