I would like to use GitPython in the following scenario:
I want to use the portable git, no matter if git is already installed or not (the reason being this issue).
I know i can specify the git executable by setting the GIT_PYTHON_GIT_EXECUTABLE
environment variable, but
i've not found a way to do this on windows (setx
seems to do something, but env
shows no such variable afterward) apart from manually editing the system environment variables.
This is supposed to be an end-user program, i cannot ship instructions like "please set an environment variable".
The path is only known when the program is already running.
So my question is, how can i set the executable path manually during runtime? The following does not seem to work, it only prints git
and my system's git version:
import os
import sys
# Download and extract a portable git
git_dir = r"C:\Users\Florian\Downloads\mingit-busybox\cmd"
git_bin = os.path.join(git_dir, "git")
os.putenv("GIT_PYTHON_GIT_EXECUTABLE", git_bin)
os.environ.putenv("GIT_PYTHON_GIT_EXECUTABLE", git_bin)
# Attempt with VonC's Answer, making sure that it is first in PATH
sys.path = [git_dir] + sys.path
os.pathsep.join([git_dir]) + os.pathsep + os.environ["PATH"]
# Only import git now, because that's when the path is checked!
import git
g = git.Git()
print(g.GIT_PYTHON_GIT_EXECUTABLE)
print(".".join([str(v) for v in g.version_info]))
❯ python .\gitpython_test.py
git
2.23.0 # My portable git version is 2.20.1
Check if, in addition of setting, you could set the PATH.
See "how to set PATH=%PATH%
as environment in Python script?"
The goal is to set PATH
to C:\Users\Florian\Downloads\mingit-busybox\cmd;%PATH%
, meaning the git
from mingit-busybox
would come first.
Here's a minimal example:
git_dir = r"C:\Users\Florian\Downloads\mingit-busybox\cmd"
# Make sure it's at the beginning of the PATH
os.environ["PATH"] = os.pathsep.join([git_dir]) + os.pathsep + os.environ["PATH"]
# NOW import it
import git