os independent way of seeing if an executable is on the path?

Scott David Daniels Scott.Daniels at Acm.Org
Thu May 26 15:46:50 EDT 2005


Don wrote:

> 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):
Why remember when os.pathsep will do it for you.
However, for windows you need a bit more:

def which(command):
     win32 = sys.platform == 'win32'
     if win32:
	# Case-insesitive file names and file exts for commands
	try:
             knownexts = [''] + os.getenv('PATHEXT').split(os.pathsep)
         except AttributeError:
	    knownexts = ['']
         else:
             knownexts = [ext.lower() for ext in knownexts]
         test = command.lower()
         tests = set(test + ext for ext in knownexts)
     else:
	tests = set([command])
     for dirname in os.getenv('PATH').split(os.pathsep):
         try:
             files = os.listdir(dirname)		
         except IOError:
             continue
         else:
             for name in files:
		if name in tests or win32 and name.lower() in tests:
		    yield dirname, name


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list