7

我刚开始使用 Python,我的第一个任务是编写一个脚本来确定运行它的目录是否是 git 存储库。一位同学建议了以下代码:

#! /usr/bin/env python

from subprocess import Popen, PIPE, STDOUT
if Popen(("git", "branch"), stderr=STDOUT, stdout=PIPE).returncode != 0:
    print("Nope!")
else:
    print("Yup!")

它应该根据控制台命令“git branch”的返回码打印输出。但是,该脚本在存储库中不起作用。

无论如何,我将不胜感激有关此的任何建议。

任务还包括:

  • 能够在 Windows 上使用相同的脚本
  • 最终传递路径以确定脚本,而无需将其复制到目标目录

非常感谢!

4

6 回答 6

22

安装gitpython,例如pip install gitpython

然后做一个这样的函数:

import git

...

def is_git_repo(path):
    try:
        _ = git.Repo(path).git_dir
        return True
    except git.exc.InvalidGitRepositoryError:
        return False
于 2016-10-10T10:49:47.820 回答
6

虽然 tdelaney 的回答是正确的,但我想发布一个更通用的函数,可以快速复制粘贴到某人的脚本中:

该功能有两个要求:

import os
import subprocess

而且功能很简单:

def is_git_directory(path = '.'):
    return subprocess.call(['git', '-C', path, 'status'], stderr=subprocess.STDOUT, stdout = open(os.devnull, 'w')) == 0
于 2014-07-05T08:08:00.800 回答
6

关!Popen 是一个更复杂的对象,它启动一个进程但需要其他交互来获取信息。在您的情况下,您需要调用 wait() 以便 Popen 对象等待程序完成以获取返回码。如果命令返回的信息太多而无法放入管道,您还会冒程序挂起的风险。尝试“呼叫”(它会呼叫等待您)并将命令输出发送到位桶。

#! /usr/bin/env python

from subprocess import call, STDOUT
import os
if call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w')) != 0:
    print("Nope!")
else:
    print("Yup!")
于 2013-10-30T16:15:10.617 回答
4

Wouldn't it be easier to just have python check and see if a folder named .git is present in the current running directory?

于 2013-10-30T16:24:21.040 回答
1

您可以安装 GitPython,然后您可以应用此代码

import git

def is_git_repo(path):
    try:
        _ = git.Repo(path).git_dir
        return True
    except git.exc.InvalidGitRepositoryError:
        return False
于 2020-07-01T22:28:21.700 回答
0

有问题的文件夹也可能git repo 中。出于这个原因,我也喜欢提取根文件夹:

def getGitRoot(p):
    """Return None if p is not in a git repo, or the root of the repo if it is"""
    if call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w'), cwd=p) != 0:
        return None
    else:
        root = check_output(["git", "rev-parse", "--show-toplevel"], cwd=p)
        return root
于 2018-06-19T14:10:22.150 回答