Get Git Status Info in Python

Run git commands from Python to gather branch name, number of changes, total commits, and clean status, returning them as a dict.

Easy Python 3.9+ Aug 9, 2026 Git + Python 12 views 0 copies

Python code

44 lines
Python 3.9+
import subprocess
import json
from pathlib import Path


def get_git_status(repo_path="."):
    """Return basic git info about a repository as a dict."""
    try:
        branch = subprocess.check_output(
            ["git", "branch", "--show-current"],
            cwd=repo_path,
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()

        status = subprocess.check_output(
            ["git", "status", "--porcelain"],
            cwd=repo_path,
            stderr=subprocess.DEVNULL,
            text=True,
        )

        commits = subprocess.check_output(
            ["git", "rev-list", "--count", "HEAD"],
            cwd=repo_path,
            stderr=subprocess.DEVNULL,
            text=True,
        ).strip()

        return {
            "branch": branch or "(detached)",
            "tracked_changes": len([line for line in status.splitlines() if line]),
            "total_commits": int(commits),
            "is_clean": not status.strip(),
        }
    except subprocess.CalledProcessError:
        return {"error": "Not a git repository"}


if __name__ == "__main__":
    repo_path = Path(__file__).parent if "__file__" in globals() else "."
    result = get_git_status(repo_path)
    print(f"Git info for {repo_path}:")
    print(json.dumps(result, indent=2))

Output

stdout
Git info for .:
{
  "branch": "main",
  "tracked_changes": 2,
  "total_commits": 42,
  "is_clean": false
}

How it works

This helper uses subprocess.check_output to run git commands in a given folder and capture their output. git branch --show-current returns the current branch name, git status --porcelain lists changed files (each line is one change), and git rev-list --count HEAD gives the total commit count. We strip whitespace and convert numbers to int before building the dict. If any command fails, we catch CalledProcessError and return an error dict — handy when run outside a repo.

Common mistakes

  • Forgetting to pass `cwd` so git runs in the correct directory
  • Not catching `CalledProcessError` when the folder isn't a repository
  • Confusing `git status --porcelain` output with `git diff` (porcelain includes untracked files)

Variations

  1. Use `subprocess.run` with `capture_output=True` for more control over stderr
  2. Wrap the logic in a class to reuse across many repos

Real-world use cases

  • Showing repo health in a developer tool or dashboard.
  • Triggering CI or build steps only when the working tree is clean.
  • Auditing multiple repositories in a loop to find dirty or detached states.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.