Automating some git commands with Python

Last Updated : 28 Apr, 2025

Git is a powerful version control system that developers widely use to manage their code. However, managing Git repositories can be a tedious task, especially when working with multiple branches and commits. Fortunately, Git's command-line interface can be automated using Python, making it easier to manage your code and automate common tasks.

One popular library for automating Git commands with Python is GitPython. It provides an easy-to-use interface for interacting with Git repositories, allowing you to perform tasks such as creating branches, committing changes, and merging branches.

To start automating Git commands with Python, you will first need to install GitPython by running the following command:

pip install GitPython

 

Automate Git Commands with Python

1. Initialize and open a local repository

  • To initialize a new repository
Python3
from git import Repo
new_repo = Repo.init('/path/to/new/repo_directory')
  • To Open the Existing local repository
Python3
from git import Repo
existing_repo = Repo('path/to/existing/repo')

2. Clone a remote Repository

To create a local copy of the repository at the specified local_path directory, using the repository URL repo_url

import git
repo = gitRepo.clone_from('https://github.com/username/repository', '/path/to/local/directory')

Example:

Python3
import git

# Clone a remote repository
repo_url = "https://github.com/Hardik-Kushwaha/GIT_Python_Automation"
local_path = "/home/hardik/GFG_Temp/Cloned_Repo"
repo = git.Repo.clone_from(repo_url, local_path)
print(f'Repository Cloned at location: {local_path}')

Output:

Repository Cloned at location: /home/hardik/GFG_Temp/Cloned_Repo

Verify: Go to the location where you cloned the repository to verify it.

 

3. Add and Commit files

Add Files: Add the specified files to the index, preparing them to be committed.

repo.index.add(['file1', 'file2'])

Add Commit:  Create a new commit in the local repository with the specified commit message.

repo.index.commit('Your Commit Message')

Example:

Python3
import git
repo = git.Repo('/home/hardik/GFG_Temp/Cloned_Repo')

# Do some changes and commit
file1 = 'test-sample.jpg'
file2 = 'input.txt'
repo.index.add([file1,file2])
print('Files Added Successfully')
repo.index.commit('Initial commit on new branch')
print('Commited successfully')

Output:

Files Added Successfully
Commited successfully