Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Git Repo has uncommitted changes using Python

Tags:

git

python

I'm pretty new to git, but I'm trying to use python to check if a git repository has any uncommitted changes. I seem to get the same error no matter what command I try to run using python. Here's my code:

from git import *
repo = Repo("path\to\my\repo")
lastCommit = repo.head.commit.committed_date
uncommitted = repo.is_dirty()

Everything works as expected until I run the last line which is when I get the error:

Traceback (most recent call last):
.
.
.
    raise GitCommandNotFound: [Error 2] The system cannot find the file specified 

I've tried this with other commands too and I get the same error. For example, repo.index.diff(repo.head.commit). I've also tried running repo.index.diff(None) and repo.index.diff('HEAD') which give the same error. What I really want is to essentially run $ git status for the repository I've named repo. I'm using Python 2.7.9 and gitpython 1.0.1 on Windows 7. Any help would be appreciated!

like image 650
jtaylor Avatar asked Sep 06 '25 03:09

jtaylor


2 Answers

In your particular example (which is only for illustration purposes), your "path\to\my\repo" would be understood as 'path\to\\my\repo'. Use a double backslash between the components of your path ("path\\to\\my\\repo"). \t is understood as a tab, and \r is understood as a carriage return. Alternatively, you can put a r in front of your path like so: r"path\to\my\repo"

like image 177
Noctis Skytower Avatar answered Sep 07 '25 17:09

Noctis Skytower


Look like GitPython can't find git.exe.

Try setting the environment variable GIT_PYTHON_GIT_EXECUTABLE. It's should most likely be "C:\Program Files (x86)\Git\bin\git.exe" if using Git for Windows with defaults

at command line (cmd.exe)

set GIT_PYTHON_GIT_EXECUTABLE="C:\Program Files (x86)\Git\bin\git.exe"
like image 29
Joakim Elofsson Avatar answered Sep 07 '25 15:09

Joakim Elofsson