Use Git commands within Python code

An easier solution would be to use the Python subprocess module to call git. In your case, this would pull the latest code and build:

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

Docs:

  • subprocess - Python 2.x
  • subprocess - Python 3.x

So with Python 3.5 and later, the .call() method has been deprecated.

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

The current recommended method is to use the .run() method on subprocess.

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

Adding this as when I went to read the docs, the links above contradicted the accepted answer and I had to do some research. Adding my 2 cents to hopefully save someone else a bit of time.


I agree with Ian Wetherbee. You should use subprocess to call git directly. If you need to perform some logic on the output of the commands then you would use the following subprocess call format.

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!

Tags:

Python

Git