美文网首页
python学习笔记(二)

python学习笔记(二)

作者: 见龙在田007er2770 | 来源:发表于2019-04-04 22:00 被阅读0次

环境变量

A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them. This is one of the most important tools that most of the Python developers use.

虚拟环境是用来保持不同项目之间独立性的工具。是python开发者最重要的一个工具。

我们为什么需要环境变量

Imagine a scenario where you are working on two web based python projects and one of them uses a Django 1.9 and the other uses Django 1.10 and so on. In such situations virtual environment can be really useful to maintain dependencies of both the projects.

想象一下这样的场景:你你需要在两个不同的python项目中用到同一个脚本的不同版本,如一个使用Django 1.9,另外一个使用Django 1.10。在这种情况下,虚拟环境对维持两个项目的独立性就起到了非常重要的作用。

何时何地使用虚拟环境

By default, every project on your system will use these same directories to store and retrieve site packages (third party libraries). How does this matter? Now, in the above example of two projects, you have two versions of Django. This is a real problem for Python since it can’t differentiate between versions in the “site-packages” directory. So both v1.9 and v1.10 would reside in the same directory with the same name. This is where virtual environments come into play. To solve this problem, we just need to create two separate virtual environments for both the projects.The great thing about this is that there are no limits to the number of environments you can have since they’re just directories containing a few scripts.

默认情况下,系统上的每一个项目都会用同样的目录来储存和检索包。那虚拟环境如何工作了?在上面的例子中,你有Django的两个版本。由于python不能分别出"site-packages"目录下的两个版本,v1.9 和v1.10会以同样的名字储存在同样的目录下。这就是python起作用的地方。为了解决这个问题,我们只需要为两个项目创建两个虚拟环境就可以了。由于虚拟环境包含很少的脚本,因此你几乎可以无限制的创建环境。

Virtual Environment should be used whenever you work on any Python based project. It is generally good to have one new virtual environment for every Python based project you work on. So the dependencies of every project are isolated from the system and each other.
虚拟环境应该应用在任何一个基于python的项目上。最好每个项目都有一个新的环境变量,使得每个项目都能很好的区分开来。

如何使用虚拟环境

We use a module named virtualenv which is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need.
我们使用一个叫“virtualenv”的模块来创建独立的python环境。“virtualenv”会创建一个包含项目所需要的应用程序文件夹。

安装“virtualenv”

$ pip install virtualenv

测试你的安装版本

$ virtualenv --version

使用“virtualenv ”

创建环境

$ virtualenv my_name

通过运行上述命令,会创建一个叫"my_name"的文件夹,这个文件夹包含了执行这个项目的所有应用程序。这也是python包会被安装的地方。如果你想使用特定的解析器,如python3,你可以这样做:

$ virtualenv -p /usr/bin/python3 virtualenv_name

如果你想创建一个使用python2.7的虚拟环境,你可以

$ virtualenv -p /usr/bin/python2.7 virtualenv_name

创建了虚拟环境之后,你还要激活它。请一定要记得激活对应的环境,命令如下:

$ source virtualenv_name/bin/activate

一旦虚拟环境激活,虚拟环境的名字就会出现在终端的左上角,这就提示你该环境已经激活。而一旦你完成项目,需要退出当前环境,命令如下:

(virtualenv_name)$ deactivate

这样你就会回到系统默认的环境。


参考资料

相关文章

网友评论

      本文标题:python学习笔记(二)

      本文链接:https://www.haomeiwen.com/subject/vehciqtx.html