Tell if a file is executable

Introduction

Given a filename, tell whether it's executable. The trouble is that "executable" is not a simple concept. Roughly, files fall into three categories.

  1. If you double-click them they run themselves ("executables")
  2. If you double-click them they run something else which loads them ("documents")
  3. If you double-click them they don't run

The FindExecutable API call is the easiest way to distinguish these. It returns a string indicating what would be run if you were to have double-clicked on the file. If that is the same as the filename you first thought of, it's an executable. If it returns something else, it's a document. If it raises an error, it's neither.

NB The filename returned is a short filename, so you need to convert it before comparing to the original.

import sys
import pywintypes
import win32api

filename = sys.executable.lower ()

try:
  print "Looking at", filename
  r, executable = win32api.FindExecutable (filename)
  executable = win32api.GetLongPathName (executable).lower ()
except pywintypes.error:
  print "Neither executable nor document"
else:
  if executable == filename:
    print "executable"
  else:
    print "document"