我刚刚开始使用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”的返回码打印输出。但是,该脚本在存储库中不起作用。
无论如何,对于这方面的任何建议,我将不胜感激。
作业还包括:
非常感谢!
答案 0 :(得分:7)
安装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
答案 1 :(得分:5)
虽然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
答案 2 :(得分:4)
关闭! Popen是一个更复杂的对象,它启动一个过程,但需要其他交互来获取信息。在您的情况下,您需要调用wait(),以便Popen对象等待程序完成以获取返回代码。如果命令返回太多信息以适应管道,那么您也会冒着程序挂起的风险。尝试'call'(它调用等待你)并将命令输出发送到位桶。
#! /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!")
答案 3 :(得分:4)
让python检查并查看当前运行目录中是否存在名为.git的文件夹会不会更容易?
答案 4 :(得分:1)
您可以安装GitPython,然后可以应用此代码
import git
def is_git_repo(path):
try:
_ = git.Repo(path).git_dir
return True
except git.exc.InvalidGitRepositoryError:
return False
答案 5 :(得分: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