Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search for an executable file using python in linux?

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

like image 725
mikeP Avatar asked Jan 21 '12 23:01

mikeP


People also ask

How do I find the location of an executable in Linux?

Linux comes with the which command to locate a given executable. Executables are commands you type into your terminal, like git , node , touch , or vim .

How do I find a specific file in Python?

Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.

How do I check if a file is executable in Linux terminal?

In Linux systems, we should look up the x bit of the file. We found, reading the x bits, that the file a. out may be executed by its owner, joe, the members of the joe group, and others. So, the test's x flag proves if the file exists and is executable.


3 Answers

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))
like image 64
unutbu Avatar answered Oct 12 '22 23:10

unutbu


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)
like image 43
RanRag Avatar answered Oct 12 '22 23:10

RanRag


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)
like image 31
Messa Avatar answered Oct 12 '22 23:10

Messa