You can use: GitPython

Or 'native way':

from subprocess import Popen, PIPE
cmd = 'git diff --name-only'
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
files_changed_list = stdout.decode("utf-8").splitlines()
Answer from David Meu on Stack Overflow
🌐
Sling Academy
slingacademy.com › article › python-how-to-programmatically-run-git-commands-and-parse-the-output
Python: How to programmatically run Git commands and parse the output - Sling Academy
This code snippet searches for the phrase ‘Untracked files:’ in the git status output to determine if there are any untracked files in the repository. To make the calling of Git commands cleaner and more reusable, let’s wrap them in Python functions: def run_git_command(command): try: process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode != 0: raise Exception(f'Git command failed with the following error:\n{stderr.decode()}') return stdout.decode().strip() except Exception as e: print(e) # Example usage output = run_git_command(['git', 'status']) print(output)
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › tutorial.html
GitPython Tutorial — GitPython 3.2.1 documentation
If set to full, the executed git command _and_ its entire output on stdout and stderr will be shown as they happen · NOTE: All logging is outputted using a Python logger, so make sure your program is configured to show INFO-level messages.
🌐
GitHub
gist.github.com › sparkydogX › e88b95586c843398f057bc28ce602277
Execute terminal command and get output in python. · GitHub
I have a shell script which I am executing from git bash here. I automated the same using python subprocess which will launch gitbash and execute the shell script. I am not able to get the gitbash console output to python console.
🌐
GitHub
gist.github.com › nathania › 2840185
Execute git command from Python script · GitHub
May 2, 2014 - Save nathania/2840185 to your computer and use it in GitHub Desktop. ... This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ... I made a git command in python, http://goo.gl/JUHJjc would you like to have some comments on it, I am going to do a version using gitPython API which i discovered after I was all done with the one using subprocess, however still debating which approach is better !
🌐
LinuxTut
linuxtut.com › en › 320304683aa291ea2b87
Let's parse the git commit log in Python!
July 10, 2013 - So, this time, I will write it with the theme of ** Parsing Git commit log with Python **. In order to use a module that uses git, you first need to ** get the output of the git command **. So let's create a git function that gets the output of the git command using the `` subprocess` module. from subprocess import Popen, PIPE class GitError(BaseException): """Occurs when an error occurs in the acquisition result of the git function""" pass def git(cmd, *args): """Get and return git execution result""" proc = Popen( ("git", cmd) + args, stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if len(err) == 0: return out[:-1] else: raise GitError(err)
🌐
PyPI
pypi.org › project › git-adapter
git-adapter · PyPI
July 7, 2020 - It is useful when you know exactly what Git commands you would call from the shell prompt or in a shell script. Calling a git command returns a str generator representing the lines of output (at least in the default, greedy API, see below).
      » pip install git-adapter
    
Published: Nov 05, 2023
Version: 0.3.0
Find elsewhere
🌐
UnoGeeks
unogeeks.com › home › blog › python git
Python Git
January 8, 2024 - Using Git through the Command Line: You can use Python’s subprocess module to run Git commands through the command line. This approach allows you to interact with Git just like you would from the terminal. Example code to execute Git commands through Python using subprocess: ... def git_command(command): process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() return stdout.decode(), stderr.decode() # Example usage: output, error = git_command('git status') print("Output:", output) print("Error:", error)
🌐
Medium
medium.com › @wide4head › interfacing-git-from-python-abb55c548853
Interfacing with git from python. many a time we may need to get the git… | by Preveen P | Medium
August 30, 2024 - import subprocess def get_commit_info(): result = subprocess.run(['git', 'show', '--no-patch', '--no-notes', '--date=short', 'HEAD'], stdout=subprocess.PIPE) output = result.stdout.decode().strip() lines = output.split('\n') commit_hash = lines[0].strip() commit_date = lines[1].strip() return commit_hash, commit_date commit_hash, commit_date = get_commit_info() print(f"Commit Hash: {commit_hash}") print(f"Commit Date: {commit_date}") The above uses git command line program internally.
🌐
GeeksforGeeks
geeksforgeeks.org › python › automating-some-git-commands-with-python
Automating some git commands with Python - GeeksforGeeks
April 8, 2026 - ... import git repo = ... To update the local repository with the latest changes from the remote repository we use git pull command...
🌐
Waylon Walker
waylonwalker.com › python-git
Using Git from Python | Waylon Walker
April 30, 2022 - There is a good tutorial to get you started with their pure python implementation in their docs. Requesting the git status can be done as follows. note I have prefixed my commands with »> to distinguish between the command I entered and the output.
🌐
OneUptime
oneuptime.com › home › blog › how to execute system commands from python
How to Execute System Commands from Python
January 25, 2026 - import subprocess # Run command in a specific directory result = subprocess.run( ['git', 'log', '--oneline', '-5'], cwd='/path/to/your/repo', capture_output=True, text=True ) print(result.stdout) import subprocess def git_status(repo_path): """Get git status for a repository.""" result = subprocess.run( ['git', 'status', '--porcelain'], cwd=repo_path, capture_output=True, text=True, check=True ) return result.stdout.strip() def git_commit(repo_path, message): """Create a git commit.""" # Stage all changes subprocess.run( ['git', 'add', '-A'], cwd=repo_path, check=True ) # Commit subprocess.run( ['git', 'commit', '-m', message], cwd=repo_path, check=True )
Top answer
1 of 2
5

