Git add through python subprocess Git add through python subprocess git git

Git add through python subprocess


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


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


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