Find the path of a shell command (shutil.which)

Eryk Sun eryksun at gmail.com
Wed Oct 12 18:14:45 EDT 2022


On 10/12/22, Weatherby,Gerard <gweatherby at uchc.edu> wrote:
>
> When no path is specified, the results of
> os.environ()<https://docs.python.org/3/library/os.html#os.environ> are used,
> returning either the “PATH” value or a fallback of
> os.defpath<https://docs.python.org/3/library/os.html#os.defpath>.

The documentation is out of sync with what the code actually does.
os.defpath is hard coded in posixpath and ntpath, but shutil.which()
actually prefers to query the system's default path to use via
os.confstr(), if it's supported:

    if path is None:
        path = os.environ.get("PATH", None)
        if path is None:
            try:
                path = os.confstr("CS_PATH")
            except (AttributeError, ValueError):
                # os.confstr() or CS_PATH is not available
                path = os.defpath

As documented by POSIX, the CS_PATH string "can be used as a value of
the PATH environment variable that accesses all of the standard
utilities of POSIX.1-2017, that are provided in a manner accessible
via the exec family of functions".

https://pubs.opengroup.org/onlinepubs/9699919799/functions/confstr.html


More information about the Python-list mailing list