Python script to determine if a directory is a git repository

Install gitpython, e.g pip install gitpython.

Then make a function like this:

import git

...

def is_git_repo(path):
    try:
        _ = git.Repo(path).git_dir
        return True
    except git.exc.InvalidGitRepositoryError:
        return False

Close! Popen is a more complicated object that starts a process but requires other interaction to get information. In your case, you need to call wait() so that the Popen object waits for the program completes to get the return code. You also risk the program hanging if the command returns too much information to fit in the pipe. Try 'call' (it calls wait for you) and send the command output to the bit bucket.

#! /usr/bin/env python

from subprocess import call, STDOUT
import os
if call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w')) != 0:
    print("Nope!")
else:
    print("Yup!")

While tdelaney's answer is correct, I would like to post a function which is more generalised and can be quickly copy-pasted into someone's script:

There are two requirements for the function:

import os
import subprocess

And the function is quite simple:

def is_git_directory(path = '.'):
    return subprocess.call(['git', '-C', path, 'status'], stderr=subprocess.STDOUT, stdout = open(os.devnull, 'w')) == 0