Locate the pip binary, either from `bin_env` as a virtualenv, as the
    executable itself, or from searching conventional filesystem locations
332248
def _get_pip_bin(bin_env):
    '''
    
    '''
    if not bin_env:
        logger.debug('pip: Using pip from currently-running Python')
        return [os.path.normpath(sys.executable), '-m', 'pip']

    python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'

    def _search_paths(*basedirs):
        ret = []
        for path in basedirs:
            ret.extend([
                os.path.join(path, python_bin),
                os.path.join(path, 'bin', python_bin),
                os.path.join(path, 'Scripts', python_bin)
            ])
        return ret

    # try to get python bin from virtualenv (i.e. bin_env)
    if os.path.isdir(bin_env):
        for bin_path in _search_paths(bin_env):
            if os.path.isfile(bin_path):
                if os.access(bin_path, os.X_OK):
                    logger.debug('pip: Found python binary: %s', bin_path)
                    return [os.path.normpath(bin_path), '-m', 'pip']
                else:
                    logger.debug(
                        'pip: Found python binary by name but it is not '
                        'executable: %s', bin_path
                    )
        raise CommandNotFoundError(
            'Could not find a pip binary in virtualenv {0}'.format(bin_env)
        )

    # bin_env is the python or pip binary
    elif os.access(bin_env, os.X_OK):
        if os.path.isfile(bin_env):
            # If the python binary was passed, return it
            if 'python' in os.path.basename(bin_env):
                return [os.path.normpath(bin_env), '-m', 'pip']
            # We have been passed a pip binary, use the pip binary.
            return [os.path.normpath(bin_env)]

        raise CommandExecutionError(
            'Could not find a pip binary within {0}'.format(bin_env)
        )
    else:
        raise CommandNotFoundError(
            'Access denied to {0}, could not find a pip binary'.format(bin_env)
        )
892625
def checkBinary(name, bindir=None):
    
    if name == "sumo-gui":
        envName = "GUISIM_BINARY"
    else:
        envName = name.upper() + "_BINARY"
    env = os.environ
    join = os.path.join
    if envName in env and exeExists(env.get(envName)):
        return env.get(envName)
    if bindir is not None:
        binary = join(bindir, name)
        if exeExists(binary):
            return binary
    if "SUMO_HOME" in env:
        binary = join(env.get("SUMO_HOME"), "bin", name)
        if exeExists(binary):
            return binary
    binary = os.path.abspath(
        join(os.path.dirname(__file__), '..', '..', 'bin', name))
    if exeExists(binary):
        return binary
    return name
265183
def find_executable(executable, path=None):
  
  if path is None:
    path = os.environ['PATH']
  paths = path.split(os.pathsep)
  base, ext = os.path.splitext(executable)

  if (sys.platform == 'win32' or os.name == 'os2') and (ext != '.exe'):
    executable = executable + '.exe'

  if not os.path.isfile(executable):
    for p in paths:
      f = os.path.join(p, executable)
      if os.path.isfile(f):
        # the file exists, we have a shot at spawn working
        return f
    return None
  else:
    return executable
1127733
def bin_find(self):
        
        flag = []
        options = [
            "-f",
            "--find"
        ]
        additional_options = ["--case-ins"]
        for arg in self.args:
            if arg in additional_options:
                flag.append(arg)
                self.args.remove(arg)
        packages = self.args[1:]
        if len(self.args) > 1 and self.args[0] in options:
            PackageManager(packages).find(flag)
        else:
            usage("")
9703
def get_or_create_environment(self, repo: str, branch: str, git_repo: Repo, repo_path: Path) -> str:
        
        return str(self.get_or_create_venv(repo_path).resolve() / "bin" / "python")
