Scans sys.path for standard library modules.
552657
def load_stdlib():
    '''
    '''
    if _stdlib:
        return _stdlib

    prefixes = tuple({os.path.abspath(p) for p in (
        sys.prefix,
        getattr(sys, 'real_prefix', sys.prefix),
        getattr(sys, 'base_prefix', sys.prefix),
    )})

    for sp in sys.path:
        if not sp:
            continue
        _import_paths.append(os.path.abspath(sp))

    stdpaths = tuple({p for p in _import_paths
                      if p.startswith(prefixes) and 'site-packages' not in p})

    _stdlib.update(sys.builtin_module_names)

    for stdpath in stdpaths:
        if not os.path.isdir(stdpath):
            continue

        for item in os.listdir(stdpath):
            if item.startswith('.') or item == 'site-packages':
                continue

            p = os.path.join(stdpath, item)
            if not os.path.isdir(p) and not item.endswith(('.py', '.so')):
                continue

            _stdlib.add(item.split('.', 1)[0])

    return _stdlib
290017
def scan_modules(self):
        

        # The module filenames may be spoofed by malware,
        # since this information resides in usermode space.
        # See: http://www.ragestorm.net/blogs/?p=163

        # Ignore special process IDs.
        # PID 0: System Idle Process. Also has a special meaning to the
        #        toolhelp APIs (current process).
        # PID 4: System Integrity Group. See this forum post for more info:
        #        http://tinyurl.com/ycza8jo
        #        (points to social.technet.microsoft.com)
        #        Only on XP and above
        # PID 8: System (?) only in Windows 2000 and below AFAIK.
        #        It's probably the same as PID 4 in XP and above.
        dwProcessId = self.get_pid()
        if dwProcessId in (0, 4, 8):
            return

        # It would seem easier to clear the snapshot first.
        # But then all open handles would be closed.
        found_bases = set()
        with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPMODULE,
                                            dwProcessId) as hSnapshot:
            me = win32.Module32First(hSnapshot)
            while me is not None:
                lpBaseAddress = me.modBaseAddr
                fileName      = me.szExePath    # full pathname
                if not fileName:
                    fileName  = me.szModule     # filename only
                    if not fileName:
                        fileName = None
                else:
                    fileName = PathOperations.native_to_win32_pathname(fileName)
                found_bases.add(lpBaseAddress)
##                if not self.has_module(lpBaseAddress): # XXX triggers a scan
                if lpBaseAddress not in self.__moduleDict:
                    aModule = Module(lpBaseAddress, fileName = fileName,
                                           SizeOfImage = me.modBaseSize,
                                           process = self)
                    self._add_module(aModule)
                else:
                    aModule = self.get_module(lpBaseAddress)
                    if not aModule.fileName:
                        aModule.fileName    = fileName
                    if not aModule.SizeOfImage:
                        aModule.SizeOfImage = me.modBaseSize
                    if not aModule.process:
                        aModule.process     = self
                me = win32.Module32Next(hSnapshot)
##        for base in self.get_module_bases(): # XXX triggers a scan
        for base in compat.keys(self.__moduleDict):
            if base not in found_bases:
                self._del_module(base)
802727
def scan_module(self, modpath, node):
        """"""

        used_origins = self.map.setdefault(modpath, set())

        def get_origins(modpath, name):
            """Returns the chain of all origins for a given name in a module."""
            origins = set()

            def walk_origins(modpath, name):
                for origin in self.import_map.get_origins(modpath, name):
                    if origin not in origins:
                        origins.add(origin)
                        if '.' in origin:
                            walk_origins(*origin.rsplit('.', 1))

            walk_origins(modpath, name)
            return origins

        def get_origins_for_node(node):
            """Returns the set of all possible origins to which the given
            dotted-path expression might dereference."""
            if node_type(node) == 'Name' and node_type(node.ctx) == 'Load':
                return {modpath + '.' + node.id} | get_origins(modpath, node.id)
            if node_type(node) == 'Attribute' and node_type(node.ctx) == 'Load':
                return set.union(set(), *[
                    {parent + '.' + node.attr} | get_origins(parent, node.attr)
                    for parent in get_origins_for_node(node.value)])
            return set()

        def get_origins_used_by_node(node):
            """Returns the set of all possible origins that could be used
            during dereferencing of the given dotted-path expression."""
            if node_type(node) == 'Name':
                return get_origins_for_node(node)
            if node_type(node) == 'Attribute':
                return set.union(get_origins_used_by_node(node.value),
                                 get_origins_for_node(node))
            return set()

        def scan_loads(node):
            if node_type(node) in ['Name', 'Attribute']:
                used_origins.update(get_origins_used_by_node(node))
            for_each_child(node, scan_loads)

        for_each_child(node, scan_loads)

        intermediate_origins = set()
        for origin in used_origins:
            parts = origin.split('.')
            for i in range(1, len(parts)):
                intermediate_origins.add('.'.join(parts[:i]))
        used_origins.update(intermediate_origins)
