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.
Python code
44 linesimport 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
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
- Use `subprocess.run` with `capture_output=True` for more control over stderr
- 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
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Build a Simple Log Graph in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
Keep learning
Related tutorials and quizzes for this topic.