Git通过python子进程添加

我试图通过python子进程运行git命令.我这样做是通过调用github的cmd目录中的git.exe来实现的.

我设法让大多数命令工作(init,remote,status)但是在调用git add时出错了.到目前为止这是我的代码:

import subprocess

gitPath = 'C:/path/to/git/cmd.exe'
repoPath = 'C:/path/to/my/repo'
repoUrl = 'https://www.github.com/login/repo';

#list to set directory and working tree
dirList = ['--git-dir='+repoPath+'/.git','--work-tree='+repoPath]


#init gitt
subprocess.call([gitPath] + ['init',repoPath]

#add remote
subprocess.call([gitPath] + dirList + ['remote','add','origin',repoUrl])

#Check status,returns files to be commited etc,so a working repo exists there
subprocess.call([gitPath] + dirList + ['status'])

#Adds all files in folder (this returns the error)
subprocess.call([gitPath] + dirList + ['add','.']

我得到的错误是:

fatal: Not a git repository (or any of the parent directories): .git

所以我搜索了这个错误,我找到的大多数解决方案都是关于不在正确的目录中.所以我的猜测也就是这样.但是,我不知道为什么. Git status返回目录中的正确文件,我已经设置了–git-dir和–work-tree

如果我去git shell我没有问题添加文件,但我不知道为什么这里出问题.

我不是在寻找使用pythons git库的解决方案.

最佳答案
您需要指定工作目录.

函数Popen,call,check_callcheck_output有一个cwd关键字参数,例如:

subprocess.call([gitPath] + dirList + ['add','.'],cwd='/home/me/workdir')

另见Specify working directory for popen

相关文章

本文从多个角度分析了vi编辑器保存退出命令。我们介绍了保存...
Python中的回车和换行是计算机中文本处理中的两个重要概念,...
SQL Server启动不了错误1067是一种比较常见的故障,主要原因...
信息模块是一种可重复使用的、可编程的、可扩展的、可维护的...
本文从电脑配置、PyCharm版本、Java版本、配置文件以及程序冲...
本文主要从多个角度分析了安装SQL Server 2012时可能出现的错...