Python Virtual Environments
Table of Contents
Python虚拟环境可以在独立的地方保持针对不同的工程的依赖需求,通过为它们创建虚拟Python环境.它解决这样的困境,"工程X以来版本1.x,但是工程Y需要4.x".并且你的全局site-packages整洁可控.
virtualenv
virtualenv is a tool to create isolated Python environments.
install via pip
$ sudo pip install virtualenv
Basic Usage
- Create a virtual environment for a project
Creates a copy of Python in whichever directory you ran the command in, placing it in a folder named
venv
.$ cd my_project_folder $ virtualenv venv
- use a Python interpreter
use the Python interpreter in /usr/bin/python2.7
$ virtualenv -p /usr/bin/python2.7 venv
- activate the virtual environment
$ source venv/bin/activate
The name of the current virtual environment will now appear on the left of the prompt (e.g. (
venv)Your-Computer:your_project UserName$
) to let you know that it’s active. - deactivate
$ deactivate
- delete a virtual environment
delete its folder
rm -rf venv
virtualenvwrapper
virtualenvwrapper provides a set of commands which makes working with virtual environments much more pleasant.
install
$ sudo pip install virtualenvwrapper $ export WORKON_HOME=~/Envs $ mkdir -p $WORKON_HOME $ source /usr/local/bin/virtualenvwrapper.sh
add env to .bashrc
export WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh
Basic Usage
More
lsvirtualenv
List all of the environments.cdvirtualenv
Navigate into the directory of the currently activated virtual environment.cdsitepackages
Navigate into currently activated site-packages directory.lssitepackages
Shows contents of site-packages directory.
autoenv
When you cd into a directory containing a .env, autoenv automagically activates the environment.
$ git clone git://github.com/kennethreitz/autoenv.git ~/.autoenv
$ echo 'source ~/.autoenv/activate.sh' >> ~/.bashrc