How can I find the path for an executable?

I know this is an older question, but if you happen to be using Python 3.3+ you can use shutil.which(cmd). You can find the documentation here. It has the advantage of being in the standard library.

An example would be like so:

>>> import shutil
>>> shutil.which("bash")
'/usr/bin/bash'

There's not a command to do that, but you can iterate over environ["PATH"] and look if the file exists, which is actually what which does.

import os

def which(file):
    for path in os.environ["PATH"].split(os.pathsep):
        if os.path.exists(os.path.join(path, file)):
                return os.path.join(path, file)

    return None

Good luck!


There is distutils.spawn.find_executable().

Tags:

Python