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.
Python code
24 linesimport 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
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
- Use `subprocess.check_call` instead of `run(check=True)` for simpler error handling.
- 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
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.