How to Get Git Status and Log in Python

A beginner-friendly helper that runs git status and git log from Python using subprocess, with safe handling for non-repo directories.

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

Python code

36 lines
Python 3.9+
import subprocess
from pathlib import Path


def git_status(path: str = ".") -> str:
    """Return the current git status as a string."""
    result = subprocess.run(
        ["git", "status", "--short"],
        cwd=path,
        capture_output=True,
        text=True
    )
    return result.stdout.strip() or "No changes"


def git_log(path: str = ".", count: int = 5) -> str:
    """Return the last `count` git commit messages."""
    result = subprocess.run(
        ["git", "log", f"-{count}", "--oneline"],
        cwd=path,
        capture_output=True,
        text=True
    )
    return result.stdout.strip()


if __name__ == "__main__":
    print("Git status:")
    print(git_status())

    current_dir = Path(__file__).parent
    if (current_dir / ".git").exists():
        print("\nRecent commits:")
        print(git_log())
    else:
        print("\nNot a git repository — skipping commit log.")

Output

stdout
Git status:
 M README.md

Recent commits:
5f3a2b1 Add new feature
c9e8d7f Fix typo in docs
ab12cd3 Update README

How it works

This script uses subprocess.run to execute git commands and capture their output. The capture_output=True and text=True arguments collect stdout as a string, making it easy to print or process. The cwd parameter lets you run git in a specific directory, defaulting to the current one. The git_status function returns No changes when there are no modifications, while git_log returns the last N commit messages. The if __name__ == "__main__" guard runs the code only when the script is executed directly, not when imported.

Common mistakes

  • Forgetting to use `cwd` to run git in the right directory
  • Not checking `returncode` to handle git errors gracefully
  • Assuming `.git` exists without verifying the repo state
  • Using `shell=True` unnecessarily, which can lead to injection risks

Variations

  1. Use `git.log()` from the GitPython library for a more object-oriented approach
  2. Capture stderr separately to parse error messages from git

Real-world use cases

  • A pre-commit hook that checks if there are uncommitted changes before allowing a commit.
  • A CI script that logs recent commits to a deployment notice when new code is released.
  • A developer tool that shows the current branch and pending changes in an IDE extension.

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.