Using GitPython will give you a good python interface to Git.

For cloning a new repository you can use clone_from function:

from git import Repo  # pip install gitpython

Repo.clone_from(git_url, repo_dir)

See the GitPython Tutorial for examples on using the Repo object.

Note: GitPython requires git being installed on the system, and accessible via system's PATH.

Answer from Amir Ali Akbari on Stack Overflow
🌐
GitHub
gist.github.com › plembo › a786ce2851cec61ac3a051fcaf3ccdab
Clone git repo using GitPython · GitHub
Clone git repo using GitPython. GitHub Gist: instantly share code, notes, and snippets.
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › tutorial.html
GitPython Tutorial — GitPython 3.1.46 documentation
from git import Repo # rorepo is a Repo instance pointing to the git-python repository. # For all you know, the first argument to Repo is a path to the repository you # want to work with.
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › quickstart.html
GitPython Quick Start Tutorial — GitPython 3.1.46 documentation
# $ git clone <url> <local_dir> repo_url = "https://github.com/gitpython-developers/QuickStartTutorialFiles.git" repo = Repo.clone_from(repo_url, local_dir)
🌐
PDX
web.pdx.edu › ~gjay › teaching › mth271_2020 › html › 03_Working_with_git.html
Git Repo class in python
Note: Provided variables will be used to update the execution environment for `git`. If some variable is not specified in `env` and is defined in `os.environ`, value from `os.environ` will be used. If you want to unset some variable, consider providing empty string as its value. :param multi_options: See ``clone`` method :param kwargs: see the ``clone`` method :return: Repo instance pointing to the cloned directory
🌐
AskPython
askpython.com › home › how to use gitpython to pull remote repository?
How To Use GitPython To Pull Remote Repository? - AskPython
June 30, 2023 - Why Choose GitPython Over Command Line Operations? Let’s consider a scenario where you have a Python script that needs to clone multiple Git repositories, update them daily, and perform specific tasks based on the changes. You would have a lot of interaction with the command line to deal ...
🌐
DEV Community
dev.to › nisevi › script-for-cloning-repositories-4h4m
Python script for cloning repositories - DEV Community
July 28, 2020 - This is a script for cloning repositories from a given organization in the GitHub ecosystem. Tagged with python, script, github, token.
Find elsewhere
🌐
JanBask Training
janbasktraining.com › community › devops › python-way-to-clone-a-git-repository
Python way to clone a git repository | JanBask Training Community
June 2, 2025 - Whether you're automating a deployment process or building a tool that interacts with Git, Python gives you both simple and advanced options. ... GitPython is a popular library for interacting with Git repositories programmatically. from git import Repo Repo.clone_from("https://github.com/user/repo.git", "local_folder")
🌐
GitHub
github.com › gitpython-developers › GitPython
GitHub - gitpython-developers/GitPython: GitPython is a python library used to interact with Git repositories. · GitHub
GitPython and its required package dependencies can be installed in any of the following ways, all of which should typically be done in a virtual environment. ... git clone https://github.com/gitpython-developers/GitPython cd GitPython ...
Starred by 5.1K users
Forked by 968 users
Languages   Python
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › reference.html
API Reference — GitPython 3.1.46 documentation
classmethod add(repo: Repo, name: str, path: str | os.PathLike[str], url: str | None = None, branch: str | None = None, no_checkout: bool = False, depth: int | None = None, env: Mapping[str, str] | None = None, clone_multi_options: Sequence[Any] | None = None, allow_unsafe_options: bool = False, allow_unsafe_protocols: bool = False) → Submodule · Add a new submodule to the given repository. This will alter the index as well as the .gitmodules file, but will not create a new commit.
🌐
Grimoire
grimoire.carcano.ch › the grimoire of a modern linux professional › blog › dev-ops tools › scripting › git with python howto gitpython tutorial and pygit2 tutorial
Git With Python HowTo GitPython Tutorial And PyGit2 Tutorial
November 14, 2024 - Git With Python HowTo GitPython Tutorial And PyGit2 Tutorial with also real life use case showing cloning, committing and pushing using HTTP or SSH transport
🌐
DevDungeon
devdungeon.com › content › working-git-repositories-python
Working with Git Repositories in Python | DevDungeon
March 17, 2020 - You can take an existing repo, load it, and then clone that to another local repo. You might want to do this if you use the primary repository as a template for creating new projects. import git # Load existing local repo my_repo = git.Repo('existing_repo') # Create a copy of the existing repo my_repo.clone('/path/to/clone_of_existing_repo')
Top answer
1 of 4
27

just pass the branch name parameter, e.g. :-

repo = Repo.clone_from(
    'http://user:[email protected]/user/project.git',
    '/home/antro/Project/',
    branch='master'
)

