Find a specific file, or find all executable files within the system path I wrote a function to find a specific file, or all the executable files with a given name and accessing flag, and I want to make sure it is as cross-platform as possible. Currently, I'm using the PATHEXT environment variable to get the extensions for files that the operating system considers executable.

import os

class CytherError(Exception):
    def __init__(self, message):
        Exception.__init__(self, message)
        self.message = 'CytherError: {}'.format(repr(message))

def where(name, flags=os.F_OK):
    result = []
    extensions = os.environ.get('PATHEXT', '').split(os.pathsep)
    if not extensions:
        raise CytherError("The 'PATHEXT' environment variable doesn't exist")

    paths = os.environ.get('PATH', '').split(os.pathsep)
    if not paths:
        raise CytherError("The 'PATH' environment variable doesn't exist")

    for path in paths:
        path = os.path.join(path, name)
        if os.access(path, flags):
            result.append(os.path.normpath(path))
        for ext in extensions:
            whole = path + ext
            if os.access(whole, flags):
                result.append(os.path.normpath(whole))
    return result


Usage:



In[-]: where('python')

Out[-]: "C:\Python35\python.exe"


Please be brutal in pointing out anything you find, except for:


Commenting
Docstrings
PEP 8 spacing


I will have these things covered later.
I could have just used the function which(), offered by shutil. Documented here.

Example:

&gt;&gt;&gt; from shutil import which
&gt;&gt;&gt; which('python')
'C:\Python35\python.exe'