428086
def _get_system_python_executable():
    
    # This function is required by get_package_as_folder() to work
    # inside a virtualenv, since venv creation will fail with
    # the virtualenv's local python binary.
    # (venv/virtualenv incompatibility)

    # Abort if not in virtualenv or venv:
    if not hasattr(sys, "real_prefix") and (
            not hasattr(sys, "base_prefix") or
            os.path.normpath(sys.base_prefix) ==
            os.path.normpath(sys.prefix)):
        return sys.executable

    # Extract prefix we need to look in:
    if hasattr(sys, "real_prefix"):
        search_prefix = sys.real_prefix  # virtualenv
    else:
        search_prefix = sys.base_prefix  # venv

    def python_binary_from_folder(path):
        def binary_is_usable(python_bin):
            try:
                filenotfounderror = FileNotFoundError
            except NameError:  # Python 2
                filenotfounderror = OSError
            try:
                subprocess.check_output([
                    os.path.join(path, python_bin), "--version"
                ], stderr=subprocess.STDOUT)
                return True
            except (subprocess.CalledProcessError, filenotfounderror):
                return False

        python_name = "python" + sys.version
        while (not binary_is_usable(python_name) and
               python_name.find(".") > 0):
            # Try less specific binary name:
            python_name = python_name.rpartition(".")[0]
        if binary_is_usable(python_name):
            return os.path.join(path, python_name)
        return None

    # Return from sys.real_prefix if present:
    result = python_binary_from_folder(search_prefix)
    if result is not None:
        return result

    # Check out all paths in $PATH:
    bad_candidates = []
    good_candidates = []
    ever_had_nonvenv_path = False
    for p in os.environ.get("PATH", "").split(":"):
        # Skip if not possibly the real system python:
        if not os.path.normpath(p).startswith(
                os.path.normpath(search_prefix)
                ):
            continue

        # First folders might be virtualenv/venv we want to avoid:
        if not ever_had_nonvenv_path:
            sep = os.path.sep
            if ("system32" not in p.lower() and "usr" not in p) or \
                    {"home", ".tox"}.intersection(set(p.split(sep))) or \
                    "users" in p.lower():
                # Doesn't look like bog-standard system path.
                if (p.endswith(os.path.sep + "bin") or
                        p.endswith(os.path.sep + "bin" + os.path.sep)):
                    # Also ends in "bin" -> likely virtualenv/venv.
                    # Add as unfavorable / end of candidates:
                    bad_candidates.append(p)
                    continue
            ever_had_nonvenv_path = True

        good_candidates.append(p)

    # See if we can now actually find the system python:
    for p in good_candidates + bad_candidates:
        result = python_binary_from_folder(p)
        if result is not None:
            return result

    raise RuntimeError("failed to locate system python in: " +
                       sys.real_prefix)
1145946
def make_virtualenv(env):
    
    if find_executable("virtualenv") is not None:
        cmd = ["virtualenv"] + [env]
        subprocess.check_call(cmd)
    else:
        # Otherwise, download virtualenv from pypi
        path = urlretrieve(VENV_URL)[0]
        subprocess.check_call(["tar", "xzf", path])
        subprocess.check_call(
            [sys.executable, "virtualenv-%s/virtualenv.py" % VENV_VERSION, env]
        )
        os.unlink(path)
        shutil.rmtree("virtualenv-%s" % VENV_VERSION)
94209
def find_include_path():
    
    incl_from_env = os.environ.get('MXNET_INCLUDE_PATH')
    if incl_from_env:
        if os.path.isdir(incl_from_env):
            if not os.path.isabs(incl_from_env):
                logging.warning("MXNET_INCLUDE_PATH should be an absolute path, instead of: %s",
                                incl_from_env)
            else:
                return incl_from_env
        else:
            logging.warning("MXNET_INCLUDE_PATH '%s' doesn't exist", incl_from_env)

    curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
    # include path in pip package
    pip_incl_path = os.path.join(curr_path, 'include/')
    if os.path.isdir(pip_incl_path):
        return pip_incl_path
    else:
        # include path if build from source
        src_incl_path = os.path.join(curr_path, '../../include/')
        if os.path.isdir(src_incl_path):
            return src_incl_path
        else:
            raise RuntimeError('Cannot find the MXNet include path in either ' + pip_incl_path +
                               ' or ' + src_incl_path + '\n')
428908
def _get_env_activate(bin_env):
    '''
    
    '''
    if not bin_env:
        raise CommandNotFoundError('Could not find a `activate` binary')

    if os.path.isdir(bin_env):
        if salt.utils.platform.is_windows():
            activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
        else:
            activate_bin = os.path.join(bin_env, 'bin', 'activate')
        if os.path.isfile(activate_bin):
            return activate_bin
    raise CommandNotFoundError('Could not find a `activate` binary')
565957
def _python_rpath(self):
        """"""
        # Windows virtualenv installation installs pip to the [Ss]cripts
        # folder. Here's a simple check to support:
        if sys.platform == 'win32':
            return os.path.join('Scripts', 'python.exe')
        return os.path.join('bin', 'python')
420576
def is_virtual_environment(path):
    
    if not path.is_dir():
        return False
    for bindir_name in ('bin', 'Scripts'):
        for python in path.joinpath(bindir_name).glob('python*'):
            try:
                exeness = python.is_file() and os.access(str(python), os.X_OK)
            except OSError:
                exeness = False
            if exeness:
                return True
    return False
534698
def _brute_force_install_pip(self):
        """"""
        if os.path.exists(self.pip_installer_fname):
            logger.debug("Using pip installer from %r", self.pip_installer_fname)
        else:
            logger.debug(
                "Installer for pip not found in %r, downloading it", self.pip_installer_fname)
            self._download_pip_installer()

        logger.debug("Installing PIP manually in the virtualenv")
        python_exe = os.path.join(self.env_bin_path, "python")
        helpers.logged_exec([python_exe, self.pip_installer_fname, '-I'])
        self.pip_installed = True
