python library call equivalent to `which' command

Scott David Daniels Scott.Daniels at Acm.Org
Mon Jun 29 23:26:09 CEST 2009


Robert Kern wrote:
> On 2009-06-29 14:31, Tim Pinkawa wrote:
>> On Mon, Jun 29, 2009 at 2:17 PM, Christian Heimes<lists at cheimes.de>  
>> 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"? 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.
> 
> Just check if os.path.exists(os.path.join(path, filename)).
> 
But on windows, checking for a list of possible extensions, it may well
be faster to operate on the listdir output.  I made my which-equivalent
function a generator, so I could choose to stop at the first entry or
continue at the invoker's pleasure (good for both Trojan-discovery and
"forgot to delete the .pyc" operations).

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list