Need Simple Way To Determine If File Is Executable

Tim Golden tjgolden at gmail.com
Fri Dec 15 04:04:52 EST 2006


[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




More information about the Python-list mailing list