Python - Virtual Environment

Definition

  • Temporary adjustment to how Python runs code.
  • It is not a virtual machine, nor a container.
  • It manipulates the environment variables of your shell so that you can execute one known version of Python using a local set of modules.

Creation

Command Description
venv ENV_DIR create in ENV_DIR path to directory
venv --system-site-packages ENV_DIR give the venv access to the system site-packages dir
venv --symlinks try to use symlinks rather than copies (avoid in Windows)
venv --copies ENV_DIR try to use copies rather than symlinks
venv --clear ENV_DIR delete the contents of the environment directory
venv --upgrade ENV_DIR upgrade the environment directory to use this version of Python
venv --without-pip ENV_DIR skips installing or upgrading pip in the virtual environment
venv --prompt PROMPT provides an alternative prompt prefix for this environment

Activation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# no virtual environment
$ python --version
Python 2.7.17

# virtual environment
$ python3 -m venv myvirtualenv
#creates a virtual environment called myvirtualenv
$ source ./venv/bin/activate
# activates the virtual environment
(myvirtualenv)$ python --version
Python 3.7
# check we have python 3 active
(myvirtualenv)$ deactivate

# no virtual environment
$ python --version
Python 2.7.17

Using modules

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# no virtual environment
$ python3
>>> import flask
ModuleNotFoundError: No module named 'flask'

# virtual environment
(venv)$ python -m pip install flask
[...]
(venv) bash-4.3$ python -m pip install flask
Collecting flask
Downloading [...]
Successfully installed [...]
(venv)$ python
>>> from flask import Flask
>>> app = Flask(__name__)
(venv)$ deactivate

# no virtual environment again
$ python3
>>> import flask
ModuleNotFoundError: No module named 'flask'

Storing a Virtual Environment configuration

Get the installed packages list and pipe it into the requirements.txt file.

1
pip freeze > requirements.txt

Restoring a Virtual Environment

The virtual environment system encourages you to keep track of the modules you’re using in a requirements.txt file within your project directory.
You can process requirements.txt with pip to handle automated installs of all dependencies:

1
2
3
4
5
6
7
$ cd myproject
$ source ./venv/bin/activate
(venv)$ python -m pip install -r requirements.txt
Installed [...]
$ python
>>> from flask import Flask
>>> import examplepymod

Cheatsheet

Description Command
Create a virtual environment python -m venv /directory/venv
Activate a virtual environment source ./venv/bin/activate
Install required modules (venv)$ python -m pip install -r requirements.txt
Deactivate a virtual environment (venv)$ deactivate
Store an environment configuration pip freeze > requirements.txt