python - Git通过python子进程添加

标签 python git github cmd subprocess

我正在尝试通过 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 状态返回目录中的正确文件,我已经设置了 --git-dir 和 --work-tree

如果我转到 git shell,我可以毫无问题地添加文件,但我找不到这里出错的原因。

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

最佳答案

您需要指定工作目录。

函数 Popen , call , check_call , 和 check_output有一个 cwd 关键字参数来这样做,例如:

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

另见 Specify working directory for popen

关于python - Git通过python子进程添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766655/

相关文章:

git - 寻求单个团队项目下多个 Git 存储库的命名约定

git - .github/workflows 文件是特定于分支的吗?

python - 将文本大小转换为数据坐标

python - 从 scrapy 中获取 None

python - Pandas :dt.dayofweek 显示不正确的值

python - Intellisense 不适用于 python

android - 如何从 Android Studio 在 Synology 上使用 Git?

git - 如何在不丢失 +2 票的情况下一次重新设置 Gerrit 审查的所有提交?

github - 更改 Github 的默认 Gist 样式

Jenkins简单管道不是由github推送触发的