【问题标题】:Possible to extract the git repo revision hash via Python code?可以通过 Python 代码提取 git repo 修订哈希吗?
【发布时间】:2012-10-10 19:18:35
【问题描述】:

是否有任何简单的方法可以使用 Python 代码获取 git 存储库(在 GitHub 上)版本哈希?我想用它来处理 github 上我的软件的“开发”版本的版本控制。

【问题讨论】:

标签: python git version


【解决方案1】:
def git_version():
    from subprocess import Popen, PIPE
    gitproc = Popen(['git', 'rev-parse','HEAD'], stdout = PIPE)
    (stdout, _) = gitproc.communicate()
    return stdout.strip()

【讨论】:

    【解决方案2】:
    from subprocess import Popen, PIPE
    
    gitproc = Popen(['git', 'show-ref'], stdout = PIPE)
    (stdout, stderr) = gitproc.communicate()
    
    for row in stdout.split('\n'):
        if row.find('HEAD') != -1:
            hash = row.split()[0]
            break
    
    print hash
    

    【讨论】:

      【解决方案3】:

      像这样?

      import subprocess
      ref = subprocess.check_output("""
          git 2>/dev/null show-ref | awk '/refs\/heads\/master/{print $1}'
      """, shell=True)
      print ref
      

      如果你有master以外的其他东西,请调整它

      【讨论】:

      • 通过python。通过Popen 运行git 命令并在python 中解析输出。
      • 无需通过管道将其传输到 awk。只需从 Popen 对象中读取 stdout 并在 Python 中解析文本。 Python作为字符串处理非常好!
      • 对不起,不得不接受 tMC 的回答。 check_output 来自 2.7,我现在想要向后兼容。
      【解决方案4】:

      您也可以为此使用GitHub API

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 2014-05-30
        • 2013-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多