[issue37894] [win] shutil.which can not find the path if 'cmd' include directory path and not include extension name

Eryk Sun report at bugs.python.org
Thu Aug 22 00:41:10 EDT 2019


Eryk Sun <eryksun at gmail.com> added the comment:

The code that sets up the PATHEXT `files` could be moved up. It also needs to be fixed in order to implement the correct behavior. For example:

    use_bytes = isinstance(cmd, bytes)

    files = [cmd]
    if _WINDOWS:
        # Also look for the name plus each PATHEXT extension.
        default_pathext = '.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC'
        pathext = os.environ.get('PATHEXT', default_pathext)
        if use_bytes:
            pathext = os.fsencode(pathext).split(b';')
        else:
            pathext = pathext.split(';')
        for ext in pathext:
            files.append(cmd + ext)

    # If we're given a path with a directory part, look it up directly rather
    # than referring to PATH directories. This includes checking relative to the
    # current directory, e.g. ./script.
    if os.path.dirname(cmd):
        for file in files:
            if _access_check(file, mode):
                return file
        return None

The author of the PATHEXT code in shutil.which() was following a source that documented the behavior incorrectly. CMD always looks for the filename before trying to append the PATHEXT extensions. It does not limit its search to PATHEXT extensions. The only exception is a file that has no extension, in which case "." has to be set in PATHEXT to get CMD to find the file. However, where.exe finds a file that has no extension, regardless of PATHEXT, so Python's which() should be free to follow that example.

----------
nosy: +eryksun
stage:  -> needs patch
versions:  -Python 3.5

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37894>
_______________________________________


More information about the Python-bugs-list mailing list