os.path.exists() for files in your Path?

Please note that checking for existance and then opening is always open to race-conditions. The file can disappear between your program's check and its next access of the file, since other programs continue to run on the machine.

Thus there might still be an exception being thrown, even though your code is "certain" that the file exists. This is, after all, why they're called exceptions.


Extending Trey Stout's search with Carl Meyer's comment on PATHEXT:

import os
def exists_in_path(cmd):
  # can't search the path if a directory is specified
  assert not os.path.dirname(cmd)

  extensions = os.environ.get("PATHEXT", "").split(os.pathsep)
  for directory in os.environ.get("PATH", "").split(os.pathsep):
    base = os.path.join(directory, cmd)
    options = [base] + [(base + ext) for ext in extensions]
    for filename in options:
      if os.path.exists(filename):
        return True
  return False

EDIT: Thanks to Aviv (on my blog) I now know there's a Twisted implementation: twisted.python.procutils.which

EDIT: In Python 3.3 and up there's shutil.which() in the standard library.


You could get the PATH environment variable, and try "exists()" for the .exe in each dir in the path. But that could perform horribly.

example for finding notepad.exe:

import os
for p in os.environ["PATH"].split(os.pathsep):
    print os.path.exists(os.path.join(p, 'notepad.exe'))

more clever example:

if not any([os.path.exists(os.path.join(p, executable) for p in os.environ["PATH"].split(os.pathsep)]):
    print "can't find %s" % executable

Is there a specific reason you want to avoid exception? (besides dogma?)

Tags:

Python

Windows