Find executable in current dir, system path or given ProgramFiles subdir
422368
def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
    """"""
    for fn in [filename, filename+".exe"]:
        try:
            if installsubdir is None:
                path = _where(fn)
            else:
                path = _where(fn, dirs=[os.path.join(os.environ[env], installsubdir)])
        except IOError:
            path = filename
        else:
            break        
    return path
509411
def getPathOfExecutable(executable):
    
    exe_paths = os.environ['PATH'].split(':')
    for exe_path in exe_paths:
        exe_file = os.path.join(exe_path, executable)
        if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
            return exe_file
    return None
721779
def which(fname):
    """"""
    if "PATH" not in os.environ or not os.environ["PATH"]:
        path = os.defpath
    else:
        path = os.environ["PATH"]

    for p in [fname] + [os.path.join(x, fname) for x in path.split(os.pathsep)]:
        p = os.path.abspath(p)
        if os.access(p, os.X_OK) and not os.path.isdir(p):
            return p

    p = sp.Popen("locate %s" % fname, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
    (stdout, stderr) = p.communicate()
    if not stderr:
        for p in stdout.decode().split("\n"):
            if (os.path.basename(p) == fname) and (
                os.access(p, os.X_OK)) and (
                not os.path.isdir(p)):
                return p
111064
def find_executable(executable):
    '''
    
    '''
    logger = logging.getLogger(__name__)
    logger.debug("Checking executable '%s'...", executable)
    executable_path = _find_executable(executable)
    found = executable_path is not None
    if found:
        logger.debug("Executable '%s' found: '%s'", executable, executable_path)
    else:
        logger.debug("Executable '%s' not found", executable)
    return executable_path
688771
def find_program(basename):
    
    names = [basename]
    if os.name == 'nt':
        # Windows platforms
        extensions = ('.exe', '.bat', '.cmd')
        if not basename.endswith(extensions):
            names = [basename+ext for ext in extensions]+[basename]
    for name in names:
        path = is_program_installed(name)
        if path:
            return path
922128
def which(program):
    "  "

    head, _ = op.split(program)

    if head:
        if is_exe(program):
            return program
    else:
        for path in environ["PATH"].split(pathsep):
            exe_file = op.join(path, program)
            if is_exe(exe_file):
                return exe_file
    return None
734079
def find_program (program):
    """"""
    if os.name == 'nt':
        # Add some well-known archiver programs to the search path
        path = os.environ['PATH']
        path = append_to_path(path, get_nt_7z_dir())
        path = append_to_path(path, get_nt_mac_dir())
        path = append_to_path(path, get_nt_winrar_dir())
    else:
        # use default path
        path = None
    return which(program, path=path)
448747
def which(cmd, safe=False):
    """"""
    from autopaths.file_path import FilePath
    def is_executable(path):
        return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
    path, name = os.path.split(cmd)
    if path:
        if is_executable(cmd): return FilePath(cmd)
    else:
        for path in os.environ['PATH'].split(os.pathsep):
            candidate = os.path.join(path, cmd)
            if is_executable(candidate): return FilePath(candidate)
    if not safe: raise Exception('which failed to locate a proper command path "%s"' % cmd)
1095536
def find_by_ext(dirname, ext):
    """"""
    # Get all fasta-files
    try: 
        files = os.listdir(dirname) 
    except OSError: 
        if os.path.exists(dirname): 
            cmd = "find {0} -maxdepth 1 -name \"*\"".format(dirname) 
            p = sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE) 
            stdout, _stderr = p.communicate() 
            files = [os.path.basename(fname) for fname in stdout.decode().splitlines()] 
        else: 
            raise 
     
    retfiles = [os.path.join(dirname, fname) for fname in files if 
                    os.path.splitext(fname)[-1] in ext] 
 
    return retfiles
725128
def find_runner(program):
    
    if os.path.isfile(program) and not os.access(program, os.X_OK):
        # program is a path to a non-executable file
        try:
            opened = open(program)
        except PermissionError:
            return None
        first_line = opened.readline().strip()
        if first_line.startswith('#!'):
            return shlex.split(first_line[2:])
        if program.endswith('.py'):
            return [sys.executable]
    return None
589891
def find_executables
      return enum_for(:find_executables) unless block_given?

      exts = (ENV.has_key?('PATHEXT') ? ENV.fetch('PATHEXT').split(';') : []) << ''
      paths = @path.sub('*', ENV['PATH']).split(File::PATH_SEPARATOR)
      raise ArgumentError.new('No PATH to search!') if paths.empty?
      cmds = strict? ? @executables.first(1) : @executables

      lookup_cache = Set.new
      cmds.product(paths, exts).map do |cmd, path, ext|
        exe = File.absolute_path?(cmd) ? cmd : File.expand_path("#{cmd}#{ext}", path)

        next unless lookup_cache.add?(exe) # don't yield the same exe path 2x
        next unless File.executable?(exe)
        next if File.directory?(exe)

        yield exe
      end
    end
