Find executable path in Python
The full path to executables on the system Path are discovered by Python
shutil.which.
On Windows, this also auto-adds the .exe
extension.
A caveat on Unix-like systems (Linux, MacOS) is that shell aliases are not necessarily found by shutil.which. You should instead append the directory of the desired executable to environment variable PATH.
import shutil
# None if executable not found
exe = shutil.which('ls')
cmd = [exe, '-l']
print(cmd)
Since shutil.which()
returns None
for non-found executable it is convenient for
pytest.mark.skipif
For non-system utilities or other programs not on PATH, where the executable path is known, the path can be specified:
shutil.which('myexe', path=mypath)
Fixed in Python 3.8, but present in earlier Python versions is a bug that requires a string for shutil.which(..., path=str(mypath))
.