Skip to main content
rule CX Codex

python-script — Claude Code rule: what it does, how to install

python-script defines Python 3.11+ script standards for Claude Code, enforcing package workflows with uv, modern type syntax, and clean CLI structures.

MIT ★ 1,627 updated 2026-10-25

Install into GitHub Copilot · Manually: put the files in place All methods and platforms ↓
.github/instructions/python-script.instructions.md
Open on GitHub

What python-script does

This rule instructs Claude Code to follow Microsoft internal conventions for CLI tools and automation scripts. Direct use of pip install is completely forbidden: dependencies must be added with uv add, and executions must run through uv run. It also requires an active .venv environment in the project root.

File interactions rely exclusively on pathlib.Path rather than os.path. For command-line parsing, the rule dictates isolating argparse setup into a dedicated function for testability, or adopting click when subcommands are present. Type hints must follow modern Python 3.11 syntax, using built-in generics like list[str] and pipe unions instead of old typing imports.

Scripts follow predictable exit codes: 0 for success, 1 for runtime failures, 2 for bad arguments, and 130 on SIGINT. The environment will fail early if a root .venv is missing.

What it helps with

  • enforce uv dependency management instead of raw pip install
  • standardize CLI argument parsing with argparse or click
  • replace os.path calls with modern pathlib.Path methods
  • handle exit codes and SIGINT cleanly in automation scripts

Example prompts for the agent

  • Create a CLI file processor with argparse and verbose logging
  • Refactor this script to use Python 3.11 types and pathlib
  • Build a Click command-line tool with subcommands and explicit exit codes

How to install python-script

Manually: put the files in place

.github/instructions/python-script.instructions.md

The applyTo field sets which files it applies to

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about python-script

How to install python-script in Claude Code?

Save the rule text into .claude/rules/python-script.md inside your project root. Claude Code will automatically attach the instructions whenever modifying **/*.py files.

What does the python-script rule do?

It directs Claude Code to generate Python 3.11+ scripts using uv for dependencies, pathlib for file operations, and Google-style docstrings.

Does this rule allow standard pip commands?

No. The guidelines explicitly forbid running pip install directly and mandate package management through uv.

Source text

python-script.instructions.md · MIT
---
applyTo: '**/*.py'
description: 'Python scripting conventions'
---

# Python Script Instructions

Conventions for Python 3.11+ scripts used in automation, tooling, and CLI applications.

## Environment and Dependency Management

1. **Never use `pip install` directly.** All package management must be handled using `uv` (e.g., `uv add <package>`).
2. **Never run Python scripts or tools outside a virtual environment.** Always execute scripts via `uv run <script.py>` or ensure the 
`.venv` is activated before running.
3. Ensure a `.venv` exists in the project root before executing any Python code. If starting from scratch, refer to the `uv-projects.instructions.md` file for environment setup.

## Entry Points and Exit Codes

```python
import sys

EXIT_SUCCESS = 0  # Successful execution
EXIT_FAILURE = 1  # General failure
EXIT_ERROR = 2    # Arguments or configuration error


def main() -> int:
    """Main entry point for the script."""
    return EXIT_SUCCESS


if __name__ == "__main__":
    sys.exit(main())
```

Standard exit codes: 0 success, 1 failure, 2 configuration error, 130 user interrupt (SIGINT).

## CLI Argument Parsing

### argparse

Extract parser creation into a separate function for testability.

```python
import argparse
from pathlib import Path


def create_parser() -> argparse.ArgumentParser:
    """Create and configure argument parser."""
    parser = argparse.ArgumentParser(description="Process files")
    parser.add_argument("-v", "--verbose", action="store_true")
    parser.add_argument("-o", "--output", type=Path, default=Path("output.txt"))
    parser.add_argument("input_file", type=Path)
    return parser
```

Use `type=Path` for file arguments and `action="store_true"` for boolean flags.

### click

For complex CLIs with subcommands or interactive prompts, use the *click* framework.

```python
import click


@click.command()
@click.option("-v", "--verbose", is_flag=True)
@click.argument("input_file", type=click.Path(exists=True))
@click.pass_context
def main(ctx: click.Context, verbose: bool, input_file: str) -> None:
    """Process input files."""
    ctx.exit(0)  # Explicit exit code
```

Use `@click.group()` for subcommands, `ctx.exit(code)` for exit codes, and `ctx.fail(message)` for errors.

## Logging Configuration

```python
import logging

logger = logging.getLogger(__name__)


def configure_logging(verbose: bool = False) -> None:
    """Configure logging based on verbosity level."""
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(level=level, format="%(levelname)s: %(message)s")
```

Create module-level logger, configure early in main. For file logging, add *FileHandler* to the root logger.

## Path Handling

Use *pathlib.Path* exclusively; avoid *os.path*.

```python
from pathlib import Path


def process_file(path: Path) -> None:
    """Read, process, and write file content."""
    content = path.read_text(encoding="utf-8")
    processed = transform_content(content)
    output_path = path.with_suffix(".out")
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(processed, encoding="utf-8")
```

Common patterns: `cwd()`, `resolve()`, `exists()`, `is_dir()`, `is_file()`, `iterdir()`, `glob()`, `rglob()`, `read_text()`, `write_text()`, `mkdir(parents=True, exist_ok=True)`, `parent`, `name`, `stem`, `suffix`.

## Subprocess Execution

Use *subprocess.run()* with error handling.

