user4493177 user4493177 - 1 year ago 187
Python Question

Git add through python subprocess

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 = '';

#list to set directory and working tree
dirList = ['--git-dir='+repoPath+'/.git','--work-tree='+repoPath]

#init gitt[gitPath] + ['init',repoPath]

#add remote[gitPath] + dirList + ['remote','add','origin',repoUrl])

#Check status, returns files to be commited etc, so a working repo exists there[gitPath] + dirList + ['status'])

#Adds all files in folder (this returns the error)[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.

Answer Source

You need to specify the working directory.

subprocess.Popen has a keyword argument to do so:

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

See also Python specify popen working directory via argument

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download