virtualenv --独立的python开发环境
? python ?    2019-01-11 16:22:44    687    0    0
gua_l   ? python ?

 virtualenv 概述

virtualenv提供了一个独立的python开发环境,用于多个python项目不同环境的隔离。当我们多个项目并行时,并且项目彼此之间需要导入同一模块的不同版本时,virtualenv所提供的虚拟环境就非常有用。

这是一个开源的项目。

源码访问: https://github.com/pypa/virtualenv 

文档参考: https://virtualenv.pypa.io/en/latest

 

安装使用

安装

pip install virtualenv​
 
初始化python 独立的运行环境
cd /home/releng/Songhua_auto_release
virtualenv --no-site-packages venv
 
以上执行完会在当前目录生成venv的目录,使用以下命令使环境激活,activate
source venv/bin/activate
 
导入模块 ,其中导入的模块是是test.py 中需要import 的。退出环境后,环境外使用的是系统安装的原有模块。
pip install -U multi-mechanize
pip install requests
python test.py
 
在环境里执行脚本
python test.py
 
退出环境
deactivate

 

实操演示

//以下安装时 , 需要使用root  权限安装

[root@huangbei temp]# pip install --upgrade pip
[root@huangbei temp]# pip install virtualenv

[root@huangbei temp]# exit

[relmgr@huangbei temp]$ virtualenv --no-site-packages venv
........
Installing setuptools, pip, wheel...done.

[relmgr@huangbei temp]$ ll
drwxrwxr-x 5 relmgr relmgr 77 Sep 26 15:25 venv

//执行完初始化,当前目录生成了venv 目录


[relmgr@huangbei temp]$ cat test.py
#-*- coding:utf-8 -*-
import mechanize


 

[relmgr@huangbei temp]$ source venv/bin/activate

//激活环境就进入(venv)开头的环境里
(venv) [relmgr@huangbei temp]$ python test.py
........
ImportError: No module named mechanize

//以上我们可以知道,这个干净的虚拟环境要执行此脚本还需要再导入模块包

(venv) [relmgr@huangbei temp]$ pip install -U multi-mechanize


 

(venv) [relmgr@huangbei temp]$ python test.py

(venv) [relmgr@huangbei temp]$ deactivate
[relmgr@huangbei temp]$

// deactivate 退出环境 ,下次进入环境时,之前导入的模块仍有保留

// 环境之内与环境之外,可以导入同一个模块的不同版本V1 和 V2 。彼此隔离,互不影响。


Pre: GitLab GEO 异地主副服务器同步--文档翻译

Next: mount/nfs 共享目录

687
Sign in to leave a comment.
No Leanote account? Sign up now.
0 comments
Table of content