2015-07-21 231 views
1

我对git很陌生,但我试图用python来检查git存储库是否有任何未提交的更改。无论我尝试使用python运行什么命令,我似乎都会得到相同的错误。这里是我的代码:如何使用Python检查Git Repo是否有未提交的更改

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

一切正常,直到我跑最后一行是当我得到的错误:

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

我与其他命令试过这也和我一样错误。例如,repo.index.diff(repo.head.commit)。我也尝试运行repo.index.diff(None)repo.index.diff('HEAD'),它们给出了相同的错误。我真正想要的是为我已命名为repo的存储库本质上运行$ git status。我在Windows 7上使用Python 2.7.9和gitpython 1.0.1。任何帮助将不胜感激!

回答

1

在您的特定示例中(仅用于说明目的),您的"path\to\my\repo"将被理解为'path\to\\my\repo'。在路径的组件之间使用双反斜杠("path\\to\\my\\repo")。 \t被理解为一个选项卡,并且\r被理解为回车符。或者,您可以在路径前面输入r,如下所示:r"path\to\my\repo"

+0

这些“[string lterals](https://en.wikipedia.org/wiki/String_literal)”被称为原始字符串,但请记住,这只是表示程序文本中字符串的一种不同方式 - t表示不同类型的对象。 – holdenweb

+0

@holdenweb感谢您为jtaylor解释。如果在Python 3之前使用'u'而不是'r',那么数据类型将会不同。在Python 3之后,用'b'代替'r'也会改变数据类型。 –

1

看起来像GitPython找不到git.exe。

尝试设置环境变量GIT_PYTHON_GIT_EXECUTABLE。 这是应该最有可能是 “C:\ Program Files文件(x86)的\的Git \ BIN \ git.exe” 如果使用混帐的Windows与默认

在命令行(CMD.EXE)

set GIT_PYTHON_GIT_EXECUTABLE="C:\Program Files (x86)\Git\bin\git.exe" 
0
from git import Repo 
def has_uncommited(repo_path): 
    repo = Repo(repo_path) 
    untracked = repo.untracked_files 
    return untracked is None 

会做你想要什么,根据documentation,反正。

1

感谢您的建议,但实施它们并没有真正解决我的问题。只要

def statusChecker(repo, lastCommit): 
    uncommittedFiles = [] 
    files = os.listdir(repo) 
    for file in files: 
     if os.path.getmtime(repo + "\\\\" + file) > lastCommit: 
      uncommittedFiles.append(file) 
    uncommittedFiles = uncommittedFiles.remove(".git") 
    return uncommittedFiles 

为你使用类似lastCommit = repo.head.commit.committed_datelastCommit说法这应该很好地工作:我没有制定变通用下面的代码。

相关问题