How can I call 'git pull' from within Python?

前端 未结 6 1602
栀梦
栀梦 2020-12-07 18:11

Using the github webhooks, I would like to be able to pull any changes to a remote development server. At the moment, when in the appropriate directory, git pull

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 19:07

    This is a sample recipe, I've been using in one of my projects. Agreed that there are multiple ways to do this though. :)

    >>> 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 ..." 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
    

    The problem with your code was, you were not passing an array for subprocess.Popen() and hence was trying to run a single binary called git pull. Instead it needs to execute the binary git with the first argument being pull and so on.

提交回复
热议问题