Git add via python subprocess

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

I managed to get most of the commands to work (init, remote, status), but I get an error when calling git add. This is my code:

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 am getting is:

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

So, I was looking for this error, and most of the solutions I found were not in the correct directory. So I assumed that it is. However, I do not know why. git status returns the correct files in the directory, and I installed - git -dir and -work-tree

If I go to the git shell, I have no problem adding files, but I can’t find out why something is wrong here.

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

+4
source share
3 answers

You need to specify the working directory.

subprocess.Popen has a keyword argument for this:

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

See also Python. Specifies the popen working directory through an argument.

+1
source

Besides using the cwd Popen argument, you can also use the git -C flag:

 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 it should be something like

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

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']) 
0
source

All Articles