TheWaterProgrammer
TheWaterProgrammer

Reputation: 8259

How to get output of git commands into Python variables

Is it possible to collect output of a git command into a Python variable?

Lets a simple command like git status which gives the list of files changed on the repo. Lets say the output of git status is following

A.cpp
B.hpp
C.cpp

Is it possible to get the above output of git status into a Python list?

I read the some git commands do not pipe the output and rather just print? Is it true even today? If a git command was piping the output, how can one collect it a Python list or variable?

Can GitPython help here?

Upvotes: 1

Views: 3168

Answers (2)

Milan Lakhani
Milan Lakhani

Reputation: 108

You could also use Python's os module.

import os

os.system("git diff --name-only | tee status")

would put the names of the changed files into a file called status.

Erm I think the other answer is better though.

Upvotes: 1

David Meu
David Meu

Reputation: 1545

You can use: GitPython

Or 'native way':

from subprocess import Popen, PIPE
cmd = 'git diff --name-only'
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
files_changed_list = stdout.decode("utf-8").splitlines()

Upvotes: 3

Related Questions