I commonly use os.path.exists()
to check if a file is there before doing anything with it.
I\'ve run across a situation where I\'m calling a executable that
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.