如何在python中获取git repo的最后提交ID [英] how to get last commit id of the git repo in python

查看:145
本文介绍了如何在python中获取git repo的最后提交ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道存储库中确切的git commit ID.可能就像最新提交(最新提交)和第二最新提交一样.

I would like to know the exact git commit id in a repository. May be like latest commit(most recent) and 2nd most recent commit.

我尝试过如下所示的git命令,但在python脚本中也需要相同的命令.

I have tried git commands like below, but I need the same in python script.

$ git rev-parse @ 最新输出:669ec6662bedc7a9962bef83612a33522a8e4fb8

$ git rev-parse @ most recent Output: 669ec6662bedc7a9962bef83612a33522a8e4fb8

$ git rev-parse @〜最近第二个输出:97a90650792efdbef3f6abb92bd6108c11889cc6

$ git rev-parse @~ 2nd most recent Output: 97a90650792efdbef3f6abb92bd6108c11889cc6

推荐答案

您可以使用 subprocess 模块来实现.该代码将返回一个包含最后两次提交的列表,其中列表中的第一项是最新的.

You can do that using subprocess module. This code will return a list containing the last two commits, where the first item in the list is the latest.

import subprocess

def get_git_revisions_hash():
    hashes = []
    hashes.append(subprocess.check_output(['git', 'rev-parse', 'HEAD']))
    hashes.append(subprocess.check_output(['git', 'rev-parse', 'HEAD^']))
    return hashes

列表理解也可以实现同样的目的.此解决方案可扩展性更高,因为您无需添加其他子流程调用:

The same can also be achieved with list comprehension. This solution is more extendable, because you don't need to add additional subprocess calls:

commits = ['HEAD', 'HEAD^']
def get_git_revisions_hash2():
    return [subprocess.check_output(['git', 'rev-parse', '{}'.format(x)])
            for x in commits]

还有 GitPython 模块,它为您提供了git的接口.您可以阅读文档,它为git提供了更多内置工具.

There is also GitPython module, which gives you an interface to git. You can read the docs, it gives more builtin tools for git.

这篇关于如何在python中获取git repo的最后提交ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