pythonlinuxpython-os

How to check if a file is an executable in Python when os.acess() doesn't work?


I'm trying to get all the executables within a folder containing a bunch of libraries using a python script. To do so I set up the following:

for libs in os.listdir(parent_dir):
    path = parent_dir + libs + "/"
    for root,dirs,files in os.walk(path):
         for file in files:
              if os.access(file,os.X_OK):
                   #task to be done
                   print(file) #for debugging

However, it didn't work. I checked the permissions of the executable files manually and while the file type is set to "exeutable", permissions are "read and write", and I can't figure out how to fix this. Changing the permission of the target file is also not an option since there's a lot of files, and the number of files is also variable depending on how many libraries I'm working with. I am also using Ubuntu Linux if that helps.


Solution

  • It's returning False because it isn't finding the files. Either change to the directory of each individual file or use absolute paths.

    for libs in os.listdir(parent_dir):
        path = parent_dir + libs + "/"
        for root, dirs, files in os.walk(path):
             for file in files:
                  file = os.path.join(root, file) # get absolute path
                  if os.access(file, os.X_OK):
                       print(file)
    

    As noted in the comments, it is better to use absolute paths than doing the following. But it should work as well.

    for libs in os.listdir(parent_dir):
        path = parent_dir + libs + "/"
        for root, dirs, files in os.walk(path):
             os.chdir(root) # change to directory of files
             for file in files:
                  if os.access(file, os.X_OK):
                       print(os.path.join(root, file)) # note that you still should use an absolute path for accuracy