Fixup paths added in .pth file that point to the virtualenv
    instead of the system site packages.

    In depth:  .PTH can execute arbitrary code, which might
    manipulate the PATH or sys.path

    :return:
11877
def fixup_paths():
    
    original_paths = os.environ.get('PATH', "").split(os.path.pathsep)
    original_dirs = set(added_dirs)
    yield

    # Fix PATH environment variable
    current_paths = os.environ.get('PATH', "").split(os.path.pathsep)
    if original_paths != current_paths:
        changed_paths = set(current_paths).difference(set(original_paths))
        # rebuild PATH env var
        fixed_paths = []
        for path in current_paths:
            if path in changed_paths:
                fixed_paths.append(env_t(fix_path(path)))
            else:
                fixed_paths.append(env_t(path))
        os.environ['PATH'] = os.pathsep.join(fixed_paths)

    # Fix added_dirs
    if added_dirs != original_dirs:
        for path in set(added_dirs.difference(original_dirs)):
            fixed_path = fix_path(path)
            if fixed_path != path:
                print("Fix %s >> %s" % (path, fixed_path))
                added_dirs.remove(path)
                added_dirs.add(fixed_path)

                i = sys.path.index(path)  # not efficient... but shouldn't happen often
                sys.path[i] = fixed_path

                if env_t(fixed_path) not in os.environ['PATH']:
                    os.environ['PATH'].append(os.pathsep + env_t(fixed_path))
1230915
def added_env_paths(env_vars, env=None):
    
    if not env_vars:
        return None

    if not env:
        env = dict(os.environ)

    result = dict(env)
    for env_var, paths in env_vars.items():
        separator = paths[0]
        paths = paths[1:]
        current = env.get(env_var, "")
        current = [x for x in current.split(separator) if x]

        added = 0
        for path in paths.split(separator):
            if path not in current:
                added += 1
                current.append(path)

        if added:
            result[env_var] = separator.join(current)

    return result
149657
def paths_list():
        

        paths = set()
        try:
            paths.add(os.getcwd())
        except FileNotFoundError:
            log.warning("The current working directory doesn't exist")
        if "PATH" in os.environ:
            paths.update(os.environ["PATH"].split(os.pathsep))
        else:
            log.warning("The PATH environment variable doesn't exist")
        # look for Qemu binaries in the current working directory and $PATH
        if sys.platform.startswith("win"):
            # add specific Windows paths
            if hasattr(sys, "frozen"):
                # add any qemu dir in the same location as gns3server.exe to the list of paths
                exec_dir = os.path.dirname(os.path.abspath(sys.executable))
                for f in os.listdir(exec_dir):
                    if f.lower().startswith("qemu"):
                        paths.add(os.path.join(exec_dir, f))

            if "PROGRAMFILES(X86)" in os.environ and os.path.exists(os.environ["PROGRAMFILES(X86)"]):
                paths.add(os.path.join(os.environ["PROGRAMFILES(X86)"], "qemu"))
            if "PROGRAMFILES" in os.environ and os.path.exists(os.environ["PROGRAMFILES"]):
                paths.add(os.path.join(os.environ["PROGRAMFILES"], "qemu"))
        elif sys.platform.startswith("darwin"):
            if hasattr(sys, "frozen"):
                # add specific locations on Mac OS X regardless of what's in $PATH
                paths.update(["/usr/bin", "/usr/local/bin", "/opt/local/bin"])
                try:
                    exec_dir = os.path.dirname(os.path.abspath(sys.executable))
                    paths.add(os.path.abspath(os.path.join(exec_dir, "../Resources/qemu/bin/")))
                # If the user run the server by hand from outside
                except FileNotFoundError:
                    paths.add("/Applications/GNS3.app/Contents/Resources/qemu/bin")
        return paths
