How To

Install and Use Pipenv for Python on Linux

Pipenv is a packaging tool for Python that combines virtual environment management and dependency tracking into a single workflow. It replaces the manual use of pip and virtualenv by automatically creating and managing a virtualenv for your projects, adding and removing packages from a Pipfile as you install and uninstall them, and generating the deterministic Pipfile.lock for reproducible builds.

Original content from computingforgeeks.com - post 2092

This guide covers how to install Pipenv on Linux and use it for day-to-day Python project management. The steps work on Ubuntu, Debian, Fedora, Arch Linux, Rocky Linux, AlmaLinux, and RHEL. We cover dependency management, virtual environments, environment variables, importing from requirements.txt, and a comparison with alternative tools like Poetry and venv.

Prerequisites

  • A Linux system running Ubuntu, Debian, Fedora, Arch, Rocky Linux, AlmaLinux, or RHEL
  • Python 3.8 or later installed
  • pip installed (comes with Python 3.4+ but some distros ship it separately)
  • Sudo or root access for system-wide installation

Step 1: Install Pipenv on Linux

There are several ways to install Pipenv depending on your distribution and preference. The pip method works everywhere, while native package managers provide system-integrated packages on supported distros.

Install Pipenv using pip (all distributions)

The recommended cross-distro method is installing through pip. This gives you the latest version regardless of your distribution:

pip install --user pipenv

The --user flag installs Pipenv to your home directory under ~/.local/bin. Make sure this path is in your PATH environment variable. Add it to your shell profile if needed:

echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

Install Pipenv on Ubuntu / Debian

Ubuntu and Debian ship Pipenv in their default repositories:

sudo apt update
sudo apt install pipenv

Install Pipenv on Fedora

Fedora includes Pipenv in its default repos:

sudo dnf install pipenv

Install Pipenv on RHEL / Rocky Linux / AlmaLinux

On RHEL-family distributions, install via pip since Pipenv is not in the default repos:

sudo dnf install python3-pip
pip3 install --user pipenv

Install Pipenv on Arch Linux / Manjaro

On Arch-based distributions, install from the official repositories:

sudo pacman -S python-pipenv

Verify the installation

Confirm Pipenv is installed and accessible by checking its version:

pipenv --version

You should see output showing the installed version:

pipenv, version 2024.4.0

Step 2: Create a New Python Project with Pipenv

Pipenv manages a virtual environment per project directory. Start by creating a project folder and initializing a Pipenv environment inside it:

mkdir ~/myproject
cd ~/myproject
pipenv install

This creates two files in the directory – Pipfile and Pipfile.lock – and sets up a virtual environment. Pipenv stores virtualenvs in ~/.local/share/virtualenvs/ by default.

To use a specific Python version, pass the --python flag:

pipenv install --python 3.12

Check which virtualenv Pipenv created for the project:

pipenv --venv

The output shows the full path to the virtualenv directory:

/home/user/.local/share/virtualenvs/myproject-a1b2c3d4

Step 3: Manage Dependencies with Pipenv

Pipenv handles installing, removing, and updating packages while automatically updating your Pipfile and Pipfile.lock.

Install a package

Add a package to your project. This installs it into the virtualenv and records it in Pipfile:

pipenv install requests

Install a development-only package

Development dependencies like linters and test frameworks should be installed with the --dev flag. They go into a separate [dev-packages] section in Pipfile and are not installed in production:

pipenv install pytest --dev
pipenv install black --dev

Install a specific version

Pin a package to a specific version when your project requires it:

pipenv install requests==2.31.0

Remove a package

Uninstall a package and remove it from the Pipfile:

pipenv uninstall requests

Update packages

Update all packages to their latest allowed versions and regenerate the lock file:

pipenv update

To update a single package:

pipenv update requests

List installed packages

View all installed packages and their dependency tree:

pipenv graph

The output shows each top-level package and its sub-dependencies:

requests==2.31.0
  - certifi [required: >=2017.4.17, installed: 2024.2.2]
  - charset-normalizer [required: >=2,<4, installed: 3.3.2]
  - idna [required: >=2.5,<4, installed: 3.6]
  - urllib3 [required: >=1.21.1,<3, installed: 2.2.1]

Step 4: Understand Pipfile and Pipfile.lock

Pipenv uses two files to track dependencies. Understanding both is key to managing Python projects correctly.

The Pipfile is the human-readable dependency file. Open it to see the current project configuration:

cat Pipfile

A typical Pipfile looks like this:

