How to Push Git Tags to a Remote with Python

Push specified git tags (or all tags) to a remote repository using Python's subprocess module with error handling.

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

Python code

24 lines
Python 3.9+
import subprocess
import sys


def push_tags_to_remote(remote: str = "origin", tags: list[str] | None = None) -> None:
    """
    Push git tags to a remote repository.
    If no tags are given, push all local tags.
    """
    if tags:
        subprocess.run(["git", "push", remote, *tags], check=True)
    else:
        subprocess.run(["git", "push", remote, "--tags"], check=True)
    print(f"Tags pushed successfully to '{remote}'.")


if __name__ == "__main__":
    # Simulate pushing only specific tags (replace with actual tag names as needed)
    demo_tags = ["v1.0.0", "v1.1.0"]
    try:
        push_tags_to_remote("origin", demo_tags)
    except subprocess.CalledProcessError as e:
        print(f"Failed to push tags: {e}", file=sys.stderr)
        sys.exit(1)

Output

stdout
Tags pushed successfully to 'origin'.

How it works

The code uses subprocess.run to execute the git push command with the check=True flag, which raises a CalledProcessError if the command exits with a non-zero status. When a list of tags is provided, they are passed directly to git; otherwise, --tags pushes all local tags. The function prints a confirmation message after success. The script also demonstrates catching errors and exiting with a non-zero code for shell-friendly error handling.

Common mistakes

  • Not using `check=True` so silent failures go unnoticed.
  • Forgetting to handle `CalledProcessError` and exiting with a non-zero code.
  • Passing strings with spaces or special characters without proper quoting.
  • Assuming the remote name exists without verifying it in the git config.

Variations

  1. Use `subprocess.check_call` instead of `run(check=True)` for simpler error handling.
  2. Capture output with `capture_output=True` and `text=True` to log git messages.

Real-world use cases

  • Automating release tagging tasks in CI/CD pipelines to push versioned tags after a successful build.
  • Creating a management script that syncs a known set of tags to a mirror remote or backup repository.
  • Running a pre-deploy step that ensures all release tags are available on the production remote for rollback tracking.

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.