Python 3.3+shutilfunction
shutil.which()
system and environment
Finds an executable program on PATH like the which command and returns its path, or None if the program is not found.
Syntax
shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None) -> str | None
A missing program yields None, not an exception: check the result before handing it to subprocess, or the failure surfaces later and less clearly. A file without execute permission is not found even if it sits on PATH. If the name contains a directory ('./tool', a full path), PATH is not searched — the file itself is checked. On Windows extensions from PATHEXT are tried, so which('python') finds python.exe.
Examples
import os, shutil, sys
print(shutil.which('no-such-program-xyz')) # → None
print(shutil.which(sys.executable) is not None) # → True
exe_dir, exe_name = os.path.split(sys.executable)
print(shutil.which(exe_name, path=exe_dir)) # → ? /usr/bin/python3.14 — путь зависит от машины
import os, shutil
with open('tool', 'w') as f:
f.write('#!/bin/sh\n')
print(shutil.which('tool', path='.')) # → None — нет права на исполнение
os.chmod('tool', 0o755)
print(shutil.which('tool', path='.')) # → ? ./tool — на Windows иначе
See also
Open in the full glossarydocs.python.orgReport an inaccuracy