In Python, is there a portable and simple way to test if an executable program exists?
By simple I mean something like the which
command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with Popen
& al and see if it fails (that's what I'm doing now, but imagine it's launchmissiles
)
The best example should be the python bulit-in module shutil.which() in Python 3. The link is https://hg.python.org/cpython/file/default/Lib/shutil.py
I know that I'm being a bit of a necromancer here, but I stumbled across this question and the accepted solution didn't work for me for all cases Thought it might be useful to submit anyway. In particular, the "executable" mode detection, and the requirement of supplying the file extension. Furthermore, both python3.3's
shutil.which
(usesPATHEXT
) and python2.4+'sdistutils.spawn.find_executable
(just tries adding'.exe'
) only work in a subset of cases.So I wrote a "super" version (based on the accepted answer, and the
PATHEXT
suggestion from Suraj). This version ofwhich
does the task a bit more thoroughly, and tries a series of "broadphase" breadth-first techniques first, and eventually tries more fine-grained searches over thePATH
space:Usage looks like this:
The accepted solution did not work for me in this case, since there were files like
meld.1
,meld.ico
,meld.doap
, etc also in the directory, one of which were returned instead (presumably since lexicographically first) because the executable test in the accepted answer was incomplete and giving false positives.There is a which.py script in a standard Python distribution (e.g. on Windows
'\PythonXX\Tools\Scripts\which.py'
).EDIT:
which.py
depends onls
therefore it is not cross-platform.You can try the external lib called "sh" (http://amoffat.github.io/sh/).
For python 3.2 and earlier:
This is a one-liner of Jay's Answer, Also here as a lambda func:
Or lastly, indented as a function:
For python 3.3 and later:
As a one-liner of Jan-Philip Gehrcke Answer:
As a def:
See os.path module for some useful functions on pathnames. To check if an existing file is executable, use os.access(path, mode), with the os.X_OK mode.
EDIT: The suggested
which()
implementations are missing one clue - usingos.path.join()
to build full file names.