如何从Python中调用“git pull”?

2024-05-19 16:24:48 发布

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

使用github webhooks,我希望能够将任何更改拉到远程开发服务器。此时,当在适当的目录中时,git pull将获得需要进行的任何更改。但是,我不知道如何从Python中调用该函数。我试过以下方法:

import subprocess
process = subprocess.Popen("git pull", stdout=subprocess.PIPE)
output = process.communicate()[0]

但这会导致以下错误

Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/subprocess.py", line 679, in init errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory

有没有办法从Python中调用bash命令?


Tags: inpygitgithub服务器child远程lib
3条回答

使用GitPython的公认答案比直接使用subprocess要好得多。

这种方法的问题是,如果您想解析输出,您最终会看到“瓷器”命令的结果,which is a bad idea

以这种方式使用GitPython就像得到一个闪亮的新工具箱,然后用它来固定它的一堆螺钉,而不是里面的工具。以下是API的设计用途:

import git
repo = git.Repo('Path/to/repo')
repo.remotes.origin.pull()

如果您想检查是否有更改,可以使用

current = repo.head.commit
repo.remotes.origin.pull()
if current != repo.head.commit:
    print("It changed")

^{}需要程序名和参数的列表。您传递的是一个字符串,它(默认为shell=False)相当于:

['git pull']

这意味着子进程试图找到一个名为git pull的程序,但未能找到:在Python 3.3中,代码引发异常FileNotFoundError: [Errno 2] No such file or directory: 'git pull'。相反,请输入一个列表,如下所示:

import subprocess
process = subprocess.Popen(["git", "pull"], stdout=subprocess.PIPE)
output = process.communicate()[0]

顺便说一下,在Python2.7+中,您可以使用^{}便利函数简化此代码:

import subprocess
output = subprocess.check_output(["git", "pull"])

另外,要使用git功能,根本不需要调用git二进制文件(尽管简单且可移植)。考虑使用git-pythonDulwich

你考虑过使用GitPython吗?它是为你设计来处理这些废话的。

import git 

g = git.cmd.Git(git_dir)
g.pull()

https://github.com/gitpython-developers/GitPython

相关问题 更多 >