Python Virtual Environments Cheat Sheet
Virtual environments make using Python a bit more manageable, especially when it comes to deploying Python programs and creating the requirements (able to use pip freeze > requirements.txt
and only use packages necessary to that individual project). However, I commonly find myself forgetting some of the more basic commands. For Python 2 use pip
, for Python 3 use pip3
.
Downloading virtualenv
- Download virtualenv using pip
pip install virtualenv
- Download virtualenvwrapper using pip
pip install virtualenvwrapper
. Virtual environment wrapper will make using virtual environments a little easier. - On a Mac:
- Create a directory to store your virtual environments, i.e
mkdir ~/Documents/Development/virtualenvs
vi ~/.bash_profile
- Add to file:
- Save and quit (esc + :wq)
source ~/.bash_profile
- Quit and reopen terminal to reload bash profile
- Create a directory to store your virtual environments, i.e
Basic commands to use virtual environments
lsvirtualenv
: List your virtual environmentsmkvirtualenv [name]
: Create a new virtual environment. Use the flag-ppython3.5
after name to create a Python 3.5 virtual environment.rmvirtualenv [name]
: Remove a virtual environmentworkon [name]
: Enter a virtual environmentdeactivate
: Stop working on a virtual environmentpip freeze > requirements.txt
: View modules installed in current environmentpip install -r requirements.txt
: Install all modules in requirements.txt
Setting up virtual environments
- To make
workon [name]
go directly to the directory of the project directory, edit the /virtualenvs/postactivate and add: - To make
deactivate
exit the project directory, edit the /virtualenvs/postdeactivate and add:- by Harry Marr