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

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

Python开篇——简介、pip和condapython

1 为何须要独立的Python环境?

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

virtualenv is a tool to create isolated Python environments.github

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

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

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

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

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

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

2.1 安装

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

pip install virtualenv

2.2 使用virtualenv建立Python环境

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

cd your project path

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

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

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

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

.../Python/Scripts/virtualenv venv #...表示Python安装路径包,根据我的不一样替换,venv同上

接着就开始运行了,定位到咱们创建的文件夹下能够看到。

一共有这么几个文件。

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

cd Scripts
activate

这就进入了virtualenv的Python环境。

关闭这个环境,只须要运行以下命令。

deactivate

2.3 使用pip安装包

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

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

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

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

本文参考的一些文章连接以下。

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

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

相关文章
相关标签/搜索