Python Virtual Environments
Last updated:
Virtual environments are a powerful tool for managing dependencies and keeping your Python projects organized. They create isolated environments to avoid conflicts between different projects and maintain a clean development workspace.
What is a Virtual Environment
Isolated environment allowing one to manage project-specific dependencies and Python versions without interfering with the global Python installation.
Creating a Virtual Environment
python -m venv my_project
ls -al
total 0
drwxr-xr-x 3 paul staff 102B 22 Sep 21:09 ./
drwxr-xr-x 7 paul staff 238B 22 Sep 20:59 ../
drwxr-xr-x 6 paul staff 204B 22 Sep 21:09 my_project/
A new folder was created with the necessary files to set up a virtual environment.
Activate the Virtual Environment
source my_project/bin/activate
Once activated, you should see the name of the virtual environment in parentheses before your terminal prompt:
(my_project) pardel@dev %
Virtual Environment Benefits
- isolation: each virtual environment has its own separate Python interpreter, packages, and configurations.
- dependency management: avoids potential incompatibilities with other projects or the system-wide Python installation.
- reproducible builds: improves the portability and shareability of your projects.
- easier collaboration: sharing or deploying becomes more straightforward - virtual environment contains all the necessary dependencies and configurations.
Deactivate the Virtual Environment
deactivate
The virtual environment is deactivated, and you return to the global Python environment.
Removing a Virtual Environment
rm -rf my_project
TLDR;
Powerful tool for managing dependencies and keeping your Python projects organized - creates isolated environments to avoid conflicts between different projects and maintain a clean development workspace.