Background
virtualenv
is a tool to create isolated Python environments.
The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages
(or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.
Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global site-packages
directory? For instance, on a shared host.
In all these cases, virtualenv
can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
总结来说,virtualenv
是用来隔离不同 Python 项目的开发与运行环境。一个典型的场景是,有一个基于 Python 2.7 的 Django 项目,基于的 Django 版本是 1.1,而同时我们本机上正在开发一个同样基于 Python 2.7 的 Django 项目,不同的是这个项目基于Django 1.2 版本。
我们通过 pip install django
来安装 Django,而这个 Django 依赖包默认会保存在/usr/lib/python2.7/site-packages
,且这两个项目均会通过访问 /usr/lib/python2.7/site-packages
来完成我们的 Django 项目的编译。
这意味着,我们要么安装 1.1 的 Django 版本,要么安装 1.2的版本。
通过使用 virtualenv
后,它会在我们的工程文件夹下创建一个 venv
文件夹,里面包含了这个项目使用的 Python 可执行程序(或者称为 compiler 或者 interpreter)、所有依赖的第三方包。
最终,就解决了不同项目可能需要依赖不同版本的第三方包的问题。
...