virtualenv搭建Python虚拟环境

virtualenv

参考:https://ilaotan.github.io/2015/08/24/python-virtualEnv-pycharm.html

virtualenv用于创建相互独立的Python环境

  • 使不同应用开发环境独立
  • 环境升级不影响其他应用,也不会影响全局的Python环境
  • 它可以防止系统中出现包管理混乱和版本的冲突

安装virtualenv

sudo pip install virtualenv

创建virtualenv目录

wanyongzhendeMacBook-Pro:~ wanyongzhen$ virtualenv testvir
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/wanyongzhen/testvir/bin/python3.6
Also creating executable in /Users/wanyongzhen/testvir/bin/python
Installing setuptools, pip, wheel...done.

切换到virtualenv目录并进入Python虚拟环境

wanyongzhendeMacBook-Pro:~ wanyongzhen$ cd testvir/
wanyongzhendeMacBook-Pro:testvir wanyongzhen$ source bin/activate
(testvir) wanyongzhendeMacBook-Pro:testvir wanyongzhen$ pip list
pip (9.0.1)
setuptools (36.4.0)
wheel (0.29.0)

退出virtualenv Python虚拟环境

(testvir) wanyongzhendeMacBook-Pro:testvir wanyongzhen$ deactivate 

virtualenvwrapper

参考:http://www.jianshu.com/p/3abe52adfa2b

Virtaulenvwrapper是virtualenv的扩展包,用于更方便管理虚拟环境,它可以做:

  • 将所有虚拟环境整合在一个目录下
  • 管理(新增,删除,复制)虚拟环境
  • 快速切换虚拟环境

安装virtualenvwrapper

wanyongzhendeMacBook-Pro:testvir wanyongzhen$ sudo pip install virtualenvwrapper --upgrade --ignore-installed

创建目录用来存放虚拟环境

mkdir ~/.virtualenvs

在.bash_profile中添加

export WORKON_HOME=~/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

生效

source ~/.bashrc

创建virtualenv

wanyongzhendeMacBook-Pro:~ wanyongzhen$ mkvirtualenv python2.7 --python=python2.7
wanyongzhendeMacBook-Pro:~ wanyongzhen$ mkvirtualenv python3.6 --python=python3.6

命令列表

  • workon:列出虚拟环境列表
  • lsvirtualenv:同上
  • mkvirtualenv :新建虚拟环境
  • workon [虚拟环境名称]:切换虚拟环境
  • rmvirtualenv :删除虚拟环境
  • deactivate: 离开虚拟环境
原文地址:https://www.cnblogs.com/wanyuetian/p/7482071.html