Virtual Environments


Setting up Your Project with Virtual Environments

About Virtual Environments

  • isolated context for installing packages
  • always work inside a virtual environment
    • no global install anymore
    • create virtual env. for every project
  • isolate project dependencies

Creating a Virtual Environment

  • create a virtual environment
  • explore the virtual environment

Simple Steps Example

  1. create virtualenvs in home directory
$ cd ~
$ mkdir virtualenvs
$ cd virtualenvs
  1. create virtual env
python3 -m venv my_env

Working Inside a Virtual Environment

Activating environment on Linux and MacOS

$ . my_env/bin/activate
(my_env) $

Checking versions

$ python -V
$ pip -V
$ python -m pip list

Deactivating environment

$ deactivate

Typical workflow

$ python -m venv myenv
$ python3 -m venv myenv

Python version <= 3.3

# Python versions <= 3.3: venv not built-in
# Need to install virtualenv package first
$ virtualenv myenv

Managing Project Requirements

  • syncing dependencies with your team
    • create requirements.txt file
$ . ~/virtualenvs/my_env/bin/activate
(my_env) $ python -m pip freeze
Babel==2.9.1
pkg-resources==0.0.0
pytz==2021.1
(my_env) $ python -m pip freeze > requirements.txt
  • Installing packages from requirements file
$ python -m pip install -r requirements.txt

Projects, Requirements, and Versions

Projects

  • contain source code
  • likely under version control

Virtual Environments

  • contain packages, tools, python, etc.
  • keep them separate from your projects
  • usually: 1 venv per project
  • can have multiple venvs per project
  • or single venv for multiple projects

Specifying Versions

docopt == 0.6.1     # must be version 0.6.1
keyring >= 4.1.1    # Minimum version 4.1.1
coverage != 3.5     # Anything except version 3.5

Versions and Pip

python -m pip install flask==0.9
python -m pip install 'Django<2.0' # mind the quotes!

# Upgrade to latest version
python -m pip install -U flask

# Upgrade pip itself
# Take care NOT to overwrite system pip
python -m pip install -U pip

Testing with Tox

Can tell Tox is being used by tox.ini file

  • Install tox in virtual environment
$ python -m pip install tox
  • Viewing contents of tox.ini
$ cat tox.ini
  • Run tests using Tox
$ tox
Made with Gatsby G Logo