【问题标题】:Use Git commands within Python code在 Python 代码中使用 Git 命令
【发布时间】:2012-06-22 06:07:57
【问题描述】:

我被要求编写一个脚本,从 Git 中提取最新代码、进行构建并执行一些自动化单元测试。

我发现有两个现成的用于与 Git 交互的内置 Python 模块:GitPythonlibgit2

我应该使用什么方法/模块?

【问题讨论】:

    标签: python git


    【解决方案1】:

    如果 GitPython 包不适合你,还有 PyGit 和 Dulwich 包。这些可以通过 pip 轻松安装。

    但是,我个人只是使​​用了子流程调用。非常适合我需要的东西,这只是基本的 git 调用。对于更高级的东西,我推荐一个 git 包。

    【讨论】:

      【解决方案2】:

      因此,在 Python 3.5 及更高版本中,.call() 方法已被弃用。

      https://docs.python.org/3.6/library/subprocess.html#older-high-level-api

      目前推荐的方法是在子进程上使用 .run() 方法。

      import subprocess
      subprocess.run(["git", "pull"])
      subprocess.run(["make"])
      subprocess.run(["make", "test"])
      

      当我去阅读文档时添加这个,上面的链接与接受的答案相矛盾,我不得不做一些研究。加上我的 2 美分,希望可以为其他人节省一点时间。

      【讨论】:

        【解决方案3】:

        更简单的解决方案是使用 Python subprocess 模块来调用 git。在您的情况下,这将提取最新代码并构建:

        import subprocess
        subprocess.call(["git", "pull"])
        subprocess.call(["make"])
        subprocess.call(["make", "test"])
        

        文档:

        【讨论】:

        • 对于 Python 3.5 及更高版本,.call() 方法 has been deprecated。您现在可以使用:import subprocesssubprocess.run(["git", "pull"]) 等。
        【解决方案4】:

        EasyBuild 中,我们依赖 GitPython,效果很好。

        有关如何使用它的示例,请参阅here

        【讨论】:

          【解决方案5】:

          我同意伊恩·韦瑟比的观点。您应该使用 subprocess 直接调用 git。如果您需要对命令的输出执行一些逻辑,那么您将使用以下子进程调用格式。

          import subprocess
          PIPE = subprocess.PIPE
          branch = 'my_branch'
          
          process = subprocess.Popen(['git', 'pull', branch], stdout=PIPE, stderr=PIPE)
          stdoutput, stderroutput = process.communicate()
          
          if 'fatal' in stdoutput:
              # Handle error case
          else:
              # Success!
          

          【讨论】:

            【解决方案6】:

            如果您使用的是 Linux 或 Mac,为什么要使用 python 来完成这项任务?编写一个 shell 脚本。

            #!/bin/sh
            set -e
            git pull
            make
            ./your_test #change this line to actually launch the thing that does your test
            

            【讨论】:

            • 也许提问者想要对输出做一些复杂的事情?但是,是的,我倾向于同意。
            • 嗯,问题中有 Python 标签。请不要猜测 OP 的动机。
            猜你喜欢
            • 1970-01-01
            • 2014-10-05
            • 1970-01-01
            • 2018-10-21
            • 1970-01-01
            • 1970-01-01
            • 2021-07-14
            • 1970-01-01
            相关资源
            最近更新 更多