Python pipenv tutorial: manage dependencies like a pro
When you're working with Python, you need to install packages and manage dependencies. If you have several projects, dependencies can clash and cause problems. I'll tell you how pipenv solves this issue.
Introduction
When you're working on a Python project and need to install a package, you typically run python3 -m pip install <package>
. What happens if two projects depend on different versions of the same package? Problems can arise.
This is where "virtual envs" or "venv" were created, allowing you to have different versions of Python with their respective packages on the same computer.
In this case, pipenv
is a quite popular tool that allows you to manage Python virtual environments on your computer, similar to npm
in the Node ecosystem.
I'll explain the basic concepts so you can use it too.
Tutorial: how to use pipenv
First, install pipenv
with the following command:
python3 -m pip install pipenv
With this, you can use the pipenv command to manage environments. Keep reading!
In my case, it didn't work because the python folder of my user is not in the path. Just run the command
python -m site --user-base
and add the path it provides and add /bin at the end, to your PATH variables, in my case:export PATH="/Users/alberto/Library/Python/3.9/bin:$PATH"
.
Now, the basic commands you need to know:
Install dependencies
This command creates a virtual environment if one doesn't exist, so you can launch it directly.
pipenv install <package>
Activate a virtual environment
pipenv shell
Once inside, you can run:
python file.py
Run a file
pipenv run python file.py
Create a virtual environment
pipenv --python <version>
Delete a virtual environment
pipenv --rm
Virtualenv
There's another lower-level tool called virtualenv
that allows you to create directories containing all the dependencies to run the project with a specific python version.
Here's a link with all the documentation for the tool.
Summary
In my case, I use pipenv when needed since it's the most convenient. This reminds me of when I started working where we had different projects, all with Python, virtualenv, and docker.
Did you find this article useful? Subscribe to my newsletter and take the first step to launch IT products faster. You will receive exclusive tips that will bring you closer to your goals.