Need Simple Way To Determine If File Is Executable

Tim Daneliuk tundra at tundraware.com
Fri Dec 15 12:04:29 EST 2006


Tim Golden wrote:
> [Tim Daneliuk]
>> I have a program wherein I want one behavior when a file is
>> set as executable and a different behavior if it is not.  Is
>> there a simple way to determine whether a given named file is
>> executable that does not resort to all the lowlevel ugliness
>> of os.stat() AND that is portable across Win32 and *nix?
> 
> I'm fairly certain the answer is no. What follows is a
> relatively low-level and certainly not portable discussion.
> 
> The last couple of times this question came up on the list
> I looked into the implementation and experimented a bit
> but in short I would say that os.stat / os.access were
> near enough useless for determining executablility under
> Windows. That's not down to Python as such; it's simply
> passing back what the crt offers.
> 
> Of course that raises the slightly wider issue of: should
> the Python libs do more than simply call the underlying
> crt especially when that's known to give, perhaps misleading
> results? But I'm in no position to answer that.
> 
> I suggest that for Windows, you either use the PATHEXT
> env var and determine whether a given file ends with
> one of its components. Or -- and this depends on your
> definition of executable under Windows -- use the
> FindExecutable win32 API call (exposed in the win32api
> module of pywin32 and available via ctypes) which will
> return the "executable" for anything which has an
> association defined. So the "executable" for a Word
> doc is the winword.exe program. The "executable" for
> an .exe is itself.
> 
> TJG
> 

This seems to work, at least approximately:

   os.stat(selected)[ST_MODE] & (S_IXUSR|S_IXGRP|S_IXOTH

It probably does not catch every single instance of something
that could be considered "executable" because this is a sort
of fluid thing in Windows (as you point out).

-- 
----------------------------------------------------------------------------
Tim Daneliuk     tundra at tundraware.com
PGP Key:         http://www.tundraware.com/PGP/



More information about the Python-list mailing list