368193
def _build_paths():
    
    paths = sysconfig.get_paths()
    return {
        "prefix": sys.prefix,
        "data": paths["data"],
        "scripts": paths["scripts"],
        "headers": paths["include"],
        "purelib": paths["purelib"],
        "platlib": paths["platlib"],
    }
1334757
def _SetupPaths():
  """"""
  sdk_path = _FindSdkPath()
  if sdk_path:
    sys.path.append(sdk_path)
    try:
      import dev_appserver  # pylint: disable=g-import-not-at-top
      if hasattr(dev_appserver, 'fix_sys_path'):
        dev_appserver.fix_sys_path()
      else:
        logging.warning(_NO_FIX_SYS_PATH_WARNING)
    except ImportError:
      logging.warning(_IMPORT_ERROR_WARNING)
  else:
    logging.warning(_NOT_FOUND_WARNING)

  # Add the path above this directory, so we can import the endpoints package
  # from the user's app code (rather than from another, possibly outdated SDK).
  # pylint: disable=g-import-not-at-top
  from google.appengine.ext import vendor
  vendor.add(os.path.dirname(os.path.dirname(__file__)))
114117
def set_data_path(self, pth):
        
        if os.path.exists(pth):
            if not os.path.exists(os.path.join(pth, 'data', 'geodetic')):
                raise IOError("The given path doesn't contain a 'data' "
                              "subdirectory")
            os.environ["AIPSPATH"] = "%s dummy dummy" % pth
22368
def restart_in_venv(venv, base, site_packages, args):
    
    if base and not os.path.isabs(venv) and not venv.startswith('~'):
        base = os.path.expanduser(base)
        # ensure we have an abs basepath at this point:
        #    a relative one makes no sense (or does it?)
        if os.path.isabs(base):
            venv = os.path.join(base, venv)

    if venv.startswith('~'):
        venv = os.path.expanduser(venv)

    if not os.path.exists(venv):
        try:
            import virtualenv
        except ImportError:
            print('The virtual environment does not exist: %s' % venv)
            print('and virtualenv is not installed, so a new environment cannot be created')
            sys.exit(3)
        print('Creating new virtualenv environment in %s' % venv)
        virtualenv.logger = logger
        logger.indent += 2
        virtualenv.create_environment(venv, site_packages=site_packages)
    if sys.platform == 'win32':
        python = os.path.join(venv, 'Scripts', 'python.exe')
        # check for bin directory which is used in buildouts
        if not os.path.exists(python):
            python = os.path.join(venv, 'bin', 'python.exe')
    else:
        python = os.path.join(venv, 'bin', 'python')
    if not os.path.exists(python):
        python = venv
    if not os.path.exists(python):
        raise BadCommand('Cannot find virtual environment interpreter at %s' % python)
    base = os.path.dirname(os.path.dirname(python))
    file = os.path.join(os.path.dirname(__file__), 'runner.py')
    if file.endswith('.pyc'):
        file = file[:-1]
    proc = subprocess.Popen(
        [python, file] + args + [base, '___VENV_RESTART___'])
    proc.wait()
    sys.exit(proc.returncode)
756142
def fix_path(path):
    
    if '\\' in path:
        path = path.replace('\\', '/')

    path = os.path.normpath(path)

    return path
842465
def normalize_path():
    
    # Normalize Python paths
    whole_path = [
        os.path.abspath(path) for path in sys.path if os.path.exists(path)
    ]

    # Keep the "dynamic" current folder indicator and add the "static"
    # current path
    # Use an OrderedDict to have a faster lookup (path not in whole_set)
    whole_set = collections.OrderedDict((("", 1), (os.getcwd(), 1)))

    # Add original path entries
    for path in whole_path:
        if path not in whole_set:
            whole_set[path] = 1

    # Set the new content of sys.path (still ordered thanks to OrderedDict)
    sys.path = list(whole_set)

    # Normalize paths in loaded modules
    for module_ in sys.modules.values():
        try:
            module_.__path__ = [
                os.path.abspath(path)
                for path in module_.__path__
                if _package_exists(path)
            ]
        except AttributeError:
            # builtin modules don't have a __path__
            pass
        except ImportError:
            pass