148527
def _find_executables(name):
    
    exe_name = name + '.exe' * sys.platform.startswith('win')
    env_path = os.environ.get(name.upper()+ '_PATH', '')
    
    possible_locations = []
    def add(*dirs):
        for d in dirs:
            if d and d not in possible_locations and os.path.isdir(d):
                possible_locations.append(d)
    
    # Get list of possible locations
    add(env_path)
    try:
        add(os.path.dirname(os.path.abspath(__file__)))
    except NameError:  # __file__ may not exist
        pass
    add(os.path.dirname(sys.executable))
    add(os.path.expanduser('~'))
    
    # Platform specific possible locations
    if sys.platform.startswith('win'):
        add('c:\\program files', os.environ.get('PROGRAMFILES'),
            'c:\\program files (x86)', os.environ.get('PROGRAMFILES(x86)'))
    else:
        possible_locations.extend(['/usr/bin','/usr/local/bin','/opt/local/bin'])
    
    def do_check_version(exe):
        try:
            return subprocess.check_output([exe, '--version']).decode().strip()
        except Exception:
            # print('not a good exe', exe)
            return False
    
    # If env path is the exe itself ...
    if os.path.isfile(env_path):
        ver = do_check_version(env_path)
        if ver:
            return env_path, ver
    
    # First try to find obvious locations
    for d in possible_locations:
        for exe in [os.path.join(d, exe_name), os.path.join(d, name, exe_name)]:
            if os.path.isfile(exe):
                ver = do_check_version(exe)
                if ver:
                    return exe, ver
    
    # Maybe the exe is on the PATH
    ver = do_check_version(exe_name)
    if ver:
        return exe_name, ver
        
    # Try harder
    for d in possible_locations:
        for sub in reversed(sorted(os.listdir(d))):
            if sub.startswith(name):
                exe = os.path.join(d, sub, exe_name)
                if os.path.isfile(exe):
                    ver = do_check_version(exe)
                    if ver:
                        return exe, ver
    
    return None, None
430398
def get_current_venv():
        
        if 'VIRTUAL_ENV' in os.environ:
            venv = os.environ['VIRTUAL_ENV']
        elif os.path.exists('.python-version'):  # pragma: no cover
            try:
                subprocess.check_output(['pyenv', 'help'], stderr=subprocess.STDOUT)
            except OSError:
                print("This directory seems to have pyenv's local venv, "
                      "but pyenv executable was not found.")
            with open('.python-version', 'r') as f:
                # minor fix in how .python-version is read
                # Related: https://github.com/Miserlou/Zappa/issues/921
                env_name = f.readline().strip()
            bin_path = subprocess.check_output(['pyenv', 'which', 'python']).decode('utf-8')
            venv = bin_path[:bin_path.rfind(env_name)] + env_name
        else:  # pragma: no cover
            return None
        return venv
688279
def get_program_python(cmd):
    
    full_cmd = os.path.realpath(which(cmd))
    cmd_python = os.path.join(os.path.dirname(full_cmd), "python")
    env_python = None
    if "envs" in cmd_python:
        parts = cmd_python.split(os.sep)
        env_python = os.path.join(os.sep.join(parts[:parts.index("envs") + 2]), "bin", "python")
    if os.path.exists(cmd_python):
        return cmd_python
    elif env_python and os.path.exists(env_python):
        return env_python
    else:
        return os.path.realpath(sys.executable)
1277354
def get_bin(self, arch='x86'):
        
        bin_dir = os.path.join(self.vc_dir, 'bin')
        if arch == 'x86':
            arch = ''
        cl_path = os.path.join(bin_dir, arch, 'cl.exe')
        link_path = os.path.join(bin_dir, arch, 'link.exe')
        ml_name = 'ml.exe'
        if arch in ['x86_amd64', 'amd64']:
            ml_name = 'ml64.exe'
        ml_path = os.path.join(bin_dir, arch, ml_name)
        if os.path.isfile(cl_path) \
           and os.path.isfile(link_path) \
           and os.path.isfile(ml_path):
            logging.info(_('using cl.exe: %s'), cl_path)
            logging.info(_('using link.exe: %s'), link_path)
            logging.info(_('using %s: %s'), ml_name, ml_path)
            run_cl = partial(run_program, cl_path)
            run_link = partial(run_program, link_path)
            run_ml = partial(run_program, ml_path)
            return self.Bin(run_cl, run_link, run_ml)
        logging.debug(_('cl.exe not found: %s'), cl_path)
        logging.debug(_('link.exe not found: %s'), link_path)
        logging.debug(_('%s not found: %s'), ml_name, ml_path)
        return self.Bin(None, None, None)
567065
def dyld_find(name, executable_path=None, env=None):
    
    name = _ensure_utf8(name)
    executable_path = _ensure_utf8(executable_path)
    for path in dyld_image_suffix_search(chain(
                dyld_override_search(name, env),
                dyld_executable_path_search(name, executable_path),
                dyld_default_search(name, env),
            ), env):
        if os.path.isfile(path):
            return path
    raise ValueError, "dylib %s could not be found" % (name,)