Python Virtual Environments

Article by:
Date Published:
Last Modified:

Overview

When writing a Python application, you will likely pull in a number of third party libraries, typically installed by a package manager such as pip or conda. The application will typically depend on a specific version of each library (or a narrow range of versions). This can cause conflicts if other Python applications on your computer require different versions of the same package.

The solution to this problem is to create a separate installation space for all of the libraries, specific to the application that uses them. This is called a virtual environment.

Python has a few popular frameworks for creating virtual environments.

virtualenv

Installation

Started at Python 3, virtualenv is installed as venv with your Python installation. For Python 2.x users, you can install virtualenv with:

1
$ pip install virtualenv # Python 2.x users only

env will be the name of the virtual environment.

1
python -m venv env

This will create a directory called env in your current working directory.

To activate (on UNIX or macOS):

1
$ source env/bin/activate

To deactivate:

1
$ deactivate

To save all the libraries to a requirements.txt (Linux or Windows cmd.exe):

1
pip freeze > requirements.txt

Be careful if running the above command in PowerShell on Windows! By default, PowerShell will probably not use UTF-8 encoding but a non-standard UTF-16 LE. To prevent this, use the following command instead:

1
pip freeze | Out-File -Encoding UTF8 requirements.txt

pipenv

pipenv is a third-party Python virtual environment framework alternative to the built-in venv.

Installation

1
$ pip install --user pipenv

Authors

Geoffrey Hunter

Dude making stuff.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License .

Related Content:

Tags

comments powered by Disqus