Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 867
user4493177 Avatar asked Aug 01 '15 22:08

user4493177


1 Answers

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

like image 96
fferri Avatar answered Oct 19 '22 16:10

fferri