How to search for executable file using python on Linux?

How to search for executable file using python on Linux? Executable files do not have extensions and are located in a folder along with files with different extensions. Thanks

EDIT: what I mean by search is to get the file names of all executable files and save them in a list or tuple. Thanks

+6
source share
3 answers

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)) 
+6
source

If by request you want to list all the executables in the directory, than use the command from this SuperUser link . You can use the subprocess module to execute 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) 
+1
source

The os.access () function is in some cases better than os.stat () , because it checks whether the file can be executed by you, according to the owner of the file, group and rights.

 import os for filename in os.listdir('.'): if os.path.isfile(filename) and os.access(filename, os.X_OK): print(filename) 
+1
source

Source: https://habr.com/ru/post/906569/


All Articles