'distutils.spawn.find_executable and shutil.which can not find the file

I need to find a file contained in our software with python3.

The problem is, an executable file which can be found in the bash environment with find command, can not be found in zsh environment with python3. This file is neither in the $PATH nor os.environ["PATH"]. I could only find it when I provide its absolute path as a parameter to shutil & which.

However, since the absolute path depends on the installation path of the software, it is different for each person. Therefore, I want to ask for a general method, which can find this excitable file with only its name provided. Thanks a lot!



Solution 1:[1]

The shutil.which function uses $PATH variable to find executables. It works exactly as the bash which or command -v.

The find command uses a directory as input and searches recursively inside this directory.

To perform your search, you have to either append the directory in which your executable is in to your current PATH and then use shutil.which to locate it

import os
import shutil
os.environ['PATH'] += ':/exe/location'
exec_location = shutil.which('myexe')

or use a function that works similarly to the find command :

from pathlib import Path
from typing import Optional

def find(name: str, location: Path) -> Optional[Path]:
    files = [ f for f in location.rglob('*') if f.is_file()]
    for f in files:
        if f.name == name:
            return f.resolve()
    
    return None

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sonik