Managing Python Virtual Environments

Published

How to set up a Python project and manage its dependencies.

Step 0 - Install Python's Package Manager Globally

python -m pip install virtualenv 

Step 1 - Create a directory for your Virtual Environments

This is simply good hygene but the idea is to create a directory where you can place all of your virtual environments.

mkdir my_virtualenvs

Step 2 - Create a new Virtual Environment

The -p flag will indicate to create a virtual environment using Python 3 interpreter. Your new virtual environment will now contain 4 folders. The lib folder is for installing packages. The bin folder holds the python interpreter and pip installer.

virtualenv -p python3 my_app

Don't Mix Your Virtual Environment with your App

It's wise to keep your virtual environment folder separate from your app folder. Virtual environments are intended to contain packages, tools, the python interpreter, etc. Your project folder is meant for your source code and is often version controlled. It's not recommended to store your virtual environment inside git.

Step 3 - Activate your Environment

The bin/activate contains the script used to run your environment. When we activate our environment, we use the . to import some shellscript code from a file and the file is in your environment.

. my_app/bin/activate

Step 4 - Double Check

You can double check your activation by checking which version of python you are running.

python -V

Another check is to list all of the packages within your environment.

python -m pip list

python-pip-list

Step 5 - Install Libraries

Let's install the requests package.

python -m pip install requests

Step 6 - Deactivate Virtual Environment

deactivate

Step 7 - Sharing Dependencies

In Node it's called package.json. In Ruby it's called Gemfile. You can do something similar using pip to describe all the packages and requirements required for your app.

python -m pip freeze > requirements.txt

Step 8 - Import Existing Dependencies into a New Project

Suppose you are working in a team setting and you've downloaded the python project from git. All you need to do is find the text file your team uses to freeze dependencies and import it.

In this command-line example, requirements.txt is the name of the file with the dependencies we want to import.

python -m pip install -r requirements.txt

Step 9 - Upgrade a Package

You can always upgrade your packages using ```pip`. Simply run:

python -m pip install -U [name of package]

Comments