Clone or Download Git repository using Python

Hello programmers, in this tutorial we will see how to clone or download a git repository using python.

Making a clone of a git repository can be easy in python using a famous module GitPython.

Requirements for using of GitPython library

The following mentioned below are the requirements for the above module to be installed.

  • Python3
  • Git
  • GitPython Module

Installation of GitPython in Python

Using the command prompt in your system, install the GitPython library using the following command.

pip install GitPython

Also, GitPython’s repo is available in github, which can be cloned using the command shell using the following command.

$ git clone https://github.com/gitpython-developers/GitPython git-python

After that, initialize all the submodules.

$ git submodule update --init –recursive

For checks, we can verify the installation by running unit tests. (optional)

$ python -m unittest

 

Basic Usage of GitPython: Clone Git repo using Python

GitPython provides the object model access to the git repository. Below given is the illustration of the template for using the GitPython module to clone a git repository.

from git import Repo
Repo.clone_from(gitUrl, repoDirectory)

Output

The following repository will be cloned.

Explanation
In the above script, we first are importing the GitPython library and specifically the Repo library. In the following line, we are using the clone_from method to clone the git repository which we want. It takes two parameters, the gitUrl which is the URL that we want to clone, and the repoDirectory where we want to store the repo.

Another way is also possible for downloading the git repository. Below given is the illustration for that.

import git
git.Git(repoDirectory).clone(gitUrl)

Output

The following repository will be cloned.

Explanation
In the above script, we are importing the GitPython library and then we are making a copy of the git repository on our local computer by using the .Git method in which it takes the repoDirectory and the gitUrl as its arguments.

Leave a Reply

Your email address will not be published.