There are times when you want to do the source code management programmatically, and here comes GitPython. GitPython wraps the git commands so that you can execute most git functions from within Python (and without using shutils or subprocess). The example code snippet below shows how to do a “git clone” and if the destination is already there, it will try a “git checkout” first from the “master” branch if it exists then the “main” branch if the master branch does not exist.
try: git.Repo.clone_from(remote_repo, local_repo) except GitCommandError as error: if error.status == 128: repo = git.Repo(local_repo) branch = 'master' try: repo.git.checkout(branch) except GitCommandError: branch = 'main' repo.git.checkout(branch) else: msg = ' '.join(error.command) msg += error.stderr sys.exit(f'Error in running git: {msg}.')