Published on

Pipenv Cheat Sheet

Table of Contents

Pipenv Cheat Sheet: Streamlining Python Dependency Management

Pipenv is a powerful tool that simplifies Python package management and virtual environment handling. It combines the best of pip, virtualenv, and requirements.txt to streamline your development workflow.

Why Use Pipenv?

  • Automatic Virtual Environments: Pipenv creates and manages project-specific virtual environments, ensuring your dependencies are isolated.
  • Dependency Tracking with Pipfile: Pipenv maintains a Pipfile that clearly lists your project's direct dependencies.
  • Deterministic Builds with Pipfile.lock: Pipenv generates a Pipfile.lock that records the exact versions of all dependencies, ensuring consistent installations across environments.

Getting Started with Pipenv

Installation

Install Pipenv using pip:

pip install pipenv

Project Setup

  1. Create a New Project: Navigate to your project directory and run:

    pipenv install
    

    This creates a Pipfile and an empty virtual environment for your project.

  2. Activate Virtual Environment:

    pipenv shell
    

Managing Dependencies

Installing Packages

  • Install a Package:

    pipenv install <package_name>
    
  • Install a Specific Version:

    pipenv install <package_name>==<version>
    
  • Install Development Dependencies:

    pipenv install --dev <package_name>
    

Updating Packages

  • Update Specific Package:

    pipenv update <package_name>
    
  • Update All Packages:

    pipenv update
    

Uninstalling Packages

pipenv uninstall <package_name>

Listing Installed Packages

pipenv graph 

Advanced Pipenv Features

Dependency Locking (Pipfile.lock)

  • Generate Pipfile.lock: After installing or updating packages, run:

    pipenv lock
    

Running Commands in the Virtual Environment

  • Run a Python Script:

    pipenv run python <script_name>.py
    

Specifying Python Versions

  • Specify Python Version: In your Pipfile:
    [requires]
    python_version = "3.9" 
    

Checking for Security Vulnerabilities

pipenv check

Tips and Tricks

  • Working with Requirements.txt: If you have an existing requirements.txt, you can install all dependencies with:

    pipenv install -r requirements.txt
    
  • Environment Variables: Set environment variables within Pipenv using:

    pipenv shell --python <path_to_python_executable>
    

Troubleshooting

  • Uninstalling All Packages:
pipenv uninstall --all
  • Removing Virtual Environment:
pipenv --rm
  • Resolving Dependency Conflicts: Pipenv usually handles conflicts automatically, but if issues arise, try:

    pipenv update --prune
    
  • Ignoring Pipfile: Install without considering the Pipfile:

    pipenv install --ignore-pipfile