在Python代码中使用Git命令

31

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

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

我应该使用哪种方式/模块呢?

7个回答

50

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

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

文档:


3
使用Python 3.5及以上版本,调用方法.call()已经被弃用。现在可以使用以下代码代替: import subprocess subprocess.run(["git", "pull"]) 等等。 - Bart Jonk

26

从Python 3.5开始,.call()方法已被弃用。

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

目前推荐使用subprocess的.run()方法。

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

当我查看文档时,发现上面的链接与被接受的答案相矛盾,因此我不得不进行一些研究。在这里补充我的意见,希望能为其他人节省一些时间。


25

我同意Ian Wetherbee的观点。您应该使用subprocess直接调用git。如果您需要对命令输出执行某些逻辑,则可以使用以下subprocess调用格式。

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!

这比GitPython更好在哪里?GitPython是否只是在幕后执行此操作?如果是,为什么要重新发明它? - John
2
实际上,我刚刚读到GitPython存在系统资源泄漏问题(https://gitpython.readthedocs.io/en/stable/intro.html#limitations)。这已经足够让我远离它了! - John
1
此外,我在2012年写下了这个答案。那已经是10年前的事情了。因此,自那时以来可能已经有了新的软件。如果有一种新的厉害方法,请将其添加为此问题的答案。 - aychedee

2
如果GitPython包对你没用,还有PyGit和Dulwich包可供选择。这两个都可以通过pip轻松安装。
但是,我个人只使用过子进程调用。对于我所需的基本git调用来说,它非常完美。如果需要更高级的操作,建议使用Git包。

2
EasyBuild中,我们依赖于GitPython,这很好地解决了问题。
请参见此处,以获取如何使用它的示例。

0

我不得不在运行调用的基础上使用shlex,因为我的命令对于单独的子进程来说过于复杂而无法理解。

import subprocess
import shlex
git_command = "git <command>"
subprocess.run(shlex.split(git_command))

-8
如果你使用的是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

也许提问者想对输出做一些复杂的操作?但是,我倾向于同意。 - aychedee
15
好的,题目中提到了Python标签,请不要猜测提问者的动机。 - ᴠɪɴᴄᴇɴᴛ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接