Call git via subprocess
. From one of my own programs:
def gitcmd(cmds, output=False):
"""Run the specified git command.
Arguments:
cmds -- command string or list of strings of command and arguments
output -- wether the output should be captured and returned, or
just the return value
"""
if isinstance(cmds, str):
if ' ' in cmds:
raise ValueError('No spaces in single command allowed.')
cmds = [cmds] # make it into a list.
# at this point we'll assume cmds was a list.
cmds = ['git'] + cmds # prepend with git
if output: # should the output be captured?
rv = subprocess.check_output(cmds, stderr=subprocess.STDOUT).decode()
else:
with open(os.devnull, 'w') as bb:
rv = subprocess.call(cmds, stdout=bb, stderr=bb)
return rv
Some examples:
rv = gitcmd(['gc', '--auto', '--quiet',])
outp = gitcmd('status', True)