Skip to content

Linux: shutil.which fails to find executable in current working directory/cwd when PATH unset (subprocess works) #141041

@grqz

Description

@grqz

Bug report

Bug description:

On Linux, executables from the cwd are used when PATH is unset:

$ PATH= python -V
Python 3.13.7

subprocess.run also works in this case:

$ PATH= python -q
>>> from subprocess import run
... run(['python', '-V'])
... 
Python 3.13.7
CompletedProcess(args=['python', '-V'], returncode=0)
>>> 

But shutil.which returns None:

>>> from shutil import which
>>> which('python')
>>> 

This is because when PATH is empty(""), the executable ("python") is passed to the kernel's execve directly, without resolving. execve then resolves the file relative to the cwd, I believe it's the case in both Linux and FreeBSD.
POSIX 2024 says this about the PATH environment variable:

If PATH is unset or is set to null, or if a path prefix in PATH contains a character ('%'), the path search is implementation-defined.

EDIT: PATH is empty, not unset

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions