pythongitdirectoryrepository

Python script to determine if a directory is a git repository


I have just started with Python and my first assignment is to write a script to determine if a directory where it is ran is a git repository. A co-student suggested this code:

#! /usr/bin/env python

from subprocess import Popen, PIPE, STDOUT
if Popen(("git", "branch"), stderr=STDOUT, stdout=PIPE).returncode != 0:
    print("Nope!")
else:
    print("Yup!")

It should print an output depending on what the returncode of console command "git branch" is. However, the script did not work in the repository.

In any case, I would be grateful for any piece of advice regarding this.

The assignment also includes:

Many thanks!


Solution

  • 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 to complete 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!")