在Python cod中使用Git命令

2024-05-15 21:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我发现有两个内置的Python模块可以与Git进行交互,这两个模块都是现成的:GitPythonlibgit2

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


Tags: 模块方法代码git脚本libgit2单元测试内置
3条回答

我同意伊恩·韦瑟比的观点。您应该使用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!

EasyBuild中,我们依赖于GitPython,这很好。

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

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

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

文件:

相关问题 更多 >