Monday, August 24, 2009

Python: checking if an executable exists in the path

I wanted to do this on Windows. Based on this StackOverflow question and on Trey Stout's and Carl Meyer's responses I made the following snippet:
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

4 comments:

  1. Interesting.. At first sight it's a pretty simple, small snippet, and yet I did learn more than two things from it!

    10x

    ReplyDelete
  2. FWIW, there's a a function for this in twisted:
    http://twistedmatrix.com/documents/current/api/twisted.python.procutils.html#which

    ReplyDelete
  3. Thanks Aviv, I wasn't aware. I'm happy to see the implementation is similar to mine, which I take as a comment :)

    ReplyDelete