Returns the path the system-wide python binary.
        (In case we're running in a virtualenv or venv)
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)
629658
def get_stdlib_path():
    
    if sys.version_info >= (2, 7):
        import sysconfig
        return sysconfig.get_paths()['stdlib']
    else:
        return os.path.join(sys.prefix, 'lib')
990651
def local_path_export(at_start=True, env_cmd=None):
    
    paths = [get_bcbio_bin()]
    if env_cmd:
        env_path = os.path.dirname(get_program_python(env_cmd))
        if env_path not in paths:
            paths.insert(0, env_path)
    if at_start:
        return "export PATH=%s:\"$PATH\" && " % (":".join(paths))
    else:
        return "export PATH=\"$PATH\":%s && " % (":".join(paths))
639047
def which_bin(exes):
    '''
    
    '''
    def wrapper(function):
        def wrapped(*args, **kwargs):
            if salt.utils.path.which_bin(exes) is None:
                raise CommandNotFoundError(
                    'None of provided binaries({0}) was not found '
                    'in $PATH.'.format(
                        ['\'{0}\''.format(exe) for exe in exes]
                    )
                )
            return function(*args, **kwargs)
        return identical_signature_wrapper(function, wrapped)
    return wrapper
1022860
def binary(self):
    """"""
    lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE)
    lib_path = os.path.join(safe_mkdtemp(), lib_name)
    try:
      with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp:
        # NB: The header stripping code here must be coordinated with header insertion code in
        #     build-support/bin/native/bootstrap_code.sh
        engine_version = input_fp.readline().decode('utf-8').strip()
        repo_version = input_fp.readline().decode('utf-8').strip()
        logger.debug('using {} built at {}'.format(engine_version, repo_version))
        with open(lib_path, 'wb') as output_fp:
          output_fp.write(input_fp.read())
    except (IOError, OSError) as e:
      raise self.BinaryLocationError(
        "Error unpacking the native engine binary to path {}: {}".format(lib_path, e),
        e)
    return lib_path
475665
def go_to_ve():
    
    # two options are possible
    if not path.abspath(sys.prefix) == VE_ROOT:
        # Option A: we are in the parental process that was called from command line like
        # $> ./launch.py start PROCESS_NAME
        # in this case sys.prefix points to Global Interpreter
        python = get_python()
        retcode = subprocess.call([python, __file__] + sys.argv[1:])
        sys.exit(retcode)
    else:
        # Option B: we have already followed Option A and instantiated Virtual Environment command
        # This mean that sys.prefix points to Virtual Environment
        pass
160802
def binary(self):
        

        return self._project.loader.find_object_containing(self.addr, membership_check=False)
1088056
def get_system_path():
    """"""
    _bpath = []
    if is_win:
        try:
            import win32api
        except ImportError:
            logger.warn("Cannot determine your Windows or System directories")
            logger.warn("Please add them to your PATH if .dlls are not found")
            logger.warn("or install http://sourceforge.net/projects/pywin32/")
        else:
            sysdir = win32api.GetSystemDirectory()
            sysdir2 = os.path.normpath(os.path.join(sysdir, '..', 'SYSTEM'))
            windir = win32api.GetWindowsDirectory()
            _bpath = [sysdir, sysdir2, windir]
    _bpath.extend(compat.getenv('PATH', '').split(os.pathsep))
    return _bpath
1260392
def which(program, ignore_own_venv=False):
    
    if not program:
        return None
    if os.path.isabs(program):
        return program if is_executable(program) else None
    for p in os.environ.get("PATH", "").split(":"):
        fp = os.path.join(p, program)
        if (not ignore_own_venv or not fp.startswith(sys.prefix)) and is_executable(fp):
            return fp
    return None
140763
def get_env_path(cls):
        
        return os.path.dirname(Finder.python()) + os.pathsep + os.environ['PATH']
893406
def is_venv():
    
    dir_path = os.path.dirname(SRC)
    is_venv_flag = True

    if SYS_NAME == "Windows":
        executable_list = ["activate", "pip.exe", "python.exe"]
    elif SYS_NAME in ["Darwin", "Linux"]:
        executable_list = ["activate", "pip", "python"]

    for executable in executable_list:
        path = os.path.join(dir_path, BIN_SCRIPTS, executable)
        if not os.path.exists(path):
            is_venv_flag = False

    return is_venv_flag
1112094
def get_paths(self):
        '''
        
        '''

        # guess site package dir of virtualenv (system dependent)
        venv_site_packages = '%s/lib/site-packages' % self.venv_dir

        if not os.path.isdir(venv_site_packages):
            venv_site_packages_glob = glob.glob('%s/lib/*/site-packages' % self.venv_dir)

            if len(venv_site_packages_glob):
                venv_site_packages = venv_site_packages_glob[0]

        return [
            self.venv_dir,
            venv_site_packages
        ]
917134
def path_niftypet_local():
    ''''''
    # if using conda put the resources in the folder with the environment name
    if 'CONDA_DEFAULT_ENV' in os.environ:
        env = os.environ['CONDA_DEFAULT_ENV']
        print 'i> conda environment found:', env
    else:
        env = ''
    # create the path for the resources files according to the OS platform
    if platform.system() == 'Linux' :
        path_resources = os.path.join( os.path.join(os.path.expanduser('~'),   '.niftypet'), env )
    elif platform.system() == 'Windows' :
        path_resources = os.path.join( os.path.join(os.getenv('LOCALAPPDATA'), '.niftypet'), env )
    elif platform.system() == 'Darwin':
        path_resources = os.path.join( os.path.join(os.path.expanduser('~'),   '.niftypet'), env )
    else:
        raise SystemError('e> the operating system is not recognised and therefore not supported!')

    return path_resources
105986
@VisibleForTesting
  Path getWindowsPythonPath() {
    String cloudSdkPython = System.getenv("CLOUDSDK_PYTHON");
    if (cloudSdkPython != null) {
      Path cloudSdkPythonPath = Paths.get(cloudSdkPython);
      if (Files.exists(cloudSdkPythonPath)) {
        return cloudSdkPythonPath;
      } else {
        throw new InvalidPathException(cloudSdkPython, "python binary not in specified location");
      }
    }

    Path pythonPath = getPath().resolve(WINDOWS_BUNDLED_PYTHON);
    if (Files.exists(pythonPath)) {
      return pythonPath;
    } else {
      return Paths.get("python");
    }
  }
861792
def _get_relative_pythonpath(self):
        """"""
        # Workaround to replace os.path.relpath (new in Python v2.6):
        offset = len(self.root_path)+len(os.pathsep)
        return [path[offset:] for path in self.pythonpath]
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
13158
def get_pidfile_path(working_dir):
   
   pid_filename = virtualchain_hooks.get_virtual_chain_name() + ".pid"
   return os.path.join( working_dir, pid_filename )