使用命令可以判断
git rev-parse --is-inside-work-tree
返回true即是git仓库,返回其他值,都是非git仓库。
代码实现:
import subprocess
repo_dir = "../path/to/check/"
command = ['git', 'rev-parse', '--is-inside-work-tree']
process = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=repo_dir,
universal_newlines=True)
process_output = process.communicate()[0]
is_git_repo = str(process_output.strip())
if is_git_repo == "true":
print("success! git repo found under {0}".format(repo_dir))
else:
print("sorry. no git repo found under {0}".format(repo_dir))
参考链接:https://stackoverflow.com/questions/2044574/determine-if-directory-is-under-git-control