def which(cmd, mode=os.F_OK | os.X_OK, path=None):
<EOL>def _access_check(fn, mode):<EOL><INDENT>return (os.path.exists(fn) and os.access(fn, mode)<EOL>and not os.path.isdir(fn))<EOL><DEDENT>if os.path.dirname(cmd):<EOL><INDENT>if _access_check(cmd, mode):<EOL><INDENT>return cmd<EOL><DEDENT>return None<EOL><DEDENT>if path is None:<EOL><INDENT>path = os.environ.get("<STR_LIT>", os.defpath)<EOL><DEDENT>if not path:<EOL><INDENT>return None<EOL><DEDENT>path = path.split(os.pathsep)<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>if not os.curdir in path:<EOL><INDENT>path.insert(<NUM_LIT:0>, os.curdir)<EOL><DEDENT>pathext = os.environ.get("<STR_LIT>", "<STR_LIT>").split(os.pathsep)<EOL>if any(cmd.lower().endswith(ext.lower()) for ext in pathext):<EOL><INDENT>files = [cmd]<EOL><DEDENT>else:<EOL><INDENT>files = [cmd + ext for ext in pathext]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>files = [cmd]<EOL><DEDENT>seen = set()<EOL>for dir in path:<EOL><INDENT>normdir = os.path.normcase(dir)<EOL>if not normdir in seen:<EOL><INDENT>seen.add(normdir)<EOL>for thefile in files:<EOL><INDENT>name = os.path.join(dir, thefile)<EOL>if _access_check(name, mode):<EOL><INDENT>return name<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return None<EOL>
Given a command, mode, and a PATH string, return the path which
    conforms to the given mode on the PATH, or None if there is no such
    file.

    `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
    of os.environ.get("PATH"), or can be overridden with a custom search
    path.

    Copied from https://hg.python.org/cpython/file/default/Lib/shutil.py