[英]Python git module Invalid git repository error
我有一个放置在文件夹结构中的脚本,例如:
~/wofc/folder1/folder2/script.py
script.py
使用git模块执行一些任务。 但是,当我从folder2
外部运行脚本时,即当我将cd
放入folder1
我运行python folder2/script.py arg1 arg2
我会raise InvalidGitRepositoryError(epath)
错误。 当我从folder2
内部运行脚本时,脚本运行良好,即cd
进入folder2
并运行python script.py arg1 arg2
。 以下是相关的代码段。 您能告诉我这是什么问题吗?
git = Repo('{}/..'.format(os.getcwd())).git
git.checkout('master')
git.pull()
而不是Repo('{}/..'.format(os.getcwd())).git
,请使用os.path.abspath
:
git = Repo(os.path.abspath('{}/..'.format(os.getcwd())).git
git.checkout('master')
git.pull()
要运行git commands
,当前文件夹应该是git repo
。
应该存在.git
repo以执行git命令。
这就是错误的原因。
问题是您使用os.getcwd()
返回当前工作目录。 如果您正站在folder2
外面,则此函数将返回~/wofc/folder1
。
您应该将其交换为以下内容:
import os
os.path.dirname(os.path.abspath(__file__))
例如这样:
import os
path = os.path.dirname(os.path.abspath(__file__))
git = Repo('{}/..'.format(path)).git
git.checkout('master')
git.pull()
正如user1846747所说,gitPython需要一个Repo对象来运行git命令。
这是一个典型的引导问题(鸡和鸡蛋问题):“当我需要知道根在哪里创建一个Repo对象以运行git命令时,如何运行gitPython来运行gitPython来查找Repo根目录在哪里? ?”
@MaxNoe在他的python-gitpath项目httpsgithub.com/MaxNoe/python-gitpath中找到文件所在的git存储库的根目录下解决了这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.