>>> which("sh") is not None
    True

    >>> which("bogus-executable-that-doesn't-exist") is None
    True
180605
def which(file):
    
    for path in os.environ["PATH"].split(os.pathsep):
        if os.path.exists(os.path.join(path, file)):
                return os.path.join(path, file)
    return None
908195
function exists(cmd) {
  return run(`which ${cmd}`).then(stdout => {
    if (stdout.trim().length === 0) {
      // maybe an empty command was supplied?
      // are we running on Windows??
      return Promise.reject(new Error("No output"));
    }

    const rNotFound = /^[\w\-]+ not found/g;

    if (rNotFound.test(cmd)) {
      return Promise.resolve(false);
    }

    return Promise.resolve(true);
  });
}
449463
def which(program):
    

    def is_exe(fpath):
        if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
            return True
        return False

    for path in os.environ["PATH"].split(os.pathsep):
        for ext in os.getenv("PATHEXT", "").split(os.pathsep):
            fname = program + ext.lower()
            abspath = os.path.join(path.strip('"'), fname)

            if is_exe(abspath):
                return abspath

    return None
1195924
function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') {
        cb = mask;
        mask = 0777;
    }

    filesystem.mkdir(path, mask, function(err) {
        if (err) {
            if (err.code == 'EEXIST') cb(null);
            else cb(err);
        } else cb(null);
    });
}
474759
def find_binary_of_command(candidates):
    
    from distutils.spawn import find_executable
    for c in candidates:
        binary_path = find_executable(c)
        if c and binary_path:
            return c, binary_path
    raise RuntimeError('No binary located for candidates: {}'.format(
        candidates))
336175
def which(exe):
    '''
    
    '''
    def wrapper(function):
        def wrapped(*args, **kwargs):
            if salt.utils.path.which(exe) is None:
                raise CommandNotFoundError(
                    'The \'{0}\' binary was not found in $PATH.'.format(exe)
                )
            return function(*args, **kwargs)
        return identical_signature_wrapper(function, wrapped)
    return wrapper
21445
def is_tomodir(subdirectories):
    
    required = (
        'exe',
        'config',
        'rho',
        'mod',
        'inv'
    )
    is_tomodir = True
    for subdir in required:
        if subdir not in subdirectories:
            is_tomodir = False
    return is_tomodir
413560
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
    

    if os.path.dirname(cmd):
        if os.path.isfile(cmd) and os.access(cmd, mode):
            return cmd

    if path is None:
        path = os.environ.get('PATH', defpath)
    if not path:
        return None

    paths = path.split(pathsep)

    if sys.platform == 'win32':
        # oh boy
        if curdir not in paths:
            paths = [curdir] + paths

        # also need to check the fileexts...
        pathext = os.environ.get('PATHEXT', '').split(pathsep)

        if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
            files = [cmd]
        else:
            files = [cmd + ext for ext in pathext]
    else:
        # sanity
        files = [cmd]

    seen = set()
    for p in paths:
        normpath = normcase(p)
        if normpath in seen:
            continue
        seen.add(normpath)
        for f in files:
            fn = os.path.join(p, f)
            if os.path.isfile(fn) and os.access(fn, mode):
                return fn

    return None
517947
def check_exists(name, path):
    '''
    
    '''
    cmd = [_get_cmd(), '--display', name]
    out = __salt__['cmd.run_all'](cmd, python_shell=False)

    if out['retcode'] > 0 and out['stderr'] != '':
        return False

    return any((line.startswith(path) for line in out['stdout'].splitlines()))
