Find command in $PATH

April 19, 2010

I make calls to external commands from Python quite often. Sometimes it is desirable to know if a command is available on the running system before making a call to subprocess.call(). Here’s the code I came up with for doing that:

import os

def find_in_path(cmd):
    for path in os.environ[“PATH”].split(os.pathsep):
        full_cmd = os.path.join(path, cmd)
        if os.path.exists(full_cmd) and os.access(full_cmd, os.X_OK):
            return full_cmd
    return None

If there’s a better way to do this, or even a builtin python way, don’t hesitate to mention it.