7

How do I search for an executable file using python in linux? The executable files have no extensions and are in a folder together with files that have different extensions. Thanks

EDIT: What I mean by search is to get the filenames of all the executable files and store them in a list or tuple. Thanks

mikeP
  • 801
  • 2
  • 11
  • 20

3 Answers3

7

To do it in Python:

import os
import stat

executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH
for filename in os.listdir('.'):
    if os.path.isfile(filename):
        st = os.stat(filename)
        mode = st.st_mode
        if mode & executable:
            print(filename,oct(mode))
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    2 remarks, `S_IEXEC` is a [synonym](https://docs.python.org/3.6/library/stat.html#stat.S_IEXEC) of `S_IXUSR`. Since the OP used `IXGRP` and `IXOTH` I'd advocate using `IXUSR` for consistency. And second, this search for files executable by everyone. Meaning, it could not be executable by yourself, so don't trust on this to believe you can execute it (as I've just seen it done in a colleague's code, code which sent me there ^^) – Vser Nov 22 '19 at 17:25
2

Function os.access() is in some cases better than os.stat(), because it check whether the file can be executed by you, according to file owner, group and permissions.

import os

for filename in os.listdir('.'):
    if os.path.isfile(filename) and os.access(filename, os.X_OK):
        print(filename)
Messa
  • 24,321
  • 6
  • 68
  • 92
2

If by search you mean to list all the executable files in a directory than use the command from this SuperUser Link.You can use Subprocess module to execute the commands from python code.

import shlex   
executables = shlex.split(r'find /dir/mydir -executable -type f')
output_process = subprocess.Popen(executables,shell=True,stdout=subprocess.PIPE)
Community
  • 1
  • 1
RanRag
  • 48,359
  • 38
  • 114
  • 167