CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pipdeptree

Command line utility to show dependency tree of packages.

Pending
Overview
Eval results
Files

cli-interface.mddocs/

CLI Interface

Command-line argument parsing and option handling with comprehensive configuration support for controlling dependency tree display and output formats.

Capabilities

Options Class

Configuration object containing all CLI options with type annotations.

class Options(Namespace):
    """Namespace class containing all CLI configuration options."""
    
    # Output format options
    freeze: bool              # Print in pip freeze format
    json: bool               # Output raw JSON
    json_tree: bool          # Output nested JSON tree
    mermaid: bool            # Output Mermaid diagram
    output_format: str | None # GraphViz output format (dot, png, svg, etc.)
    
    # Package selection options  
    python: str              # Python interpreter path
    path: list[str]          # Custom search paths
    packages: str            # Comma-separated package list to show
    exclude: str             # Comma-separated package list to exclude
    exclude_dependencies: bool # Exclude dependencies of excluded packages
    all: bool                # List all deps at top level
    local_only: bool         # Show only virtualenv packages
    user_only: bool          # Show only user site packages
    
    # Display options
    reverse: bool            # Show reverse dependencies
    depth: float             # Limit tree depth
    encoding: str            # Output encoding
    license: bool            # Show package licenses
    
    # Warning control
    warn: WarningType        # Warning level (silence/suppress/fail)

Argument Parsing

Main functions for parsing command-line arguments.

def get_options(args: Sequence[str] | None) -> Options:
    """
    Parse command line arguments and return Options object.
    
    Parameters:
    - args: List of command line arguments (None uses sys.argv)
    
    Returns:
    Options object with parsed configuration
    
    Raises:
    SystemExit: If argument parsing fails or validation errors occur
    """

def build_parser() -> ArgumentParser:
    """
    Build and configure the argument parser.
    
    Returns:
    Configured ArgumentParser instance with all pipdeptree options
    """

Main Entry Point

CLI application entry point for command-line usage.

def main(args: Sequence[str] | None = None) -> int | None:
    """
    CLI - The main function called as entry point.
    
    This function:
    1. Parses command line arguments
    2. Discovers installed packages
    3. Builds dependency tree
    4. Validates for conflicts/cycles
    5. Renders output in requested format
    
    Parameters:
    - args: Command line arguments (None uses sys.argv)
    
    Returns:
    Exit code: 0 for success, 1 for errors/warnings (depending on warn setting)
    """

Enum Action Handler

Custom argparse action for handling enum-based arguments.

class EnumAction(Action):
    """
    Generic action that converts string into Enum value for argparse.
    
    Used for handling WarningType enum values from command line arguments.
    """

Command Line Arguments

Package Selection Arguments

# Interpreter and path options
--python PATH           # Python interpreter to inspect (default: current)
--python auto          # Auto-detect virtual environment
--path PATH            # Restrict package search paths (can be used multiple times)

# Package filtering
-p, --packages PKG     # Comma-separated packages to show (supports wildcards)
-e, --exclude PKG      # Comma-separated packages to exclude (supports wildcards)
--exclude-dependencies # Also exclude dependencies of excluded packages

# Scope limiting
-l, --local-only       # Only show virtualenv packages (if in virtualenv)
-u, --user-only        # Only show user site directory packages

Output Format Arguments

# Text output options
-a, --all              # List all dependencies at top level
-d, --depth N          # Limit tree depth to N levels
-r, --reverse          # Show reverse dependencies
--license              # Show package licenses
--encoding ENC         # Set output encoding

# Alternative output formats
-f, --freeze           # Output in pip freeze format
-j, --json             # Output raw JSON
--json-tree            # Output nested JSON tree
--mermaid              # Output Mermaid flow diagram
--graph-output FMT     # GraphViz output format (dot, png, svg, pdf, etc.)

Warning Control Arguments

-w, --warn LEVEL       # Warning control: silence, suppress (default), fail

Informational Arguments

-v, --version          # Show version information
-h, --help             # Show help message

Usage Examples

Basic Usage

from pipdeptree._cli import get_options, main

# Parse arguments programmatically
options = get_options(['--packages', 'django,requests', '--json'])
print(f"Output format: {'JSON' if options.json else 'text'}")
print(f"Packages: {options.packages}")

# Run full CLI pipeline
exit_code = main(['--reverse', '--packages', 'numpy'])

Command Line Examples

# Show dependency tree for all packages
pipdeptree

# Show specific packages with wildcards
pipdeptree --packages "django*,requests"

# Show what depends on specific packages
pipdeptree --reverse --packages numpy,matplotlib

# Output formats
pipdeptree --json > deps.json
pipdeptree --json-tree > tree.json
pipdeptree --mermaid > deps.mmd
pipdeptree --graph-output png > deps.png

# Filtering and scoping
pipdeptree --local-only --exclude "test*,dev*"
pipdeptree --user-only --depth 2

# Environment and interpreter selection
pipdeptree --python /path/to/venv/bin/python
pipdeptree --python auto  # Auto-detect virtual environment

# Warning control
pipdeptree --warn fail     # Exit with code 1 if conflicts found
pipdeptree --warn silence  # No warning output

Integration with Other Functions

from pipdeptree._cli import get_options
from pipdeptree._discovery import get_installed_distributions
from pipdeptree._models import PackageDAG
from pipdeptree._render import render
from pipdeptree._validate import validate

# Parse CLI options
options = get_options(['--json', '--packages', 'requests'])

# Use options to configure package discovery
distributions = get_installed_distributions(
    interpreter=options.python,
    supplied_paths=options.path or None,
    local_only=options.local_only,
    user_only=options.user_only,
)

# Build and filter tree
tree = PackageDAG.from_pkgs(distributions)
validate(tree)

if options.reverse:
    tree = tree.reverse()

# Apply package filtering
if options.packages or options.exclude:
    include = options.packages.split(",") if options.packages else None
    exclude = set(options.exclude.split(",")) if options.exclude else None
    tree = tree.filter_nodes(include, exclude, options.exclude_dependencies)

# Render output
render(options, tree)

Argument Validation

The CLI performs several validation checks:

# Mutual exclusion validation
if options.exclude_dependencies and not options.exclude:
    parser.error("must use --exclude-dependencies with --exclude")

if options.license and options.freeze:
    parser.error("cannot use --license with --freeze")
    
if options.path and (options.local_only or options.user_only):
    parser.error("cannot use --path with --user-only or --local-only")

Error Handling

The CLI handles various error conditions:

  • Invalid arguments: Argument parser shows usage and exits
  • Interpreter query failures: Returns exit code 1 with error message
  • Include/exclude conflicts: Returns exit code 1 with conflict message
  • Pattern not found warnings: Handled based on warning configuration
  • Dependency conflicts: Exit code determined by warning level setting

Custom Formatter

The CLI uses a custom help formatter for improved readability:

class _Formatter(ArgumentDefaultsHelpFormatter):
    """Custom formatter with wider help display and better positioning."""
    
    def __init__(self, prog: str) -> None:
        super().__init__(prog, max_help_position=22, width=240)

Install with Tessl CLI

npx tessl i tessl/pypi-pipdeptree

docs

cli-interface.md

data-models.md

environment-detection.md

index.md

output-rendering.md

package-discovery.md

validation.md

warning-system.md

tile.json