212441
def find_path_package(thepath):
    
    pname = find_path_package_name(thepath)
    if not pname:
        return None
    fromlist = b'' if six.PY2 else ''
    return __import__(pname, globals(), locals(), [fromlist])
735274
def add_static_path(self, prefix: str, path: str) -> None:
        
        pattern = prefix
        if not pattern.startswith('/'):
            pattern = '/' + pattern
        if not pattern.endswith('/(.*)'):
            pattern = pattern + '/(.*)'
        self.add_handlers(
            r'.*',  # add static path for all virtual host
            [(pattern, StaticFileHandler, dict(path=path))]
        )
12187
def __add_paths(self, config):
        
        bin_path = os.path.join(self.directory.install_directory(self.feature_name), 'bin')
        whitelist_executables = self._get_whitelisted_executables(config)
        for f in os.listdir(bin_path):
            for pattern in BLACKLISTED_EXECUTABLES:
                if re.match(pattern, f):
                    continue
            if whitelist_executables and f not in whitelist_executables:
                continue
            self.directory.symlink_to_bin(f, os.path.join(bin_path, f))
722595
def _interpreter_path(append_version: bool = False) -> str:
    

    base_dir = Path(getattr(sys, "real_prefix", sys.base_prefix)).resolve()
    sys_exec = Path(sys.executable)
    name = sys_exec.stem
    suffix = sys_exec.suffix

    if append_version:
        name += str(sys.version_info.major)

    name += suffix

    try:
        return str(next(iter(base_dir.rglob(name))))

    except StopIteration:

        if not append_version:
            # If we couldn't find an interpreter, it's likely that we looked for
            # "python" when we should've been looking for "python3"
            # so we try again with append_version=True
            return _interpreter_path(append_version=True)

        # If we were still unable to find a real interpreter for some reason
        # we fallback to the current runtime's interpreter
        return sys.executable
81777
def join_sys_path(currfile, dir_level_num=3):
    
    if os.path.isdir(currfile):
        root_path = currfile
    else:
        root_path = get_base_dir(currfile, dir_level_num)

    sys.path.append(root_path)
787318
def _fix_paths(self, options):
        
        for k in ('template_path', 'static_path'):
            if k in options:
                v = options.pop(k)
                if v is None:
                    continue
                if not os.path.isabs(v):
                    v = os.path.abspath(
                        os.path.join(self.root_path, v))
                    app_log.debug('Fix %s to be absolute: %s' % (k, v))
                options[k] = v
1062218
def _directory_import(self):
        

        # Return True on success, False on failure but download is allowed, and
        # otherwise raise SystemExit
        path = os.path.abspath(self.path)

        # Use an empty WorkingSet rather than the man
        # pkg_resources.working_set, since on older versions of setuptools this
        # will invoke a VersionConflict when trying to install an upgrade
        ws = pkg_resources.WorkingSet([])
        ws.add_entry(path)
        dist = ws.by_key.get(DIST_NAME)

        if dist is None:
            # We didn't find an egg-info/dist-info in the given path, but if a
            # setup.py exists we can generate it
            setup_py = os.path.join(path, 'setup.py')
            if os.path.isfile(setup_py):
                # We use subprocess instead of run_setup from setuptools to
                # avoid segmentation faults - see the following for more details:
                # https://github.com/cython/cython/issues/2104
                sp.check_output([sys.executable, 'setup.py', 'egg_info'], cwd=path)

                for dist in pkg_resources.find_distributions(path, True):
                    # There should be only one...
                    return dist

        return dist
1131728
def pushPath(self, path):
        
        # normalize the path
        path = os.path.normcase(nstr(path)).strip()
        if path and path != '.' and path not in sys.path:
            sys.path.append(path)
            self._addedpaths.insert(0, path)
            return True
        return False