Dependency issues are common among every popular programming language out there including Python. Simply put, when working on multiple projects a certain package might be required by multiple projects with different version. In Python this is handled by using virtual environments.
Prerequisites
- Python 3
- pip
Solution(s)
First, make sure pip is installed.
python -m ensurepip --upgrade
Now, you have two options: pipenv
and virtualenv
.
pipenv
Think of pipenv as a similar tool to Node.js npm, or Ruby’s bundler. It’s a dependency manager that simplifies the dependencies in most cases. Recommended to starts with.
create and initiate environment
Step 1. Install pipenv.
pip install --user pipenv
Step 2. Create a project directory.
mkdir project1
Step 3. Initiate the virtual environment.
pipenv --three
Step 4. Start the virtual env.
pipenv shell
manage packages
To install any package, run:
pipenv install <package>
If you need specific version, run:
pipenv install <package=version>
To install packages from a .txt file usually named requirements.txt
, run:
pipenv install -r requirements.txt
View installed packages / dependencies using one of the following commands:
pipenv graph
pipenv run pip list
Related: Python: pip list vs pip freeze (-all).
Uninstall a package:
pipenv uninstall <package>
exit environment
Exit from the virtual env by typing:
exit
remove environment
To delete the virtual env, run:
pinenv --rm
In case of any leftover files, execute rm -rf
against the pipenv --venv
output.
virtualenv
However, virtualenv is more of a low-level tool, probably a lightweight one.
install and initiate environment
Step 1. Install virtualenv.
pip install --user virtualenv
Step 2. Create a project directory.
virtualenv venv
Step 3. Initiate the virtual environment.
source venv/bin/activate
manage packages
Install any package with:
pip install <package>
If you need specific version, run:
pip install <package=version>
In case you have a requirements.txt
file, run:
pip install -r requirements.txt
To remove any package, run:
pip uninstall <package>
To uninstall anything from requirements.txt
, run:
pip uninstall -r requirements.txt
exit environment
Exit from the virtual env by running:
deactivate
remove environment
If you want to delete the environment as well, run:
rm -rf venv
Conclusion
Strongly recommended not to apply it in a production environment. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.