How to stage and commit all changes with Git in Python

Run git add -A and git commit from Python using subprocess to automate staging and committing all file changes in one step.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 12 views 0 copies

Python code

20 lines
Python 3.9+
import subprocess
from pathlib import Path

def stage_and_commit_all(commit_message: str) -> None:
    """Stage all changes and create a commit with the given message."""
    repo_root = Path.cwd()
    if not (repo_root / ".git").exists():
        raise RuntimeError("Not inside a Git repository")

    subprocess.run(["git", "add", "-A"], check=True, cwd=repo_root)
    subprocess.run(
        ["git", "commit", "-m", commit_message],
        check=True,
        cwd=repo_root
    )
    print(f"Committed all changes with message: '{commit_message}'")

if __name__ == "__main__":
    # Example usage
    stage_and_commit_all("Auto-commit: staged all changes")

Output

stdout
$ python stage_commit.py
Committed all changes with message: 'Auto-commit: staged all changes'

$ git log --oneline -1
abc1234 Auto-commit: staged all changes

How it works

The subprocess.run call executes Git commands in the shell with check=True, which raises CalledProcessError if any command fails — giving you immediate feedback. The cwd=repo_root argument ensures commands run from the repository root even if the script is invoked from a subdirectory. Checking for the .git directory first prevents a confusing Git error when the script runs outside a repo. Using git add -A stages new, modified, and deleted files, so the commit captures the full working tree state.

Common mistakes

  • Running `git add` without the `-A` flag, which misses deleted files
  • Forgetting `cwd=repo_root` when the script runs from a different directory
  • Not checking for `cwd` validity or `.git` existence before invoking Git

Variations

  1. Use `git commit -a -m` to commit all tracked changes without staging, but new files are not included
  2. Add `--allow-empty` to the commit command to allow commits when nothing changed

Real-world use cases

  • Automating daily checkpoints in a data pipeline by committing processed outputs to a repo.
  • Creating a pre-deploy hook that stages and commits config changes before release.
  • Building a team onboarding script that commits an initial project scaffold automatically.

Sponsored

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.