see here for more info

2 of 4
4

GitPython uses a keyword args transformation under the hood:

# cmd.py
def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]:
    if len(name) == 1:
        if value is True:
            return ["-%s" % name]
        elif value not in (False, None):
            if split_single_char_options:
                return ["-%s" % name, "%s" % value]
            else:
                return ["-%s%s" % (name, value)]
    else:
        if value is True:
            return ["--%s" % dashify(name)]
        elif value is not False and value is not None:
            return ["--%s=%s" % (dashify(name), value)]
    return []

A resulting list of command parts is fed into subprocess.Popen, so you do not want to add --single-branch to the repo URL. If you do, a strange list will be passed to Popen. For example:

['-v', '--branch=my-branch', 'https://github.com/me/my-project.git --single-branch', '/tmp/clone/here']

However, armed with this new information, you can pass any git CLI flags you like just by using the kwargs. You may then ask yourself, "How do I pass in a dash to a keyword like single-branch?" That's a no-go in Python. You will see a dashify function in the above code which transforms any flag from, say, single_branch=True to single-branch, and then to --single-branch.

Full Example:

Here is a useful example for cloning a single, shallow branch using a personal access token from GitHub:

repo_url = "https://github.com/me/private-project.git"
branch = "wip-branch"
# Notice the trailing : below
credentials = base64.b64encode(f"{GHE_TOKEN}:".encode("latin-1")).decode("latin-1")
Repo.clone_from(
    url=repo_url,
    c=f"http.{repo_url}/.extraheader=AUTHORIZATION: basic {credentials}",
    single_branch=True,
    depth=1,
    to_path=f"/clone/to/here",
    branch=branch,
)

The command list sent to Popen then looks like this:

['git', 'clone', '-v', '-c', 'http.https://github.com/me/private-project.git/.extraheader=AUTHORIZATION: basic XTE...UwNTo=', '--single-branch', '--depth=1', '--bare', '--branch=wip-branch', 'https://github.com/me/private-project.git', '/clone/to/here']

(PSA: Please do not actually send your personal tokens as part of the URL before the @.)

Top answer
1 of 1
13

requests is third-party, so (per the style guide) there should be a blank line in the imports:

import os

import requests

api_repo is constant, so should be API_REPO. There should also be spaces around the = in assignments:

API_REPO = 'https://api.github.com/user/repos'

Explicit line continuation isn't very Pythonic, especially when the line is short enough anyway:

url = '%s?access_token=%s' % \
(api_repo,API_TOKEN,)

Also, there should be spaces after commas (and I wouldn't bother with the trailing one). This would be better written as:

url = '%s?access_token=%s' % (API_REPO, API_TOKEN)

r and i aren't very good variable names. I would use req_json and git_url.


You are mixing % string formatting with + concatenation. You should at least be consistent, and I would use the more modern str.format:

os.system("git clone {}".format(git_url)) 

You should also be consistent with string literal quotes. Per the style guide:

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.


In all, I would probably have written it as:

import os

import requests

API_TOKEN = "..."
API_URL = "https://api.github.com/user/repos"

url = "{}?access_token={}".format(API_URL, API_TOKEN)
req_json = requests.get(url).json()

for repo in req_json:
    os.system("git clone {}".format(repo["git_url"]))
🌐
Feral Cat
feralcat.xyz › home › how to clone a git repo in python – updated
How To Clone A Git Repo In Python - Updated - Feral Cat - Software Development
February 19, 2025 - GitPython is the go-to library for working with Git repositories in Python. It wraps Git commands, so you don’t have to shell out manually. ... Make sure you have Git installed and accessible from your command line. If git --version doesn’t return a version number, install Git first. Let’s now do the same thing I mentioned in that older post but using this nice and shiny package. We’re going to clone a git repo in Python3.
🌐
Delft Stack
delftstack.com › home › howto › python › python git clone
Python Way to Clone a Git Repository | Delft Stack
March 4, 2025 - The first section is the destination path we want the repository to be cloned in, then inside the .clone() is the GitHub URL of the project folder we want to clone. This method works very similarly to GitPython; it is a library like GitPython and works just as easily. Using this method is a question of preference compared to GitPython because they are similar in operation. To boot, we will install dload by typing pip install dload inside our terminal. Then we create a new Python file, name it new.py and enter this snippet:
🌐
PyPI
pypi.org › project › github-clone
github-clone · PyPI
July 4, 2021 - Python :: 3 · Report project as malware · Git clone (download) any sub-directories of any GitHub repository (at any reference) without having to clone the entire repository, with only its GitHub URL. Uses the GitHub API to recursively clone the sub-directories tree and files.
      » pip install github-clone
    
Published   Jul 04, 2021
Version   1.2.0