如何使用GitPython拉取远程代码库?

29
我正在尝试使用GitPython拉取Git代码库,到目前为止,这是我从官方文档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()
事实是我想访问repo.remotes.origin并进行拉取操作,而不重命名它的源(origin.rename)。我该如何实现?谢谢。
4个回答

58

我通过直接获取存储库名称来实现了这一点:

 repo = git.Repo('repo_path')
 o = repo.remotes.origin
 o.pull()

10
这里的repo_name实际上不是仓库的名称,而是指基于git版本库的文件系统路径。 - Paul Tobias
2
如果你的远程仓库是一个字符串,那么 git.Repo(repo_dir).remotes[remote].pull() 就可以拉取代码了。 - crizCraig
3
如果您想按名称从分支进行拉取操作: repo = git.Repo(localpath_to_repo_dir) repo.remotes.origin.pull(branch_name) - otaku
1
如何使用此方法强制拉取? - Mike
我在使用GitPython时也遇到了一些问题。您能否请您向我解释一下如何在进行身份验证时从存储库中获取/拉取代码?您提供的所有方法都没有考虑到某些存储库可能需要用户名和密码。 - undefined
显示剩余2条评论

11

希望你在寻找这个:

import git
g = git.Git('git-repo')
g.pull('origin','branch-name')
为给定仓库和分支获取最新的提交记录。

为我工作 :) 谢谢! - HolyM
谢谢!如果您想直接从URL中提取,这也可以工作。 - Daniel Lavedonio de Lima

11

正如被接受的答案所说,使用repo.remotes.origin.pull()是可能的,但缺点是它会将真实的错误信息隐藏在自己的通用错误中。例如,当DNS解析不起作用时,repo.remotes.origin.pull()会显示以下错误消息:

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

另一方面,使用GitPython直接执行git命令,例如repo.git.pull(),会显示真正的错误信息:

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.'

5

来自Akhil Singhal的问题回答中,git.Git模块上述仍然有效,但已经更名git.cmd.Git,例如:

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

1
你所提到的那个变更已经发生在15年前了。 - Mikaelblomkvistsson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接