Find the path of an executable in Python

Sometimes you need to override the system PATH for an executable called by subprocess. You can put PATH only to the needed executable (to avoid that executable loading other executables on paths you don’t want) by

from pathlib import Path
from distutils.spawn import find_executable
import subprocess

myexe='ls' # whatever your exe command is

binpath = Path(find_executable(myexe)).parent 

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

subprocess.run(cmd, env={'PATH':str(binpath)}) 

For example, I use this in my az/el computation addon to astrometry.net that gives azimuth and elevation vs. pixel outputs for a camera, for example–a critical piece of my Ph.D. work.

Categories:

Updated:

Leave a Comment