python library call equivalent to `which' command

Tim Pinkawa timpinkawa at gmail.com
Mon Jun 29 14:53:30 EDT 2009


On Mon, Jun 29, 2009 at 12:54 PM, destroooooy<destroooooy at gmail.com> wrote:
> Hi,
>  I'm looking for a Python library function that provides the same
> functionality as the `which' command--namely, search the $PATH
> variable for a given string and see if it exists anywhere within. I
> currently examine the output from `which' itself, but I would like
> something more portable. I looked through the `os' and `os.path'
> modules but I didn't find anything.

This works on POSIX systems. Windows uses semicolons to separate paths
rather than colons so that would need to be taken into account when
running on Windows. This also doesn't recognize shell built-ins, only
real binaries.

import os

def which(file):
    for path in os.environ["PATH"].split(":"):
            if file in os.listdir(path):
                    print "%s/%s" % (path, file)

>>> which("ls")
/bin/ls



More information about the Python-list mailing list