Appendix A: Virtual Environments and Libraries
Python 3 has a module called venv
for creating
virtual environments for your projects.
A virtual environment is an independent Python installation at a location (subdirectory) that you specify. When you activate a virtual environment, that particular Python installation will be used to run your programs.
If your project depends on external libraries, you can install
these into your virtual environment using the standard Python
installation tool pip
.
This allows you to:
Keep each software project in a separate environment.
Specify your project’s dependencies precisely.
Here’s a quick start.
Create a new virtual environment
This creates the directory venv_name
.
python3 -m venv venv_name
Often people use the name venv
for the installation
directory.
Note: You do not want to include your virtual environment installation directory in your repository. This folder will contain a large number of binary files.
Activate the virtual environment
The new directory venv_name
has a sub-directory
bin
, in which there is a script called
activate
.
venv_name
|-- bin
|- activate
Calling this script with the source
command
activates the virtual environment by setting your PATH
and other environment variables.
source venv_name/bin/activate
This will also change your prompt to include
(venv_name)
, to indicate that the virtual environment
is active.
Deactivate the virtual environment
deactivate
Install requirements into the virtual environment
First activate the virtual environment. Then calling
pip install
will install stuff into the active virtual
environment.
source venv_name/bin/activate
pip install library_name
Specfiy your dependencies in requirements.txt
It is common practice to list your dependencies in a file
requirements.txt
in the root directory of your
project:
matplotlib
numpy
Including requirements.txt
in your source code
repository allows you to easily reproduce your development
environment in another location.
Use the -r
flag with pip install
to
install the libraries listed in requirements.txt
.
pip install -r requirements.txt
Set up your dev environment in another location
The requirements.txt
file helps you set up a new
development environment (for example to work on your project on
another computer, or to work with a collaborator).
python3 -m venv venv_name
source venv_name/bin/activate
pip install -r requirements.txt