如何使用GitPython检出标签

13

在一个Python脚本中,我尝试在克隆Git仓库后检出一个标签。我使用的是GitPython 0.3.2。

#!/usr/bin/env python
import git
g = git.Git()
g.clone("user@host:repos")
g = git.Git(repos)
g.execute(["git", "checkout", "tag_name"])

使用这段代码时出现错误:

g.execute(["git", "checkout", "tag_name"])
File "/usr/lib/python2.6/site-packages/git/cmd.py", line 377, in execute
raise GitCommandError(command, status, stderr_value)
GitCommandError: 'git checkout tag_name' returned exit status 1: error: pathspec 'tag_name' did not match any file(s) known to git.
如果我将标签名称替换为分支名称,我就没有问题了。我在GitPython文档中没有找到相关信息。如果我尝试在shell中检出相同的标签,也没有问题。
您知道如何在Python中检出git标签吗?
答案: 如果我使用分支名称替换标签名称,我就没有问题。我在GitPython文档中没有找到相关信息。如果我尝试在shell中检出相同的标签,也没有问题。请问如何在Python中检出git标签?

1
我希望这只是一个例子,但是你的错误显示你正在实际使用字符串“tag_name”,这就是为什么出现错误的原因。无论如何,“git checkout <tag>” 是正确的格式,但是您还应该知道,您需要先运行“git fetch”,然后在运行“git pull origin refs/tags/<tag>”。 - Inbar Rose
4个回答

10
假设您已经克隆了存储库到“path/to/repo”,只需尝试以下操作:
from git import Git

g = Git('path/to/repo')

g.checkout('tag_name')

10
属性错误:'Git'对象没有'checkout'属性。 - Jon Skarpeteig
我刚刚尝试了以下代码序列:[1] from git import Git [2] g = Git('GooglePlayAppsCrawler') [3] g.checkout()。它可以正常工作(GooglePlayAppsCrawler是我当前工作目录中的git仓库)。 - lev

1
git.Repo().git.checkout('tag')

1
from git import Git
g = Git(repo_path)
g.init()
g.checkout(version_tag)

像cmd.py类Git评论所说的那样

"""
The Git class manages communication with the Git binary.

It provides a convenient interface to calling the Git binary, such as in::

 g = Git( git_dir )
 g.init()                   # calls 'git init' program
 rval = g.ls_files()        # calls 'git ls-files' program

``Debugging``
    Set the GIT_PYTHON_TRACE environment variable print each invocation
    of the command to stdout.
    Set its value to 'full' to see details about the returned values.
""" 

-1

这对我有用,而且我认为它更接近预期的API使用方式:

from git import Repo

repo = Repo.clone_from("https://url_here", "local_path")
repo.heads['tag-name'].checkout()

无法工作:AttributeError: 'IterableList'对象没有属性tag-name - Lei Yang
这对我起作用了 - 我相信这与gitpython的最新版本匹配(对我来说是GitPython==3.1.7) - Audrey Dutcher

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