I am trying to connect and execute GIT commands using python such as pull, check status, add and commit new files etc.
I am using python 3.7, PyCharm for IDE and GitPython 2.1.7 as a library. I have also used the following tutorial: https://www.fullstackpython.com/blog/first-steps-gitpython.html
But I have an issue with the GIT executable it seems. I have followed the code within the tutorial to the T, barring setting up the environment as PyCharm does this for me.
I am receiving the following error:
"
raise ImportError(err)
ImportError: Bad git executable.
The git executable must be specified in one of the following ways:
- be included in your $PATH
- be set via $GIT_PYTHON_GIT_EXECUTABLE
- explicitly set via git.refresh()
All git commands will error until this is rectified.
This initial warning can be silenced or aggravated in the future by setting the $GIT_PYTHON_REFRESH environment variable.
Use one of the following values:
- quiet|q|silence|s|none|n|0: for no warning or exception
- warn|w|warning|1: for a printed warning
- error|e|raise|r|2: for a raised exception
Example:
export GIT_PYTHON_REFRESH=quiet
"
I have set my environmental variable "Path" to my Git\bin path as informed by another user on here asking a similar question, but to no avail.
Any help is very much appreciated!
import os
from git import Repo
COMMITS_TO_PRINT = 5
def print_commit(commit):
print('----')
print(str(commit.hexsha))
print("\"{}\" by {} ({})".format(commit.summary,
commit.author.name,
commit.author.email))
print(str(commit.authored_datetime))
print(str("count: {} and size: {}".format(commit.count(),
commit.size)))
def print_repository(repo):
print('Repo description: {}'.format(repo.description))
print('Repo active branch is {}'.format(repo.active_branch))
for remote in repo.remotes:
print('Remote named "{}" with URL "{}"'.format(remote, remote.url))
print('Last commit for repo is {}.'.format(str(repo.head.commit.hexsha)))
if __name__ == "__main__":
repo_path = os.getenv('GIT_REPO_PATH')
# Repo object used to programmatically interact with Git repositories
repo = Repo(repo_path)
# check that the repository loaded correctly
if not repo.bare:
print('Repo at {} successfully loaded.'.format(repo_path))
print_repository(repo)
# create list of commits then print some of them to stdout
commits = list(repo.iter_commits('master'))[:COMMITS_TO_PRINT]
for commit in commits:
print_commit(commit)
pass
else:
print('Could not load repository at {} :('.format(repo_path))