```python
import subprocess
import os
from pathlib import Path


def run_command(cmd: list[str], cwd: Path | None = None, extra_env: dict[str, str] | None = None) -> str:
    """Run command and return stdout, raising on failure."""
    env = os.environ.copy()
    if extra_env:
        env.update(extra_env)
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True, cwd=cwd, env=env)
        return result.stdout
    except subprocess.CalledProcessError as e:
        logger.error("Command failed: %s\nstderr: %s", e.returncode, e.stderr)
        raise
    except FileNotFoundError:
        logger.error("Command not found: %s", cmd[0])
        raise
```

Use `capture_output=True` and `text=True` for string output. Use `check=True` to raise on non-zero exit.

## Type Hints

Use Python 3.11+ syntax with built-in generics.

```python
from pathlib import Path
from typing import Literal, Self


def process_items(items: list[str]) -> dict[str, int]:  # Built-in generics
    return {item: len(item) for item in items}


def read_file(path: str | Path) -> str:  # Union with pipe
    return Path(path).read_text(encoding="utf-8")


def find_config(name: str) -> Path | None:  # Optional with pipe
    config = Path(name)
    return config if config.exists() else None


def set_level(level: Literal["debug", "info", "warning"]) -> None:  # Constrained values
    pass


class Builder:
    def add(self, item: str) -> Self:  # Fluent interface
        self.items.append(item)
        return self
```

Use `list[str]` not `typing.List[str]`, `str | None` not `Optional[str]`, `Literal` for constrained values, `Self` for chained methods.

## Error Handling

Handle interrupts and pipe errors at the top level.

```python
import sys


def main() -> int:
    """Main entry point with error handling."""
    try:
        return run()
    except KeyboardInterrupt:
        print("\nInterrupted by user", file=sys.stderr)
        return 130
    except BrokenPipeError:
        sys.stderr.close()
        return 1
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1
```

Custom exceptions can carry exit codes:

```python
class ScriptError(Exception):
    def __init__(self, message: str, exit_code: int = 1) -> None:
        super().__init__(message)
        self.exit_code = exit_code
```

## Documentation

Use Google-style docstrings with Args, Returns, Raises, and Example sections.

```python
def process_data(data: list[str], *, normalize: bool = False) -> dict[str, int]:
    """Process input data and return statistics.

    Args:
        data: List of strings to process.
        normalize: If True, normalize values before processing.

    Returns:
        Dictionary mapping processed items to their counts.

    Raises:
        ValueError: If data is empty.

    Example:
        >>> process_data(["a", "b", "a"])
        {'a': 2, 'b': 1}
    """
```

Include module docstrings with description, usage, and examples.

## Script Organization

Organize scripts in this order:

1. Shebang: `#!/usr/bin/env python3`
2. Copyright header: `# Copyright (c) 2026 Microsoft Corporation. All rights reserved.`
3. SPDX license identifier: `# SPDX-License-Identifier: MIT`
4. PEP 723 inline script metadata (if applicable)
5. Future imports: `from __future__ import annotations`
6. Imports: standard library, third-party, local (separated by blank lines)
7. Constants and exit codes
8. Module-level logger
9. Helper functions
10. Parser creation function
11. Logging configuration function
12. Run logic function
13. Main entry point
14. Module guard: `if __name__ == "__main__": sys.exit(main())`

## Inline Script Metadata

PEP 723 inline metadata enables automatic dependency installation with *uv*.

```python
#!/usr/bin/env python3
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "click>=8.0",
#     "rich>=13.0",
# ]
# ///
```

Place after copyright and SPDX headers, before module docstring. Run with `uv run script.py`.

© microsoft · MIT · microsoft/hve-core

Similar IDE rules

All IDE rules for Programming languages →

From the same set148

The whole set →
python-tests python-tests sets pytest authoring conventions: AAA test structure, given-when-then naming, and when to reach for mocker, monkeypatch or MagicMock. CX Codex +1 ★ 1,627repo stars vex OpenVEX v0.2.0 reference and management playbooks for structuring, checking, and validating vulnerability statements. CX Codex +1 ★ 1,627repo stars rust-tests This rule sets conventions for Rust tests, from module placement and naming to fixtures and HTTP mocks. Use it when you want tests in a project to follow the same structure. CX Codex +1 ★ 1,627repo stars CVE Analyzer CVE Analyzer — a subagent for deep CVE analysis: checks if vulnerable code is reachable in the project and returns evidence-backed VEX status. CX Codex +1 ★ 1,627repo stars hve-artifact-authoring The hve-artifact-authoring skill guides the creation and validation of HVE Core agents, prompts, instructions, and skills. Use it when preparing an artifact in the repository and checking it against project conventions. CX Codex +1 ★ 1,627repo stars vex-generation The vex-generation rule guides AI-assisted VEX triage with evidence requirements, confidence bands, and status constraints. Use it when an agent drafts vulnerability findings for human review. CX Codex +1 ★ 1,627repo stars dataops Microsoft DataOps and DS/MLOps testing reference: where to validate data, how to write pipeline tests, and how to tell validation errors from drift. CX Codex +1 ★ 1,627repo stars session-log-canvas-update session-log-canvas-update diffs Copilot session event schemas against the canvas baseline. Keeps the Session Log canvas in sync across Copilot runtime updates. CX Codex +1 ★ 1,627repo stars

Project sponsors

Companies that keep this analytics open