On Mon, 29 Jun 2009 13:53:30 -0500, Tim Pinkawa wrote:

>>  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.

FWIW, "which" doesn't recognise built-ins either; the "type" built-in
does.

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

There are a couple of problems with this:

1. "which" only considers executable files, and the default behaviour is
to only display the first matching file. Also, I'm assuming that the OP
wants a function which returns the path rather than printing it.

2. os.listdir() requires read permission (enumerate permission) on each
directory. The standard "which" utility stat()s each possible candidate,
so it only requires execute permission (lookup permission) on the
directories. A secondary issue is performance; enumerating a directory to
check for a specific entry can be much slower than stat()ing the specific
entry. IOW:

def which(file):
    for path in os.environ["PATH"].split(os.pathsep):
        if os.access(os.path.join(path, file), os.X_OK):
            return "%s/%s" % (path, file)

But for Windows, you also need to use PATHEXT, e.g.:

    for dir in os.environ["PATH"].split(os.pathsep):
        for ext in os.environ["PATHEXT"].split(os.pathsep):
             full = os.path.join(dir, "%s.%s" % (file, ext))
             if os.access(full, os.X_OK):
                 return full

Disclaimer: I don't know how accurate os.access(..., os.X_OK) is on
Windows; OTOH, it's probably as good as you'll get.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to