Find the path of an executable in Python

A good way to use executables on the system Path, auto-adding the .exe extension on Windows is by Python shutil.which

import shutil
import subprocess

# None if executable not found
exe = shutil.which('ls')

cmd = [exe, '-l']
print(cmd)

subprocess.run(cmd)

The fact that shutil.which() returns None for non-found executables makes it convenient for use with Pytest

Specify path

For non-system utilities or other programs not on PATH, where the executable path is known do like:

shutil.which('myexe', path=str(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))–pathlib.Path won’t work until Python 3.8 for that instance.