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
)
So basically you want to find a file in mounted filesystem (not necessarily in PATH directories only) and check if it is executable. This translates to following plan:
I'd say, doing this in a portable way will require lots of computing power and time. Is it really what you need?
I found something in StackOverflow that solved the problem for me. This works provided the executable has an option (like --help or --version) that outputs something and returns an exit status of zero. See Suppress output in Python calls to executables - the "result" at the end of the code snippet in this answer will be zero if the executable is in path, else it is most likely to be 1.
An important question is "Why do you need to test if executable exist?" Maybe you don't? ;-)
Recently I needed this functionality to launch viewer for PNG file. I wanted to iterate over some predefined viewers and run the first that exists. Fortunately, I came across
os.startfile
. It's much better! Simple, portable and uses the default viewer on the system:Update: I was wrong about
os.startfile
being portable... It's Windows only. On Mac you have to runopen
command. Andxdg_open
on Unix. There's a Python issue on adding Mac and Unix support foros.startfile
.It would seem the obvious choice is "which", parsing the results via popen, but you could simulate it otherwise using the os class. In pseudopython, it would look like this:
Python 3.3 now offers shutil.which().
For *nix platforms (Linux and OS X)
This seems to be working for me:
Edited to work on Linux, thanks to Mestreion
What we're doing here is using the builtin command
type
and checking the exit code. If there's no such command,type
will exit with 1 (or a non-zero status code anyway).The bit about stdout and stderr is just to silence the output of the
type
command, since we're only interested in the exit status code.Example usage: