best way of testing a program exists before using it?
steve at holdenweb.com
Mon Sep 11 17:54:33 CEST 2006
Hari Sekhon wrote:
> Steve Holden wrote:
>>Hari Sekhon wrote:
>>>I am writing a wrapper to a binary command to run it and then do
>>>something with the xml output from it.
>>>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"?
>>>Otherwise I'd have to do something like:
>>>if os.system('which somecommand') != 0:
>>> print "you don't have %s installed" % somecommand
>>>I know that isn't portable which is why a python solution would be
>>>better (although this will run on unix anyway, but it'd be nice if it
>>>ran on windows too).
>>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 ...
> Yeah, this occurred to me just after I sent the mail, but I don't really
> want to run the program because it will go off and do some work and take
> time to come back. If there is a better way then that would be great. I
> can't think of anything other than what you have suggested with a
> message saying that the program wasn't found in the path which would be
> the most appropriate error since the path could also be wrong.
> Perhaps I'll just bite the bullet and get the program to do something as
> small as possible to test it.
> I guess I'll just have to continue to miss my unix commands...
Erm, but don't you *have* to run the program anyway to produce the
required XML output? So, if the attempt to run it fails then you know it
isn't installed, and if it succeeds then you should have the required
output (I'm presuming either the output will appear in a file or you'll
be using the subprocess module or similar to capture its standard output).
To be specific: I wasn't suggesting that you try to run the program
first just to see whether it existed, I was suggesting you try to run it
to produce the XML, and if it fails then you know you can't.
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list