When not writing to a terminal, git clone doesn't have any output to either stdout or stderr, except on error.

When writing to a terminal, of course, it has lots of output—but that output is progress bars that are continually overwritten. Usually, you don't want that—it's going to be a big mess of control characters and repeated lines.

But if you do want it, there are two options.


First, you can use a PTY (Pseudo-TTY). You can create a PTY with os.openpty, then hand the PTY off explicitly to the child process. Or you can use os.forkpty, which handles forking and automatically hooking up the PTY so all you have to do is call one of the os.exec functions. Or you can use the pty module. (It's not entirely clear which is more portable; openpty and forkpty claim that pty is more portable, and conceptually it's designed that way… but it's also only really tested on Linux.)

Note that git wants the PTY as its stderr, not its stdout.


Alternatively, most git commands have a --progress flag that causes them to write progress to stderr even if it's not a terminal. At least as of the version documented here, this includes clone, but of course you should check the man for your local version. So, that may be all you need. (Also see the --verbose flag.)

However, this may not be as nice. For me, when I provide a PTY with no attached termcaps, I get each line followed by a \r without \n to overwrite it; when I use the --progress option, git detects the termcaps of whatever terminal my script happens to be running it, which means I end up getting ANSI color codes as well as \rs.


Of course either way I'm getting hundreds of useless lines that I have no interest in, but I assume that's what you wanted? (Or maybe you want to use universal_newlines='\r' to translate the '\r' to '\n'? That's slightly cheating, because this is self-overwriting Unix terminal output, and you're pretending it's classic-Mac output… but it works.)

2 of 2
0

I had a similar issue, but I also wanted real-time progress because the git clone was taking a long time (like 5 minutes), since it was a large git repo. And I wanted to provide real-time feedback to the user.

Here is a Python 3.7 working example:

# This will print stdout/stderr as it comes in
def run_shell_command_with_realtime_output(shell_command_string, working_dir='.'):
    # print the command to be executed, just for fun
    print("run_shell_command >", shell_command_string)

    # run it, this will NOT block
    sub_process = subprocess.Popen(shell_command_string,
                                   shell=True,
                                   cwd=working_dir, universal_newlines=True,
                                   stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # print the stdout/stderr as it comes in
    while True:
        # The readline() will block until...
        # it reads and returns a string that ends in a '\n',
        # or until the process has ended which will result in '' string
        output = sub_process.stdout.readline()
        if output:
            print(output.strip())
        elif sub_process.poll() is not None:
            break

    # get the return code
    return_code = sub_process.wait()

    # Was there an error?
    if return_code != 0:
        print("FYI, the subprocess had an error, you might want to do something special...")

    # return the sub_process, in case the caller wants to check exit/return codes
    return sub_process

It turns out git clone does not seem to write to stdout/stderr like we normally are used to. Instead it uses a pager, which is how it updates the same line, like when it is cloning, and the % is incrementing on the same line.

So you need to call it like this.

# prepare to clone the git repo
git_clone_url_with_credentials = "https://<username>:<password>@bitbucket.org/myreponame.git"
git_clone_with_progress_cmd = "git --no-pager clone --progress {}".format(git_clone_url_with_credentials)
helpers_misc.run_shell_command_with_progress(git_clone_with_progress_cmd)

And that should do it...