Why Use Virtual Environments?
Virtual Environments help in keeping all the packages required for one project at one place. So there’s less issues with conflicting dependencies. Notice that you may even run different Python versions like 2.7, 3.5, 3.6 on the same system, inside different virtual envs.
This following steps is how I start my Python Web Development projects. You can use these steps when setting up web development project using frameworks like Django, Flask, bottle.py, Sanic and Tornado. (The steps apply to Python projects in general.)
1. Make a top-level Directory
Create a directory named “virtualenvs” (a parent directory to keep all your virtual environments)
2. Create the python Virtual Environment
python3 -m venv env
You may use any name for the diretory, other than “env”. If you’re curious about what goes inside the auto-generated “env” directory, check this:
3. Activate the virtual env
Important: Activate the virtual environment every-time you want to build or run the code inside a Virtual Environment. You may edit the code files without activating the venv though.
deactivate to leave the virtual environment, or simply close the session/Terminal.
4. Create the project directory
Optionally, Initialise git inside
your_proj_name directory (you don’t need to commit the other files of
env directory into git.):
OR if you have the project code already,
git clone the code inside
git clone [url]
5 a. Install packages/dependencies using pip
If you’ve a requirements.txt file:
pip install -r requirements.txt
or install the packages individually, for example for Django:
pip install django or
pip install django==2.1 # For a particular version
5 b. You can also install packages from Source Code
For example download Django pre-release code from their git repo, and unzip it into a directory named
pip install -e django
pip install --editable django
Note that you may run
pip from any of
env‘s subdirectories: the installed code will always go into the
6. Finish and Run
You’re set to start working on the project now.
If you’re satisfied with the setup, you most probably want to keep a list of dependencies you just installed.
pip freeze > requirements.txt
(Keep the requirements file in git if you’ve initialised the git repo.)
7. Optimizing your daily workflow
I made this small shell script to automate the task of entering and activating the venv every-time I start:
#!/bin/bash cd virtualenvs/env/ source bin/activate # Configure any other environment variables here - # for example, private API keys that you don't want to check in to git. cd your_proj_name/
Paste the above code in a file name start_your_project_name.sh. From now on, to get started, you just have to do this: