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
4. Push to a remote Repository
Push the local commits to the remote repository
origin = repo.remote(name='origin')
origin.push()
Example:
Python3
import git
repo = git.Repo("/home/hardik/GFG_Temp/Cloned_Repo")
origin = repo.remote(name='origin')
existing_branch = repo.heads['main']
existing_branch.checkout()
repo.index.commit('Initial commit on new branch')
print('Commited successfully')
origin.push()
print('Pushed changes to origin')
Output:
Commited successfully
Pushed changes to origin
Verify:
5. Create a new branch
To create a new branch, you can use the create_head() method of the Repo class, which creates a new branch with the specified name
new_branch = repo.create_head('new_branch')
To checkout the new branch
new_branch.checkout()
Example:
Python3
import git
# Initialize a new repository
repo = git.Repo.init('/home/hardik/GFG_Temp/Cloned_Repo')
# Create a new branch
new_branch = repo.create_head('new_branch')
print('New Branch Created')
# Checkout the new branch
new_branch.checkout()
print("Changed the current branch to new_branch")
Output:
In this example, we first initialize a new repository using git.Repo.init() method. We then create a new branch called new_branch using the create_head() method. We then check out the new branch using the checkout() method.
New Branch Created
Changed the current branch to new_branch
To switch to an existing branch, you can use the heads attribute of the Repo class, which returns a list of branches, and then call the checkout method on the desired branch.
Python3
import git
repo = git.Repo('/home/hardik/GFG_Temp/Cloned_Repo')
# Select an existing branch
existing_branch = repo.heads['existing_branch']
existing_branch.checkout()
print('Branch Changed to an existing branch')
Output:
Branch Changed to an existing branch
6. Pull from a remote repository
To update the local repository with the latest changes from the remote repository we use git pull command
Example:
Python3
import git
repo = git.Repo("/path/to/local/repo")
origin = repo.remote(name='origin')
origin.pull()
Output:
Pulled Changes from the origin
Verify: New file hacktoberfest_tree_cert.pdf got pulled from the origin and got saved to the local machine.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read