在Python代码中使用Git命令

use*_*922 14 python git

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

我发现有两个内置的Python模块可以与Git交互,并且可以随时使用:GitPythonlibgit2.

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

Ian*_*bee 25

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

import subprocess
subprocess.call(["git", "pull"])
subprocess.call(["make"])
subprocess.call(["make", "test"])
Run Code Online (Sandbox Code Playgroud)

文档:

  • 对于 Python 3.5 及更高版本,.call() 方法[已弃用](/sf/ask/2848830841/ Between-pythons-subprocess-call-and-subprocess-run) 。您现在可以使用: `import subprocess` `subprocess.run(["git", "pull"])` 等。 (3认同)

ayc*_*dee 14

我同意Ian Wetherbee的观点.您应该使用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!
Run Code Online (Sandbox Code Playgroud)

  • 实际上,我刚刚读到 GitPython 存在系统资源泄漏问题(https://gitpython.readthedocs.io/en/stable/intro.html#limitations)。所以这足以让我远离它! (2认同)

Joe*_*obs 13

因此,在 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"])
Run Code Online (Sandbox Code Playgroud)

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