it's all in the documentation:

repo = Repo.clone_from(cloneUrl, localRepopath)
remote = repo.create_remote(remote_name, url=another_url)
remote.push(refspec='{}:{}'.format(local_branch, remote_branch))

see also the push reference API. You can avoid the refspec setting if you set a tracking branch for the remote you want to push to.

Answer from zmo on Stack Overflow
🌐
GitHub
github.com › gitpython-developers › GitPython › issues › 471
Create a new branch and push to remote? · Issue #471 · gitpython-developers/GitPython
June 13, 2016 - gitpython-developers / GitPython Public · There was an error while loading. Please reload this page. Notifications · You must be signed in to change notification settings · Fork 966 · Star 5.1k · New issueCopy link · New issueCopy link · Closed · Closed · Create a new branch and push to remote?#471 ·
Author   itielshwartz
Discussions

python - Git push via GitPython - Stack Overflow
Following is the code to git add, git commit and then git push using GitPython. More on stackoverflow.com
🌐 stackoverflow.com
python - Push new local branch to remote using Gitpython - Stack Overflow
I looked at a few references but I am still having problems: I want to clone a remote repo, create a new branch, and push the new branch back to remote using GitPython. This seems to work: impor... More on stackoverflow.com
🌐 stackoverflow.com
How do I push commits to a local repository with an SSH key?
I have a local repository that I've already cloned and I want to push changes to remote (GitHub) from a different account. I've tried something like this: id_file = os.path.expanduser('... More on github.com
🌐 github.com
2
1
Is there a way to force a git push?
Hi guys, I'm using GitPython to commit and push some changes in my Python application. However, sometimes my developers and I want to force push the commit (git push --force) instead of sometim... More on github.com
🌐 github.com
2
August 5, 2015
🌐
LinuxConfig
linuxconfig.org › home › how to manage git repositories with python
Manage Git Repositories with Python: GitPython Guide
May 27, 2022 - What we did above is calling the push method and pass a mapping between the local branch and the remote one as first argument: we basically sad to push the content of our master branch to the remote master branch. Since we specified an http url when we created the “origin” remote, once the code is executed we are prompted to provide our credentials: Username for 'https://github.com': foo Password for 'https://foo@github.com':
Top answer
1 of 4
3

I'm using gitpython==2.1.11 with Python 3.7. Below is my push function in which I first try a high-level push, and then a low-level push as necessary. Note how I check the return value of either command. I also log the push actions, and this explains what's happening at every step.

class GitCommandError(Exception):
    pass

class Git:
    def _commit_and_push_repo(self) -> None:
        repo = self._repo
        remote = repo.remote()
        remote_name = remote.name
        branch_name = repo.active_branch.name

        # Note: repo.index.entries was observed to also include unpushed files in addition to uncommitted files.
        log.debug('Committing repository index in active branch "%s".', branch_name)
        self._repo.index.commit('')
        log.info('Committed repository index in active branch "%s".', branch_name)

        def _is_pushed(push_info: git.remote.PushInfo) -> bool:
            valid_flags = {push_info.FAST_FORWARD, push_info.NEW_HEAD}  # UP_TO_DATE flag is intentionally skipped.
            return push_info.flags in valid_flags  # This check can require the use of & instead.

        push_desc = f'active branch "{branch_name}" to repository remote "{remote_name}"'
        log.debug('Pushing %s.', push_desc)
        try:
            push_info = remote.push()[0]
        except git.exc.GitCommandError:  # Could be due to no upstream branch.
            log.warning('Failed to push %s. This could be due to no matching upstream branch.', push_desc)
            log.info('Reattempting to push %s using a lower-level command which also sets upstream branch.', push_desc)
            push_output = repo.git.push('--set-upstream', remote_name, branch_name)
            log.info('Push output was: %s', push_output)
            expected_msg = f"Branch '{branch_name}' set up to track remote branch '{branch_name}' from '{remote_name}'."
            if push_output != expected_msg:
                raise RepoPushError(f'Failed to push {push_desc}.')
        else:
            is_pushed = _is_pushed(push_info)
            logger = log.debug if is_pushed else log.warning
            logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
            if not is_pushed:
                log.warning('Failed first attempt at pushing %s. A pull will be performed.', push_desc)
                self._pull_repo()
                log.info('Reattempting to push %s.', push_desc)
                push_info = remote.push()[0]
                is_pushed = _is_pushed(push_info)
                logger = log.debug if is_pushed else log.error
                logger('Push flags were %s and message was "%s".', push_info.flags, push_info.summary.strip())
                if not is_pushed:
                    raise RepoPushError(f'Failed to push {push_desc} despite a pull.')
        log.info('Pushed %s.', push_desc)
2 of 4
1

You have to define a remote repo, then push to it. e.g.

origin = repo.remote(name='origin')
origin.push()

See the Handling Remotes documentation for more examples of push/pull

🌐
Medium
zchelseal.medium.com › automate-your-git-workflow-with-gitpython-3320e833c4e2
Automate Your Git Workflow with GitPython | by Chelsea Liu | Medium
April 13, 2021 - Don’t forget to import git at the top of your script (sidenote: if you’ve also wondered why the package names (GitPython) are sometimes different from their import counterparts (git), here are some insights from wonderful internet people). Grab your repo with the latest meta-data from origin: repo = git.Repo(path_to_your_repo) # ex. "/User/some_user/some_dir" origin = repo.remote("origin") assert origin.exists() origin.fetch()
Find elsewhere
🌐
AskPython
askpython.com › home › how to use gitpython to pull remote repository?
How To Use GitPython To Pull Remote Repository? - AskPython
June 30, 2023 - Push: In GitPython, you can push your local changes to the remote repository using the push() method.
🌐
GitHub
github.com › gitpython-developers › GitPython › issues › 567
Push a commit to a named branch · Issue #567 · gitpython-developers/GitPython
gitpython-developers / GitPython Public · Notifications · You must be signed in to change notification settings · Fork 933 · Star 4.8k · New issueCopy link · New issueCopy link · Closed · Closed · Push a commit to a named branch#567 · Copy link · Labels ·
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › tutorial.html
GitPython Tutorial — GitPython 3.1.46 documentation
# Create a new submodule and check it out on the spot, setup to track master # branch of `bare_repo`. As our GitPython repository has submodules already that # point to GitHub, make sure we don't interact with them.
🌐
GitHub
github.com › gitpython-developers › GitPython › blob › master › git › remote.py
GitPython/git/remote.py at master · gitpython-developers/GitPython
# see: https://github.com/gitpython-developers/GitPython/pull/528#issuecomment-252976319 · # and: http://stackoverflow.com/a/32991784/548792 · # if 'Unknown subcommand: get-url' in str(ex): try: remote_details = self.repo.git.remote("show", self.name) for line in remote_details.split('\n'): if ' Push URL:' in line: yield line.split(': ')[-1] except GitCommandError as ex: if any(msg in str(ex) for msg in ['correct access rights', 'cannot run ssh']): # If ssh is not setup to access this repository, see issue 694 ·
Author   gitpython-developers
🌐
GitHub
github.com › gitpython-developers › GitPython › issues › 334
Is there a way to force a git push? · Issue #334 · gitpython-developers/GitPython
August 5, 2015 - Hi guys, I'm using GitPython to commit and push some changes in my Python application. However, sometimes my developers and I want to force push the commit (git push --force) instead of sometimes the app failing because it's behind the H...
Author   g12mcgov
🌐
Readthedocs
gitpython.readthedocs.io › en › 0.3.2 › tutorial.html
GitPython Tutorial — GitPython 0.3.2 documentation
Remotes are used as alias for a foreign repository to ease pushing to and fetching from them:
🌐
GeeksforGeeks
geeksforgeeks.org › python › automating-some-git-commands-with-python
Automating some git commands with Python - GeeksforGeeks
April 28, 2025 - 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')
🌐
Python Developer's Guide
devguide.python.org › gitbootcamp
Git bootcamp and cheat sheet
You should have been redirected · If not, click here to continue
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › reference.html
API Reference — GitPython 3.1.46 documentation
It will only be written into the configuration if it not None, which is when the checked out branch will be the one the remote HEAD pointed to. The result you get in these situation is somewhat fuzzy, and it is recommended to specify at least master here.
🌐
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