os independent way of seeing if an executable is on the path?
Don
donald.welch at NOSPAM.hp.com
Thu May 26 14:53:04 EDT 2005
Steven Bethard wrote:
> This has probably been answered before, but my Google skills have failed
> me so far...
>
> Is there an os independent way of checking to see if a particular
> executable is on the path? Basically what I want to do is run code like:
> i, o, e = os.popen3(executable_name)
> but I'd like to give an informative error if 'executable_name' doesn't
> refer to an executable on the path.
>
> The idea is to differentiate between errors generated by not being able
> to run the program, and errors generated while running the program. The
> former is a probably a configuration error by my user, the second is
> probably a logic error in my code (or perhaps an error on the executable
> I'm calling).
>
> In Windows, I can read the error file, and get something like:
> "'<program name>' is not recognized as an internal or external
> command,\noperable program or batch file.\n"
> and I'm sure I could parse this, but this seems fragile, and clearly os
> dependent.
>
> It's not crucial that I use os.popen3 as long as I have access to the
> input, output and error files. I played around with subprocess for a
> while, but couldn't see any way to do this using that module either.
>
> Thanks for the help,
>
> STeVe
I wrote this 'which' function for Linux, but I think if you changed the ':'
character, it would work on Windows (I think its a ';' on Windows, but I
can't remember):
def which( command ):
path = os.getenv( 'PATH' ).split( ':' )
found_path = ''
for p in path:
try:
files = os.listdir( p )
except:
continue
else:
if command in files:
found_path = p
break
return found_path
-Don
More information about the Python-list
mailing list