Python Virtual Environments
Overview
These are used to isolate environments and resolve dependency conflict resolution.
- Ensures projects have isolated siloes where they live
- Projects have their own dependency tree that don't interfere with one another.
Python Dependencies
You will often use 3rd-party libraries which doesn't come along with Python. You'll have to import and install them before they can be used.
- Normally installed using pip or easy_install
- Libraries are pulled from the pupi.org or Python Package Index
Installing Libraries
To install a library, as example, django:
pip install django
To install a specific version of django:
pip install django==2.2.12
To check the version of Django installed, you can run any of the commands below:
django --version
python -m django --version
You can also view the versions of all installed packages, including Django:
pip freeze
python -m pip freeze
To save all of these data (versions of each modules) to be reused or processed later, you can forward them to a file.
pip freeze > module-versions.txt
To upgrade to a newer version:
pip install --upgrade django
To uninstall it, don't delete the folder, instead:
pip uninstall django
Another example: installing the "site" library:
import site
print(site.getsitepackages())
Using a requirements.txt
Another way to install multiple third parties with just a single command is to put them into a single requirements.txt file and use pip to to do a bulk-install. Note that it's recommended to install modules for a project in a virtual environment.
To install from a requirements file:
pip install -r requirements.txt