首页 文章

如何在Python中调用'git pull'?

提问于
浏览
50

使用github webhooks,我希望能够将任何更改提取到远程开发服务器 . 目前,当在适当的目录中时, git pull 会获得需要进行的任何更改 . 但是,我无法弄清楚如何从Python中调用该函数 . 我尝试过以下方法:

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

但这会导致以下错误

回溯(最近一次调用最后一次):文件“”,第1行,在文件“/usr/lib/python2.7/subprocess.py”,第679行,在init errread,errwrite)文件“/ usr / lib / python2 .7 / subprocess.py“,第1249行,在_execute_child中引发child_exception OSError:[Errno 2]没有这样的文件或目录

有没有办法可以在Python中调用这个bash命令?

5 回答

  • 0

    你考虑过使用GitPython吗?它旨在为您处理所有这些废话 .

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

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

  • 34

    subprocess.Popen需要一个程序名称和参数列表 . 你传给它一个字符串,它是(默认的 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]
    

    顺便说一句,在Python 2.7中,您可以使用check_output便利函数简化此代码:

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

    此外,要使用git功能,调用git二进制文件绝对不需要(尽管简单和可移植) . 考虑使用git-pythonDulwich .

  • -3

    这是一个示例配方,我一直在我的一个项目中使用 . 同意有多种方法可以做到这一点 . :)

    >>> import subprocess, shlex
    >>> git_cmd = 'git status'
    >>> kwargs = {}
    >>> kwargs['stdout'] = subprocess.PIPE
    >>> kwargs['stderr'] = subprocess.PIPE
    >>> proc = subprocess.Popen(shlex.split(git_cmd), **kwargs)
    >>> (stdout_str, stderr_str) = proc.communicate()
    >>> return_code = proc.wait()
    
    >>> print return_code
    0
    
    >>> print stdout_str
    # On branch dev
    # Untracked files:
    #   (use "git add <file>..." to include in what will be committed)
    #
    #   file1
    #   file2
    nothing added to commit but untracked files present (use "git add" to track)
    
    >>> print stderr_str
    

    您的代码的问题是,您没有为 subprocess.Popen() 传递数组,因此尝试运行名为 git pull 的单个二进制文件 . 相反,它需要执行二进制 git ,第一个参数是 pull ,依此类推 .

  • 2

    使用GitPython接受的答案比直接使用_903701更好 .

    这种方法的问题是,如果你想解析输出,你最终会看到"porcelain"命令的结果,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")
    
  • 105

    尝试:

    subprocess.Popen("git pull", stdout=subprocess.PIPE, shell=True)
    

相关问题