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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With