Python: Find an executable with an explicit shutil.which search path
A script can resolve a tool from a chosen directory without changing the process environment. Pass that directory through shutil.which(path=...) and handle a missing executable before attempting to launch anything.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as scoped_lookup_demo.py in an empty working directory:
from pathlib import Path
from shutil import which
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
root = Path(directory)
tool = root / "demo-tool"
tool.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
tool.chmod(0o600)
print("Before executable bit:", which("demo-tool", path=str(root)))
tool.chmod(0o700)
found = which("demo-tool", path=str(root))
print("Selected expected file:", found == str(tool))
print("Missing:", which("absent-tool", path=str(root)))Run it without -O so any assertions remain enabled:
python3 scoped_lookup_demo.pyCaptured output:
Before executable bit: None
Selected expected file: True
Missing: NoneOn Linux, the default lookup checks that the candidate exists and is executable. The first lookup fails because the file lacks execute permission. The second finds the same file after its mode changes. The script never executes it and removes the temporary directory automatically.
Limits and cleanup
Use absolute directories you control and pass the returned path to the process launcher. Lookup does not validate a program’s contents or prevent replacement between lookup and execution. A command containing a directory component is checked directly; the search path does not restrict such a command.
After testing, remove the example script from its working directory:
rm -- scoped_lookup_demo.pyReference
Acknowledgements
This post was created with assistance from AI.