Virtual environments
What is a “virtual environment”?
Virtual environments allow us to create isolated installations of Python, along with installed modules. We often create virtual environments for specific projects—so that installing or uninstalling modules for one project does not break the other project.
To create virtual environments, we use Python’s venv
module.
The
venv
module supports creating lightweight “virtual environments”, each with their own independent set of Python packages installed in their site directories. A virtual environment is created on top of an existing Python installation, known as the virtual environment’s “base” Python, and may optionally be isolated from the packages in the base environment, so only those explicitly installed in the virtual environment are available.When used from within a virtual environment, common installation tools such as
pip
will install Python packages into a virtual environment without needing to be told to do so explicitly.
The syntax for creating a virtual environment is straightforward. At a command prompt,
$ python -m venv [name of or path to environment]
where $
represents the command prompt, and we substitute in the name of the environment we wish to create. So if we want to create a virtual environment called “cs021” we’d use this command:
$ python -m venv cs021
python
…
On some systems, python
might be named python3
. If you find yourself in that situation, just substitute python3
for python
wherever it appears in the instructions.
To use a virtual environment, we activate it.
On macOS
$ . ./cs021/bin/activate
(cs021) $
On Windows (with PowerShell)
PS C:\your\path\here > .\cs021\Scripts\activate
(cs021) PS C:\your\path\here >
Notice that in each case after activation, the command prompt changed. The prefix, in this case (cs021)
indicates the virtual environment that is currently active.
To deactivate, use the deactivate
command.
For more on virtual environments and venv
see the Python documentation for creation of virutal environments
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.