python library call equivalent to `which' command

Christian Heimes lists at cheimes.de
Mon Jun 29 15:53:42 EDT 2009


Tim Pinkawa wrote:
> 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.

Agreed!

> 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"? I believe
> 'which' will terminate once it finds any match, which mine does not,
> but that can be fixed by adding a break after the print.

You don't need to get the entire directory content to see if a file
exists. The stat() syscall is much faster because it requires fewer disk
reads. On modern file systems stat() is a O(1) operation while "file" in
listdir() is a O(n) operation.

By the way you need the result of os.stat anyway to see if the file has
the executable bits set.

Christian



More information about the Python-list mailing list