25

我正在尝试找到使用 gitPython 提取 git 存储库的方法。到目前为止,这是我从此处的官方文档中获取的内容。

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 来做一个 pull withouth 重命名它的起源 (origin.rename) 我怎么能做到这一点?谢谢。

4

4 回答 4

48

我通过直接获取 repo 名称来管理它:

 repo = git.Repo('repo_path')
 o = repo.remotes.origin
 o.pull()
于 2012-10-31T20:16:23.563 回答
11

希望你正在寻找这个:

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

拉取给定存储库和分支的最新提交。

于 2018-02-08T09:27:24.357 回答
8

正如公认的答案所说,可以使用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.'
于 2017-11-24T09:00:29.847 回答
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')
于 2020-09-22T10:27:17.240 回答