1098271
def check_executable(tool_name):
    """"""
    result = subprocess.call(['which', tool_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result != 0:
        message = "The executable '%s' cannot be found in your $PATH" % tool_name
        raise Exception(message)
920745
def __find_executables(path):
    
    
    success = False
    progs = {'dot': '', 'twopi': '', 'neato': '', 'circo': '', 'fdp': '', 'sfdp': ''}
    
    was_quoted = False
    path = path.strip()
    if path.startswith('"') and path.endswith('"'):
        path = path[1:-1]
        was_quoted =  True
    
    if os.path.isdir(path) : 
    
        for prg in progs.iterkeys():
    
            if progs[prg]:
                continue
               
            if os.path.exists( os.path.join(path, prg) ):
                
                if was_quoted:
                    progs[prg] = '"' + os.path.join(path, prg) + '"'
                else:
                    progs[prg] = os.path.join(path, prg)
                    
                success = True
               
            elif os.path.exists( os.path.join(path, prg + '.exe') ):

                if was_quoted:
                    progs[prg] = '"' + os.path.join(path, prg + '.exe') + '"'
                else:
                    progs[prg] = os.path.join(path, prg + '.exe')
                    
                success = True
    
    if success:
    
        return progs
        
    else:
    
        return None
67565
def which(program, add_win_suffixes=True):
    
    def is_exe(fpath):
        """Determine if program exists and is executable."""
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if add_win_suffixes and platform.system().lower() == 'windows' and not (
            fname.endswith('.exe') or fname.endswith('.cmd')):
        fnames = [fname + '.exe', fname + '.cmd']
    else:
        fnames = [fname]

    for i in fnames:
        if fpath:
            exe_file = os.path.join(fpath, i)
            if is_exe(exe_file):
                return exe_file
        else:
            for path in os.environ['PATH'].split(os.pathsep):
                exe_file = os.path.join(path, i)
                if is_exe(exe_file):
                    return exe_file

    return None
1215100
def which(filename, interactive=False, verbose=False):
    
    exe = [e.lower() for e in os.environ.get('PATHEXT', '').split(';')]
    if sys.platform != 'win32':  # pragma: nocover
        exe.append('')

    name, ext = os.path.splitext(filename)
    has_extension = bool(ext)
    if has_extension and ext.lower() not in exe:
        raise ValueError("which can only search for executable files")

    def match(filenames):
        """Returns the sorted subset of ``filenames`` that matches ``filename``.
        """
        res = set()
        for fname in filenames:
            if fname == filename:  # pragma: nocover
                res.add(fname)  # exact match
                continue
            fname_name, fname_ext = os.path.splitext(fname)
            if fname_name == name and fname_ext.lower() in exe: # pragma: nocover
                res.add(fname)
        return sorted(res)

    returnset = set()
    found = False
    for pth in get_path_directories():
        if verbose:  # pragma: nocover
            print('checking pth..')

        fnames = _listdir(pth, exe)
        if not fnames:
            continue

        for m in match(fnames):
            found_file = _normalize(os.path.join(pth, m))
            if found_file not in returnset:  # pragma: nocover
                if is_executable(found_file):
                    yield found_file
                returnset.add(found_file)
        found = True

    if not found and interactive:  # pragma: nocover
        print("Couldn't find %r anywhere on the path.." % filename)
        sys.exit(1)
920159
def require_executable(executable: str) -> None:
    
    if shutil.which(executable):
        return
    errmsg = "Missing command (must be on the PATH): " + executable
    log.critical(errmsg)
    raise FileNotFoundError(errmsg)
183834
def which(self, fname):
        """"""
        for pe in os.environ['PATH'].split(os.pathsep):
            checkname = os.path.join(pe, fname)
            if os.access(checkname, os.X_OK) and not os.path.isdir(checkname):
                return checkname
        return None
804452
def which(cmd):
    
    def is_exe(fp):
        return os.path.isfile(fp) and os.access(fp, os.X_OK)

    fpath, fname = os.path.split(cmd)
    if fpath:
        if is_exe(cmd):
            return cmd
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, cmd)
            if is_exe(exe_file):
                return exe_file
    return None
410859
def which(command)
      ENV['PATH'].split(File::PATH_SEPARATOR).map {|e| File.join(e, command) }.find {|e| File.exists?(e) }
    end