7

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.

user4493177
  • 580
  • 9
  • 30

4 Answers4

4

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

fferri
  • 15,633
  • 3
  • 36
  • 67
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>'...)
Carlo Lobrano
  • 341
  • 1
  • 9
0

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'])
alemol
  • 6,344
  • 1
  • 18
  • 27
0

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)