Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Git commands within Python code

Tags:

I have been asked to write a script that pulls the latest code from Git, makes a build, and performs some automated unit tests.

I found that there are two built-in Python modules for interacting with Git that are readily available: GitPython and libgit2.

What approach/module should I use?

like image 586
user596922 Avatar asked Jun 20 '12 06:06

user596922


People also ask

How do you write Git commands in Python?

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.

Can I use Git in Python?

GitPython is a python library used to interact with git repositories. It is a module in python used to access our git repositories. It provides abstractions of git objects for easy access of repository data, and additionally allows you to access the git repository more directly using pure python implementation.

How do you execute a command in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


2 Answers

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
like image 55
Ian Wetherbee Avatar answered Oct 05 '22 14:10

Ian Wetherbee


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! 
like image 45
aychedee Avatar answered Oct 05 '22 15:10

aychedee