python library call equivalent to `which' command

Nobody nobody at
Mon Jun 29 16:26:29 EDT 2009

On Mon, 29 Jun 2009 14:31:25 -0500, Tim Pinkawa wrote:

>> "if file in os.list()" is slow and not correct. You have to check if the
>> file is either a real file or a symlink to a file and not a directory or
>> special. Then you have to verify that the file has the executable bit, too.
> I realize four lines of Python does not replicate the functionality of
> which exactly. It was intended to give the original poster something
> to start with.
> I am curious about it being slow, though. Is there a faster way to get
> the contents of a directory than os.listdir()


> or is there a faster way to see if an element is in a list other than
> "x in y"? 


However, there is a faster (and more correct) way to test for file
existence than enumerating the directory then checking whether the file is
in the resulting list, namely to stat() the file. I.e. os.path.exists()
or os.access(); the latter will allow you to check for execute permission
at the same time.

On some systems, the speed difference may be very significant. If
readdir() is a system call, os.listdir() will make one system call (two
context switches) per directory entry, while os.access() will make one
system call in total.

[Linux has the (non-standard) getdents() system call, which returns
multiple directory entries per call. The readdir() library
function uses getdents(), as it is much more efficient than using the
readdir() system call.]

More information about the Python-list mailing list