Git通过Python子进程进行添加

8

我正在尝试通过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,添加文件就没有问题,但我无法找出为什么事情会出错。

我不想使用Python的Git库来解决这个问题。

4个回答

4

2

除了使用 Popen 的 cwd 参数,您还可以使用 git 的标志 -C

usage: git [--version] [--help] [-C <path>] [-c name=value]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

因此,它应该是这样的东西。
subprocess.Popen('git -C <path>'...)

0

在Python 2中,这对我有效。

import subprocess 

subprocess.Popen(['git', '--git-dir', '/path/.git', '--work-tree', '/work/dir', 'add', '/that/you/add/file'])

谢谢@Hemaamathavan,只是为了注册,您使用的是哪个Python版本? - alemol
我正在使用 Python 2.7。 - Hemaa mathavan
谢谢@Hemaamathavan,有人在Python3中尝试过这个吗? - alemol

0
你可以使用Python 3.5及以上版本的subprocess.run来实现这个功能。
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)¶
import subprocess
subprocess.run(["git", "clone", "https://github.com/VundleVim/Vundle.vim.git", folder], check=True, stdout=subprocess.PIPE)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接