1012826
def library_path():
    '''
    
    '''
    return os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib'))
707478
def _get_library_search_paths():
    
    search_paths = [
        '',
        '/usr/lib64',
        '/usr/local/lib64',
        '/usr/lib', '/usr/local/lib',
        '/run/current-system/sw/lib',
        '/usr/lib/x86_64-linux-gnu/',
        os.path.abspath(os.path.dirname(__file__))
    ]

    if sys.platform == 'darwin':
        path_environment_variable = 'DYLD_LIBRARY_PATH'
    else:
        path_environment_variable = 'LD_LIBRARY_PATH'
    if path_environment_variable in os.environ:
        search_paths.extend(os.environ[path_environment_variable].split(':'))
    return search_paths
23084
def find_packages(path: str) -> List[str]:
    
    for root, _dir, files in os.walk(path):
        if '__init__.py' in files:
            yield root.replace("/", ".")
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')
1090379
def check_module(mod_name):
    """"""
    # Special cases #
    if mod_name in module_name: mod_name = module_name[mod_name]
    # Use a try except block #
    try:
        __import__(mod_name)
    except ImportError as e:
        if str(e) != 'No module named %s' % mod_name: raise e
        print 'You do not seem to have the "%s" package properly installed.' \
              ' Either you never installed it or your $PYTHONPATH is not set up correctly.' \
              ' For more instructions see the README file. (%s)' % (mod_name, e)
        sys.exit()
491402
def StringizeLibSymlinks(symlinks):
    """"""
    if SCons.Util.is_List(symlinks):
        try:
            return [ (k.get_path(), v.get_path()) for k,v in symlinks ]
        except (TypeError, ValueError):
            return symlinks
    else:
        return symlinks
19707
def _find_observable_paths(extra_files=None):
    """"""
    rv = set(
        os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspath(x)
        for x in sys.path
    )

    for filename in extra_files or ():
        rv.add(os.path.dirname(os.path.abspath(filename)))

    for module in list(sys.modules.values()):
        fn = getattr(module, "__file__", None)
        if fn is None:
            continue
        fn = os.path.abspath(fn)
        rv.add(os.path.dirname(fn))

    return _find_common_roots(rv)
371449
def _get_library_os_path_from_library_dict_tree(self, library_path, library_name):
        """"""
        if library_path is None or library_name is None:
            return None
        path_list = library_path.split(os.sep)
        target_lib_dict = self.libraries
        # go down the path to the correct library
        for path_element in path_list:
            if path_element not in target_lib_dict:  # Library cannot be found
                target_lib_dict = None
                break
            target_lib_dict = target_lib_dict[path_element]
        return None if target_lib_dict is None or library_name not in target_lib_dict else target_lib_dict[library_name]
423183
def get_module(self, module_name):
        """"""
        try:
            return self.module[module_name]

        except KeyError:
            return sys.modules[module_name]
850197
def load_module(module_name, module_path):
    """"""
    if sys.version_info >= (3,0):
        import pyximport
        pyximport.install()
        sys.path.append(module_path)
        return __import__(module_name)
    else:
        import imp
        module_info = imp.find_module(module_name, [module_path])
        return imp.load_module(module_name, *module_info)
1346313
def read(*paths):
    """"""
    p = os.path.join(*paths)
    if os.path.exists(p):
        with open(p, 'r') as f:
            return f.read()
    return ''
200
def find_module(modpath):
    """"""
    module_path = modpath.replace('.', '/') + '.py'
    init_path = modpath.replace('.', '/') + '/__init__.py'
    for root_path in sys.path:
        path = os.path.join(root_path, module_path)
        if os.path.isfile(path):
            return path
        path = os.path.join(root_path, init_path)
        if os.path.isfile(path):
            return path
981230
def get_module_path(module):
    """"""
    return pathlib.Path(
        os.path.dirname(os.path.abspath(inspect.getfile(module))))
1181853
def import_module(module_name):
    """"""
    import sys, os
    import importlib
    sys.path.append(os.path.dirname(__file__))
    return importlib.import_module(module_name)