Virtual environments and package management in Python 3

A virtual environment is a directory containing a Python installation and any additional packages. Since a virtual environment is isolated, any changes made will not affect the global installation of Python. It also enables the usage of different versions of the same package in multiple virtual environments.

To create a virtual environment, the venv module will be used. The virtualenv module also can be used, but venv is the officially recommended solution so that’s what I will be using. The current Python 3 documentation recommends the usage of pyvenv, which is a wrapper around venv. Since pyvenv will be deprecated soon, avoid using pyvenv.

Installation of venv on Ubuntu 16.04:

sudo apt install python3-venv

To create a new virtual environment:

python3 -m venv python_learn_venv

To activate the newly created virtual environment:

source python_learn_venv/bin/activate

The terminal will reflect that a virtual environment has been activated by displaying it’s name.

To deactivate a virtual environment:

deactivate

After activating a virtual environment, packages can be managed using a tool called pip. The tool lets you install, upgrade, remove and search for packages.

To search for a package:

pip search package_name

To install a package:

pip install package_name

To uninstall a package:

pip uninstall package_name

To upgrade a package to the latest version:

pip install --upgrade package_name

To view information about a particular package:

pip show package_name

To view the list of packages installed in the current virtual environment:

pip freeze

pip list can be used, but pip freeze is preferred, since the output is in the format that pip install expects.

To keep track of the packages installed in your virtual environment, save the contents of pip freeze to a file called requirements.txt.

pip freeze > requirements.txt

The requirements.txt can be commited to version control.

To install packages from requirements.txt`:

pip install -r requirements.txt

A note about pip and pip3: when a virtual environment has been created with Python 3 and is active, pip refers to pip3. When a virtual environment is not activated, pip will refer to pip2.

An example of requirements.txt is here.

References: