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.
Python code
36 linesimport 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
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
- Use `git.log()` from the GitPython library for a more object-oriented approach
- 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
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.