Updated – How To Clone A Git Repo In Python3

So, a loooong time ago I wrote this post on how to clone a Git repo in Python. I used subprocess that first time around to run git commands. I was essentially trying to run git commands in python explicitly. But, there’s a better way to do this. It’s prettier, it’s easier to read. There’s better error handling. It’s all around better. It’s GitPython.

Installation

Leave the CLI in Python commands behind. Run the following to get it installed:

pip install GitPython

How To Clone A Git Repo In Python3

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.

from git import Repo

repo_url = "https://github.com/gitpython-developers/QuickStartTutorialFiles.git"
local_dir = "path/To/Where/you/want/youFiles"

repo = Repo.clone_from(repo_url, local_dir)

It looks fairly similar to what I had historically recommended. What I had recommended was:

import subprocess
# Make sure you have git installed
subprocess.call('git clone https://github.com/cvcaban/firstButton.git', shell = True)
# Now you can edit the files that were downloaded or manipulate the info how you see fit

But the old way just broke if you got an error from github. The new method should give you nice errors you can handle in your code.