29

I am trying to find the way to pull a git repository using gitPython. So far this is what I have taken from the official docs here.

test_remote = repo.create_remote('test', 'git@server:repo.git')
repo.delete_remote(test_remote) # create and delete remotes
origin = repo.remotes.origin    # get default remote by name
origin.refs                     # local remote references
o = origin.rename('new_origin') # rename remotes
o.fetch()                       # fetch, pull and push from and to the remote
o.pull()
o.push()

The fact is that I want to access the repo.remotes.origin to do a pull withouth renaming it's origin (origin.rename) How can I achieve this? Thanks.

Craig S. Anderson
  • 6,966
  • 4
  • 33
  • 46
Uuid
  • 2,506
  • 5
  • 28
  • 37

4 Answers4

58

I managed this by getting the repo name directly:

 repo = git.Repo('repo_path')
 o = repo.remotes.origin
 o.pull()
Moha the almighty camel
  • 4,327
  • 4
  • 30
  • 53
Uuid
  • 2,506
  • 5
  • 28
  • 37
  • 2
    `git.Repo(repo_dir).remotes[remote].pull()` if your remote is a string – crizCraig Jan 02 '19 at 22:03
  • `git.Repo(repo_dir).remotes.origin.pull(options)`, where, for example `options='--tags'` – Gulzar Aug 13 '19 at 12:21
  • 3
    `repo = git.Repo(localpath_to_repo_dir) repo.remotes.origin.pull(branch_name)` if you want to pull from a branch by name – otaku Aug 04 '20 at 06:06
  • 1
    How to force pull using this method ? – Mike Oct 01 '20 at 16:42
  • In case somebody is interested, that command displayed a lot of "trash"(it wasn't useful for me at least) on the screen. The way of getting around it is to assign the result to `_`. Something like this: `_ = Repo(folder_name).remotes.origin.pull()` – Vini.g.fer Jun 24 '23 at 15:04
11

As the accepted answer says it's possible to use repo.remotes.origin.pull(), but the drawback is that it hides the real error messages into it's own generic errors. For example when DNS resolution doesn't work, then repo.remotes.origin.pull() shows the following error message:

git.exc.GitCommandError: 'Error when fetching: fatal: Could not read from remote repository.
' returned with exit code 2

On the other hand using git commands with GitPython like repo.git.pull() shows the real error:

git.exc.GitCommandError: 'git pull' returned with exit code 1
stderr: 'ssh: Could not resolve hostname github.com: Name or service not known
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.'
Paul Tobias
  • 1,962
  • 18
  • 18
11

Hope you are looking for this :

import git
g = git.Git('git-repo')
g.pull('origin','branch-name')

Pulls latest commits for the given repository and branch.

Akhil Singhal
  • 151
  • 1
  • 7
5

git.Git module from Akhil Singhal s' answer above still works, but has been renamed to git.cmd.Git, e.g.:

import git 
# pull from remote origin to the current working dir:
git.cmd.Git().pull('https://github.com/User/repo','master')