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
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 .
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.
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.
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))
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With