Git add through python subprocess

99封情书 提交于 2021-02-19 01:06:52

问题


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

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','.']

The error i get is:

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

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

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

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


回答1:


You need to specify the working directory.

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')

See also Specify working directory for popen




回答2:


Other than using cwd Popen's argument, you could also use git's flag -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>]

So that it should be something like

subprocess.Popen('git -C <path>'...)



回答3:


In Python 2 this works for me.

import subprocess 

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



回答4:


You can use subprocess.run for this since Python 3.5

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)


来源:https://stackoverflow.com/questions/31766655/git-add-through-python-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!