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
)
Just remember to specify the file extension on windows. Otherwise, you have to write a much complicated
is_exe
for windows usingPATHEXT
environment variable. You may just want to use FindPath.OTOH, why are you even bothering to search for the executable? The operating system will do it for you as part of
popen
call & will raise an exception if the executable is not found. All you need to do is catch the correct exception for given OS. Note that on Windows,subprocess.Popen(exe, shell=True)
will fail silently ifexe
is not found.Incorporating
PATHEXT
into the above implementation ofwhich
(in Jay's answer):On the basis that it is easier to ask forgiveness than permission I would just try to use it and catch the error (OSError in this case - I checked for file does not exist and file is not executable and they both give OSError).
It helps if the executable has something like a
--version
flag that is a quick no-op.This is not a general solution, but will be the easiest way for a lot of use cases - those where the code needs to look for a single well known executable.
Using the python fabric library:
I know this is an ancient question, but you can use
distutils.spawn.find_executable
. This has been documented since python 2.4 and has existed since python 1.6.Also, Python 3.3 now offers
shutil.which()
.This seems simple enough and works both in python 2 and 3
None of previous examples do work on all platforms. Usually they fail to work on Windows because you can execute without the file extension and that you can register new extension. For example on Windows if python is well installed it's enough to execute 'file.py' and it will work.
The only valid and portable solution I had was to execute the command and see error code. Any decent executable should have a set of calling parameters that will do nothing.