best way of testing a program exists before using it?
grahn+nntp at snipabacken.dyndns.org
Mon Sep 11 22:39:28 CEST 2006
On Mon, 11 Sep 2006 16:21:04 +0100, Steve Holden <steve at holdenweb.com> wrote:
> Hari Sekhon wrote:
>> What is the best way of making sure that the command is installed on the
>> system before I try to execute it, like the python equivalent of the
>> unix command "which"?
> The easiest way to test whether the command will run is to try and run
> it. If the program doesn't exist then you'll get an exception, which you
> can catch. Otherwise you'll be stuck with non-portable mechanisms for
> each platform anyway ...
You don't get an exception from os.system, and it's worse for os.popen and
friends. In some situations (AFAICS) you're toast if the command doesn't
exist; for example, if you feed sys.stdin to something that doesn't exist
and want to back out and feed it to the second best command.
It would have been nice if there was an os.path.isexecutable which walked the
$PATH. Of course, that wouldn't guarantee that the file actually /was/
executable, but ...
// Jorgen Grahn <grahn@ Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn!
More information about the Python-list