How to Create a Git Commit with Message Template in Python

Run a git commit from Python using a standardized message template built from a commit type and description.

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

Python code

16 lines
Python 3.9+
import subprocess
import sys


def commit_with_template(commit_type: str, description: str) -> None:
    message = f"{commit_type}: {description}"
    try:
        subprocess.run(["git", "commit", "-m", message], check=True)
        print(f"Committed: {message}")
    except subprocess.CalledProcessError as e:
        print(f"Commit failed: {e}")
        sys.exit(1)


if __name__ == "__main__":
    commit_with_template("feat", "add commit message template script")

Output

stdout
Committed: feat: add commit message template script

How it works

This script uses subprocess.run to execute the git commit command in the shell. The check=True argument makes the call raise a CalledProcessError if the commit fails, which is caught and printed before exiting with a non-zero status. F-strings build the commit message template as type: description, enforcing a consistent conventional commit style. The if __name__ == "__main__" guard ensures the function only runs when invoked as a script, keeping it reusable as a module.

Common mistakes

  • Forgetting `check=True`, so failures are silent and the script exits 0
  • Using `git commit -am` with untracked new files, which won't be included
  • Not handling the case where there's nothing to commit, causing a CalledProcessError

Variations

  1. Add `-a` flag to auto-stage modified files with `git commit -am`
  2. Prompt for the commit type interactively with `input()` for flexibility

Real-world use cases

  • Enforce a consistent commit convention across a team by wrapping git commit in a standardized script.
  • Automate release commits that follow a version bump pattern, such as 'release: 1.2.0'.
  • Build a pre-commit hook that validates or formats commit messages generated by CI tools.

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.