[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
requests = "*"

[dev-packages]
pytest = "*"
black = "*"

[requires]
python_version = "3.12"

The [packages] section lists production dependencies. The [dev-packages] section lists development-only dependencies. The "*" means any version is acceptable.

The Pipfile.lock is auto-generated and pins every dependency (including transitive ones) to exact versions with SHA256 hashes. This ensures every developer and deployment gets identical packages. Never edit Pipfile.lock manually - it gets regenerated when you run pipenv install or pipenv lock.

Commit both Pipfile and Pipfile.lock to version control. The Pipfile defines what you want, and the lock file defines exactly what gets installed.

Step 5: Activate the Virtual Environment with pipenv shell

The pipenv shell command spawns a new shell subprocess with the virtualenv activated. This is the standard way to work inside the project environment interactively:

cd ~/myproject
pipenv shell

Your shell prompt changes to indicate the active virtualenv:

(myproject) user@host:~/myproject$

Now any python or pip command runs inside the virtualenv. To confirm, check the Python path:

which python

The path points to the virtualenv Python binary instead of the system one:

/home/user/.local/share/virtualenvs/myproject-a1b2c3d4/bin/python

Exit the virtualenv shell by typing exit or pressing Ctrl+D.

Step 6: Run Commands with pipenv run

If you do not want to activate a full shell session, use pipenv run to execute a single command inside the virtualenv. This is useful for scripts, CI pipelines, and one-off commands:

pipenv run python app.py

Run tests with pytest through Pipenv:

pipenv run pytest

Format code with black:

pipenv run black .

You can also define custom script shortcuts in your Pipfile under a [scripts] section:

[scripts]
start = "python app.py"
test = "pytest -v"
format = "black ."

Then run them by name:

pipenv run start
pipenv run test

Step 7: Import from requirements.txt

If you have an existing project that uses a requirements.txt file, Pipenv can import it directly. Run pipenv install in a directory that contains a requirements.txt and Pipenv detects and imports it automatically:

cd /path/to/existing-project
pipenv install

Pipenv reads the requirements.txt, creates a Pipfile with the same packages, and generates a lock file. If you have a separate dev requirements file, import it separately:

pipenv install -r dev-requirements.txt --dev

To go the other direction and export from Pipenv back to a requirements.txt (useful for deployment tools that need it), run:

pipenv requirements > requirements.txt

For dev dependencies:

pipenv requirements --dev > dev-requirements.txt

Step 8: Load Environment Variables from .env Files

Pipenv automatically loads a .env file from the project root when you run pipenv shell or pipenv run. This is useful for storing database credentials, API keys, and configuration that should not be committed to version control.

Create a .env file in your project directory:

vi .env

Add your environment variables:

DATABASE_URL=postgresql://localhost:5432/myapp
SECRET_KEY=your-secret-key-here
DEBUG=true

These variables are available inside any pipenv run or pipenv shell session. Access them in Python with os.environ:

import os
db_url = os.environ.get("DATABASE_URL")
print(db_url)

Add .env to your .gitignore to prevent secrets from being committed to your repository. You can create a .env.example file with placeholder values for other developers to reference.

Step 9: Pipenv vs Poetry vs venv - Comparison

Python has several environment and dependency management tools. Here is how Pipenv compares with venv (built into Python) and Poetry (another popular third-party tool):

FeaturePipenvPoetryvenv + pip
Virtual environment managementAutomaticAutomaticManual (python3 -m venv)
Lock file for reproducible buildsPipfile.lockpoetry.lockpip freeze > requirements.txt (manual)
Dependency resolutionYesYes (faster resolver)No (pip installs in order)
Dev vs production dependenciesYes ([dev-packages])Yes (dependency groups)Separate requirements files
.env file loadingBuilt-inPlugin neededNo
Package publishing (PyPI)NoYes (build + publish)No (needs twine)
Custom scriptsYes ([scripts] in Pipfile)Yes ([tool.poetry.scripts])No
Config file formatPipfile (TOML)pyproject.tomlrequirements.txt (plain text)
Maintained byPyPACommunityPython core (stdlib)

When to pick Pipenv: Application development where you need deterministic builds, automatic virtualenv management, and .env file support without building/publishing packages. It is the official PyPA recommendation for application dependency management.

When to pick Poetry: Library development where you need to build and publish packages to PyPI, or projects that want a single pyproject.toml for all configuration.

When to pick venv + pip: Simple scripts, quick prototyping, or environments where you cannot install third-party tools.

Useful Pipenv Commands Reference

Here is a quick reference of the most common Pipenv commands for daily use:

CommandDescription
pipenv installCreate virtualenv and install from Pipfile
pipenv install packageInstall a package and add to Pipfile
pipenv install --dev packageInstall a dev-only package
pipenv uninstall packageRemove a package from virtualenv and Pipfile
pipenv updateUpdate all packages to latest allowed versions
pipenv lockRegenerate Pipfile.lock without installing
pipenv shellActivate the virtualenv in a new shell
pipenv run commandRun a command inside the virtualenv
pipenv graphShow dependency tree
pipenv checkCheck for security vulnerabilities
pipenv --rmDelete the virtualenv
pipenv --venvShow virtualenv path
pipenv --whereShow project directory
pipenv requirementsExport to requirements.txt format

Conclusion

Pipenv brings dependency management and virtual environments together under one tool, eliminating the need to juggle pip freeze, requirements.txt, and manual virtualenv activation. The lock file guarantees deterministic installs across development machines and production servers.

For production deployments, consider running pipenv install --deploy which aborts if the Pipfile.lock is out of date, and pipenv install --ignore-pipfile which installs strictly from the lock file without resolving dependencies again. Pair this with Docker containers for fully reproducible deployment environments.

Related Articles

Linux Mint How To Install PHP on Linux Mint 22 Programming Using Apache Maven – Commands With Examples Programming Draw Graphs in Linux Terminal with Termgraph Programming How difficult is it to build a successful mobile app?

Leave a Comment

Press ESC to close