Automating some git commands with Python
Last Updated :
24 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
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' )
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
repo = git.Repo.init( '/home/hardik/GFG_Temp/Cloned_Repo' )
new_branch = repo.create_head( 'new_branch' )
print ( 'New Branch Created' )
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' )
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
Executing Shell Commands with Python
This article starts with a basic introduction to Python shell commands and why one should use them. It also describes the three primary ways to run Python shell commands. os.system()subprocess.run()subprocess.Popen()Â What is a shell in the os?In programming, the shell is a software interface for acc
4 min read
Using the Cat Command in Python
The cat command is a Linux shell command. It is the shorthand for concatenate. It is placed among the most often used shell commands. It could be used for various purposes such as displaying the content of a file on the terminal, copying the contents of a given file to another given file, and both a
4 min read
How to Automate an Excel Sheet in Python?
Before you read this article and learn automation in Python....let's watch a video of Christian Genco (a talented programmer and an entrepreneur) explaining the importance of coding by taking the example of automation. You might have laughed loudly after watching this video and you surely, you might
8 min read
Getting Started on Heroku with Python
Heroku is a cloud platform as a service supporting several programming languages where a user can deploy, manage and scale their applications. It is widely used to deploy server-based web applications, APIs, discord bots, and more. So today in this tutorial, we'll be deploying a simple flask app to
3 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers].
2 min read
How to see the Changes in a Git commit?
Understanding the changes introduced in each commit is crucial for effective collaboration and version control in Git. Whether you are reviewing someone else's work or tracking your own modifications, Git provides powerful tools to inspect changes. This article will guide you through the various met
4 min read
How to Use Git Shell Commands?
Git is a powerful version control system that is important for managing source code in modern software development. While there are many graphical user interfaces (GUIs) available for Git, mastering Git shell commands can significantly enhance your productivity and control over your repositories. Th
3 min read
Script management with Python Poetry
Poetry is a tool that makes it easier to manage Python dependencies and packages and create virtual environments for a project, as well as to package and distribute Python libraries. Apart from dependency management, script management is also one of the strong features of Poetry where developers can
5 min read
How To Change Folder With Git Bash?
Git Bash is a powerful tool that provides a command-line interface (CLI) for Git, allowing users to interact with their repositories in a Unix-like environment. One common task when working with Git Bash is navigating between folders, also known as directories. This article will guide you through th
2 min read
Automating Tasks with Python: Tips and Tricks
Python is a versatile and simple-to-learn programming language for all developers to implement any operations. It is an effective tool for automating monotonous operations while processing any environment. Programming's most fruitful use is an automation system to identify any process, and Python's
6 min read