venv for Python Virtual Environments
November 3, 2024•189 words
The venv
library is part of the Python standard library suites for creating reproducible environments in terms of package dependencies.
Suppose you have a folder for a Python project. The following command creates a new virtual environment.
python -m venv /path/to/new/virtual/environment
Then, use the following command to activate (or "enter") this virtual environment.
source /path/to/new/virtual/environment/bin/activate
Now we are working in an isolated Python environment: everything Python-related will be contained here. For example, import pandas as pd
won't work unless pandas
is specifically installed in this virtual environment (even if it's already installed elsewhere). Conversely, packages installed within this environment only will not be accessible from the outside.
Once the virtual environment is activated, the usual pip install
will put the installed packages in the virtual environment (as opposed to the default system directory or a different project).
The following pair of commands are useful for taking a snapshot of all package dependencies in the current virtual environment and re-installing them exactly as specified.
pip freeze > requirements.txt
pip install -r requirements.txt
Finally, use the deactivate
command to deactivate (or "exit") the virtual environment.