使用virtualenv和pip构建项目所需的独立Python环境

由于最近刚好有个测试需求,来讲一讲如何使用virtualenv和pip构建项目所需的独立Python环境。关于pip的介绍之前已有一篇博客,链接在下面。今天对pip的介绍主要是关于其他参数。

Python开篇——简介、pip和conda

1 为什么需要独立的Python环境?

在讲技术前,想先讲讲目的。为什么我们需要独立的Python环境?这里就借用virtualenv的文档来解释吧。

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

当你在开发or数据分析时,可能会遇上不同的需求,对所需要的包的版本不统一,譬如前一段我在开发D3L Tool的时候遇上的一个问题。当时开发的程序并不能在Win 7系统上运行,后面搜索了很久,发现是pyinstaller版本的问题。但是我又不太想把pyinstaller版本往下降。所以这个时候virtualenv就很有用了。

2 使用virtualenv和pip来构建纯净和独立的Python环境

接下来主要来讲讲怎么操作。另外提一句这里介绍的主要是Windows下的,Linux和Mac的会有些小差别。基于的Python环境是Anaconda2 Python 2.7.12。

2.1 安装

安装部分还是pip大法好。具体就不展开了,pip的安装在前面的博客已经介绍过了。

1
pip install virtualenv

2.2 使用virtualenv创建Python环境

先选择你要创建的工程路径。用cmd进入到该文件夹里。

1
cd your project path

接下来有两种情况,virtualenv的使用方式其实与pip类似,它也在Python安装路径的Scripts里。因此根据你是否设置了环境变量就有两种方式运行。

情况1:将Scripts路径设置为电脑的环境变量

1
virtualenv venv #venv为你的文件名,也就是放置新的、纯净的、独立的Python环境的文件夹

情况2: 没有设置Scripts路径为电脑的环境变量

1
.../Python/Scripts/virtualenv venv #...表示Python安装路径包,根据个人不同替换,venv同上

接着就开始运行了,定位到我们建立的文件夹下可以看到。

一共有这么几个文件。

接下来在cmd定位到项目路径,并运行如下命令。

1
2
cd Scripts
activate

这就进入了virtualenv的Python环境。

关闭这个环境,只需要运行如下命令。

1
deactivate

2.3 使用pip安装包

其实pip安装的部分我之前已经介绍过了,不过上一篇讲得比较简单,仅仅就讲了讲最简单的pip install。而pip 安装包的时候,由于使用的是国外的地址下载包,可能会有些慢或者经常掉线,因此使用国内镜像是比较快的,另外如前文的需求,有些时候需要安装指定版本的包。这也是这次的重点。

1
pip install -i "mirror" numpy==version # mirror就是指国内的镜像地址,version就是指包的版本。

主要介绍的两个参数就是如上所示了,一个是填入国内镜像地址,一个是给定指定包的版本。具体镜像地址见问候链接的第二篇文章。这里给出清华的镜像。

清华大学镜像:https://pypi.tuna.tsinghua.edu.cn/simple

本文参考的一些文章链接如下。

1.用virtualenv建立多个Python独立开发环境

2.让PIP源使用国内镜像,提升下载速度和安装成功率

坚持原创技术分享,您的支持将鼓励我继续创作!