Git通过python子进程添加

Git通过python子进程添加

本文介绍了Git通过python子进程添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过python子进程运行git命令.我是通过在github的cmd目录中调用git.exe来实现的.

I am trying to run git commands through python subprocess. I do this by calling the git.exe in the cmd directory of github.

我设法使大多数命令都起作用(初始化,远程,状态),但是在调用git add时出现错误.到目前为止,这是我的代码:

I managed to get most commands working (init, remote, status) but i get an error when calling git add. This is my code so far:

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

So i searched for this error, and most solutions i found were about not being in the right directory. So my guess would also be that. However, i do not know why. Git status returns the correct files in the directory, and i have set --git-dir and --work-tree

如果我转到git shell,我可以毫无问题地添加文件,但是我无法找出为什么这里出问题了.

If i go to git shell i have no problem adding files, but i cannot find out why things go wrong here.

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

I am not looking for a solution using pythons git library.

推荐答案

您需要指定工作目录.

函数 Popen call check_call check_output 具有 cwd 关键字参数,例如:

Functions Popen, call, check_call, and check_output have a cwd keyword argument to do so, e.g.:

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

另请参见为popen指定工作目录

这篇关于Git通过python子进程添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:33