Fetch Pull Rebase Workflow Script in Python

A Python script that automates the git fetch, checkout, and pull with rebase workflow using subprocess.

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

Python code

35 lines
Python 3.9+
import subprocess
import sys


def run_git_command(args: list[str]) -> str:
    """Run a git command and return its stdout, or raise on failure."""
    result = subprocess.run(
        ["git", *args],
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode != 0:
        print(f"Error: git {' '.join(args)} failed:\n{result.stderr}", file=sys.stderr)
        sys.exit(1)
    return result.stdout.strip()


def fetch_pull_rebase(remote: str = "origin", branch: str = "main") -> None:
    """Mock a fetch-and-rebase workflow using real git commands."""
    print(f"Fetching from {remote}...")
    run_git_command(["fetch", remote])

    print(f"Checking out {branch}...")
    run_git_command(["checkout", branch])

    print(f"Pulling with rebase from {remote}/{branch}...")
    run_git_command(["pull", "--rebase", remote, branch])

    print("Workflow completed successfully.")


if __name__ == "__main__":
    # Example invocation — replace with your actual remote/branch as needed
    fetch_pull_rebase("origin", "main")

Output

stdout
Fetching from origin...
Checking out main...
Pulling with rebase from origin/main...
Workflow completed successfully.

How it works

The script uses subprocess.run to execute git commands and captures stdout/stderr. It checks the return code and exits with an error message if any command fails. The strip() method cleans trailing newlines from output, and the script is structured as reusable functions for clarity.

Common mistakes

  • Forgetting to include check=False, which can cause unexpected exceptions.
  • Hardcoding remote and branch names instead of making them parameters.
  • Not capturing stderr, making it hard to debug failures.

Variations

  1. Use subprocess.call for simpler cases without capturing output.
  2. Add a --dry-run flag to print commands without executing them.

Real-world use cases

  • Automating daily sync of a local feature branch with upstream changes before starting work.
  • Running a rebase-based pull as part of a CI/CD pipeline to ensure clean history before tests.
  • Syncing multiple repositories with a single script in a monorepo environment.

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.