987343
def which(program):
    
    path_ext = [""]
    ext_list = None

    if sys.platform == "win32":
        ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")]

    def is_exe(fpath):
        exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
        # search for executable under windows
        if not exe:
            if ext_list:
                for ext in ext_list:
                    exe_path = f"{fpath}{ext}"
                    if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK):
                        path_ext[0] = ext
                        return True
                return False
        return exe

    fpath, fname = os.path.split(program)

    if fpath:
        if is_exe(program):
            return f"{program}{path_ext[0]}"
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return f"{exe_file}{path_ext[0]}"
    return None
645859
def which(filename, env=None):
    ''''''

    # Special case where filename contains an explicit path.
    if os.path.dirname(filename) != '' and is_executable_file(filename):
        return filename
    if env is None:
        env = os.environ
    p = env.get('PATH')
    if not p:
        p = os.defpath
    pathlist = p.split(os.pathsep)
    for path in pathlist:
        ff = os.path.join(path, filename)
        if is_executable_file(ff):
            return ff
    return None
75710
def find_file_dir_up(filename, path=None, n=None):
    '''
    '''
    if path is None:
        path = os.getcwd()
    i = 0
    while True:
        current_path = path
        for _ in range(i):
            current_path = os.path.split(current_path)[0]
        if os.path.isfile(os.path.join(current_path, filename)):  # found file and return
            return os.path.join(current_path, filename)
        elif os.path.dirname(current_path) == current_path:  # root of filesystem
            return
        elif n is not None and i == n:
            return
        else:  # file not found
            i += 1
            continue
771332
def _search_for_executable(self, executable):
        
        if os.path.isfile(executable):
            return os.path.abspath(executable)
        else:
            envpath = os.getenv('PATH')
            if envpath is None:
                return
            for path in envpath.split(os.pathsep):
                exe = os.path.join(path, executable)
                if os.path.isfile(exe):
                    return os.path.abspath(exe)
1041589
def find_executable(name):
    
    for pt in os.environ.get('PATH', '').split(':'):
        candidate = os.path.join(pt, name)
        if os.path.exists(candidate):
            return candidate
484923
def which(exe=None):
    '''
    
    '''

    if not exe:
        log.error('No executable was passed to be searched by salt.utils.path.which()')
        return None

    ## define some utilities (we use closures here because our predecessor used them)
    def is_executable_common(path):
        '''
        This returns truth if posixy semantics (which python simulates on
        windows) states that this is executable.
        '''
        return os.path.isfile(path) and os.access(path, os.X_OK)

    def resolve(path):
        '''
        This will take a path and recursively follow the link until we get to a
        real file.
        '''
        while os.path.islink(path):
            res = os.readlink(path)

            # if the link points to a relative target, then convert it to an
            # absolute path relative to the original path
            if not os.path.isabs(res):
                directory, _ = os.path.split(path)
                res = join(directory, res)
            path = res
        return path

    # windows-only
    def has_executable_ext(path, ext_membership):
        '''
        Extract the extension from the specified path, lowercase it so we
        can be insensitive, and then check it against the available exts.
        '''
        p, ext = os.path.splitext(path)
        return ext.lower() in ext_membership

    ## prepare related variables from the environment
    res = salt.utils.stringutils.to_unicode(os.environ.get('PATH', ''))
    system_path = res.split(os.pathsep)

    # add some reasonable defaults in case someone's PATH is busted
    if not salt.utils.platform.is_windows():
        res = set(system_path)
        extended_path = ['/sbin', '/bin', '/usr/sbin', '/usr/bin', '/usr/local/sbin', '/usr/local/bin']
        system_path.extend([p for p in extended_path if p not in res])

    ## now to define the semantics of what's considered executable on a given platform
    if salt.utils.platform.is_windows():
        # executable semantics on windows requires us to search PATHEXT
        res = salt.utils.stringutils.to_str(os.environ.get('PATHEXT', str('.EXE')))

        # generate two variables, one of them for O(n) searches (but ordered)
        # and another for O(1) searches. the previous guy was trying to use
        # memoization with a function that has no arguments, this provides
        # the exact same benefit
        pathext = res.split(os.pathsep)
        res = {ext.lower() for ext in pathext}

        # check if our caller already specified a valid extension as then we don't need to match it
        _, ext = os.path.splitext(exe)
        if ext.lower() in res:
            pathext = ['']

            is_executable = is_executable_common

        # The specified extension isn't valid, so we just assume it's part of the
        # filename and proceed to walk the pathext list
        else:
            is_executable = lambda path, membership=res: is_executable_common(path) and has_executable_ext(path, membership)

    else:
        # in posix, there's no such thing as file extensions..only zuul
        pathext = ['']

        # executable semantics are pretty simple on reasonable platforms...
        is_executable = is_executable_common

    ## search for the executable

    # check to see if the full path was specified as then we don't need
    # to actually walk the system_path for any reason
    if is_executable(exe):
        return exe

    # now to search through our system_path
    for path in system_path:
        p = join(path, exe)

        # iterate through all extensions to see which one is executable
        for ext in pathext:
            pext = p + ext
            rp = resolve(pext)
            if is_executable(rp):
                return p + ext
            continue
        continue

    ## if something was executable, we should've found it already...
    log.trace(
        '\'%s\' could not be found in the following search path: \'%s\'',
        exe, system_path
    )
    return None