Пример #1
0
def initialize():
	"""Initializes the appModule subsystem. 
	"""
	global NVDAProcessID,_importers
	NVDAProcessID=os.getpid()
	config.addConfigDirsToPythonPackagePath(appModules)
	_importers=list(pkgutil.iter_importers("appModules.__init__"))
Пример #2
0
def _extendPackagePaths(package):
    '''
    Extends the package paths for the provided package.
    
    @param package: module package
        The module package to be extended.
    @return: module package
        The extended module package, the same module usually.
    '''
    assert ismodule(package), 'Invalid package module %s' % package
    fullName, paths = package.__name__, package.__path__
    k = fullName.rfind('.')
    if k >= 0:
        name = fullName[k + 1:]
        importers = [get_importer(path) for path in sys.modules[fullName[:k]].__path__]
    else:
        name = fullName
        importers = iter_importers()

    for importer in importers:
        moduleLoader = importer.find_module(name)
        if moduleLoader and moduleLoader.is_package(name):
            path = os.path.dirname(moduleLoader.get_filename(name))
            if path not in paths:
                paths.append(path)
                # TODO: add checking to enforce the fact that the init file should not contain any code beside doc.
                # code = moduleLoader.get_code(name)
    package.__path__ = paths
    return package
Пример #3
0
def initialize():
    """Initializes the appModule subsystem. 
	"""
    global NVDAProcessID, _importers
    NVDAProcessID = os.getpid()
    config.addConfigDirsToPythonPackagePath(appModules)
    _importers = list(pkgutil.iter_importers("appModules.__init__"))
Пример #4
0
def _get_all_modules_pyinstaller():
    # Special handling for PyInstaller
    toc = set()
    importers = pkgutil.iter_importers(__package__)
    for i in importers:
        if hasattr(i, 'toc'):
            toc |= i.toc
    return toc
Пример #5
0
def tocGet():
    toc = set()

    for importer in pkgutil.iter_importers('galacteek'):
        if hasattr(importer, 'toc'):
            toc |= importer.toc

    return toc
Пример #6
0
def initialize():
    """Initializes the appModule subsystem. 
	"""
    global _importers
    config.addConfigDirsToPythonPackagePath(appModules)
    _importers = list(pkgutil.iter_importers("appModules.__init__"))
    if not initialize._alreadyInitialized:
        initialize._alreadyInitialized = True
Пример #7
0
def testGetPkgimport():
    # myp11.mkdir("/tmp/asdf")
    # FileFinder 应该是类似java的classload的东西,用来寻找可导入的类库
    for item in pkgutil.iter_importers():
        # print(item)
        for item2 in pkgutil.iter_importer_modules(item):
            # print(item2)
            pass
Пример #8
0
def frozen_iter_imps():
    mods = set()
    for imp in pkgutil.iter_importers('parsers'):
        if hasattr(imp, 'toc'):
            for mod in imp.toc:
                if mod.startswith('parsers.'):
                    mods.add(mod.split('.')[1])
    return list(mods)
Пример #9
0
def FindImporter(fullname):
    """Find a PEP 302 "loader" object for fullname

    If fullname contains dots, path must be the containing package's
    __path__. Returns None if the module cannot be found or imported.
    """
    for importer in iter_importers(fullname):
        if importer.find_module(fullname) is not None:
            return importer
    return None
Пример #10
0
 def test_pm_DevPackages(self):
     """Display a log message with packages found in dev.
        This is useful for the bin/testprod that should have 0 dev packages."""
     dev_package_paths = [package.path for package in iter_importers()
                          if hasattr(package, "path") and
                          package.path and
                          "/src/" in package.path]
     pm_logger.info("Number of dev packages: %d" % len(dev_package_paths))
     for dev_package_path in dev_package_paths:
         pm_logger.info("Dev package: %s" % dev_package_path)
Пример #11
0
def find_importer(fullname):
    """Find a PEP 302 "loader" object for fullname

    If fullname contains dots, path must be the containing package's
    __path__. Returns None if the module cannot be found or imported.
    """
    for importer in iter_importers(fullname):
        if importer.find_module(fullname) is not None:
            return importer
    return None
Пример #12
0
def get_pyinstaller_modules():
    result = []
    toc = set()
    for importer in pkgutil.iter_importers(mystic_why.__name__):
        if hasattr(importer, 'toc'):
            toc |= importer.toc
    for name in toc:
        if name.startswith(mystic_why.effects.__name__ + '.'):
            name_parts = name.split('.')
            result.append(name_parts[-1])

    return result
Пример #13
0
def iter_namespace(name):
    """Get module names from top level package name
    - Used when app is frozen with PyInstaller
    - Make sure to add module to pyi's collect_submodules so they're available from it's importer"""
    prefix = name + '.'
    toc = set()

    for importer in pkgutil.iter_importers(name.partition('.')[0]):
        if hasattr(importer, 'toc'):
            toc |= importer.toc

    for name in toc:
        if name.startswith(prefix):
            yield name
Пример #14
0
def iter_namespace(namespace):
    """Pyinstaller-compatible namespace iteration.

  Yields the name of all modules found at a given full-qualified module name.
  Use 'importlib.import_module' to import the found submodules.

  Usage:

  .. code-block:: python

      import importlib

      for found_submod in iter_namespace("module.submodule_to_iter"):
          m = importlib.import_module(found_submod)

  To have it running with pyinstaller, it still requires to ensure the wanted library
  is well packaged in your executable, and since there is no proper 'import' statements
  in your code pyinstaller might not find them. You might want to add a hook inject the
  "hidden" modules from your plugins folder inside the executable:

  - if your plugins are under the ``myappname/pluginfolder`` module
  - create a file ``specs/hook-<myappname.pluginfolder>.py``
  - content of this file should be:

      .. code-block:: python

          from PyInstaller.utils.hooks import collect_submodules
          hiddenimports = collect_submodules('<myappname.pluginfolder>')
  """
    ns_pkg = sys.modules[namespace]

    prefix = ns_pkg.__name__ + "."
    for p in pkgutil.iter_modules(ns_pkg.__path__, prefix):
        yield p[1]

    # special handling when the package is bundled with PyInstaller 3.5
    # See https://github.com/pyinstaller/pyinstaller/issues/1905#issuecomment-445787510
    toc = set()
    for importer in pkgutil.iter_importers(ns_pkg.__name__.partition(".")[0]):
        name = getattr(importer, "toc", None)
        if name:
            toc |= name
    for name in toc:
        if not name.startswith(prefix):
            continue
        rem_name = name[len(prefix):]
        if "." in rem_name:
            continue
        yield name
def _load_blockshapes():
    package_prefix = __name__ + "."

    # python file support
    for _, name, _ in pkgutil.walk_packages(__path__, package_prefix):
        _load_blockshape(name)

    # pyinstaller support
    toc = set()
    for importer in pkgutil.iter_importers(minecraft_model_reader.__name__):
        if hasattr(importer, "toc"):
            toc |= importer.toc
    for module_name in toc:
        if module_name.startswith(package_prefix):
            _load_blockshape(module_name)
Пример #16
0
def find_module_loader_without_import(module_name):
    # pkgutil.find_loader will trigger __import__
    if '.' in module_name:
        parent_module_name = module_name[:module_name.rfind('.')]
        parent_loader = find_module_loader_without_import(parent_module_name)
        if not parent_loader:
            return None
        importer = pkgutil.get_importer(os.path.dirname(parent_loader.get_filename()))
        return importer.find_module(module_name)
    else:
        for importer in pkgutil.iter_importers():
            loader = importer.find_module(module_name)
            if loader:
                return loader
        return None
Пример #17
0
def find_module_loader_without_import(module_name):
# pkgutil.find_loader will trigger __import__
    if '.' in module_name:
        parent_module_name = module_name[:module_name.rfind('.')]
        parent_loader = find_module_loader_without_import(parent_module_name)
        if not parent_loader:
            return None
        importer = pkgutil.get_importer(os.path.dirname(parent_loader.get_filename()))
        return importer.find_module(module_name)
    else:
        for importer in pkgutil.iter_importers():
            loader = importer.find_module(module_name)
            if loader:
                return loader
        return None
Пример #18
0
def iter_modules():
    # apparently pkgutil had some issues in python 2.6. Accessing any root level directories
    # failed. and it got the entire process of importing fail. Since we only need any
    # aria_extension related loading, in the meantime we could try to import only those
    # (and assume they are not located at the root level.
    # [In python 2.7 it does actually ignore any OSError].
    yielded = {}
    for importer in pkgutil.iter_importers():
        try:
            for module_name, ispkg in pkgutil.iter_importer_modules(importer):
                if module_name not in yielded:
                    yielded[module_name] = True
                    yield importer, module_name, ispkg
        except OSError:
            pass
Пример #19
0
def _walk_pyinstaller() -> typing.Iterator[ExtensionInfo]:
    """Walk extensions when using PyInstaller.

    See https://github.com/pyinstaller/pyinstaller/issues/1905

    Inspired by:
    https://github.com/webcomics/dosage/blob/master/dosagelib/loader.py
    """
    toc = set()  # type: typing.Set[str]
    for importer in pkgutil.iter_importers('qutebrowser'):
        if hasattr(importer, 'toc'):
            toc |= importer.toc
    for name in toc:
        if name.startswith(components.__name__ + '.'):
            yield ExtensionInfo(name=name)
Пример #20
0
def _walk_pyinstaller() -> typing.Iterator[ExtensionInfo]:
    """Walk extensions when using PyInstaller.

    See https://github.com/pyinstaller/pyinstaller/issues/1905

    Inspired by:
    https://github.com/webcomics/dosage/blob/master/dosagelib/loader.py
    """
    toc = set()  # type: typing.Set[str]
    for importer in pkgutil.iter_importers('qutebrowser'):
        if hasattr(importer, 'toc'):
            toc |= importer.toc
    for name in toc:
        if name.startswith(components.__name__ + '.'):
            yield ExtensionInfo(name=name)
Пример #21
0
def _pyi_pkgutil_iter_modules(path=None, prefix=''):
    # Use original implementation to discover on-filesystem
    # modules (binary extensions in regular builds, or both binary
    # extensions and compiled pyc modules in noarchive debug builds)
    yield from _orig_pkgutil_iter_modules(path, prefix)

    # Find the instance of PyInstaller's FrozenImporter
    for importer in pkgutil.iter_importers():
        if isinstance(importer, FrozenImporter):
            break
    else:
        return

    if not path:
        # Search for all top-level packages/modules. These will have
        # no dots in their entry names
        for entry in importer.toc:
            if entry.count('.') != 0:
                continue
            is_pkg = importer.is_package(entry)
            yield pkgutil.ModuleInfo(importer, prefix + entry, is_pkg)
    else:
        # Declare SYS_PREFIX locally, to avoid clash with eponymous
        # global symbol from pyi_rth_pkgutil hook.
        SYS_PREFIX = sys._MEIPASS + os.path.sep
        SYS_PREFIXLEN = len(SYS_PREFIX)
        # Only single path is supported, and it must start with
        # sys._MEIPASS
        pkg_path = os.path.normpath(path[0])
        # Remove this for compatibility with pluginpath
        # assert pkg_path.startswith(SYS_PREFIX)
        # Construct package prefix from path...
        pkg_prefix = pkg_path[SYS_PREFIXLEN:]
        pkg_prefix = pkg_prefix.replace(os.path.sep, '.')
        # ... and ensure it ends with a dot (so we can directly filter
        # out the package itself)
        if not pkg_prefix.endswith('.'):
            pkg_prefix += '.'
        pkg_prefix_len = len(pkg_prefix)

        for entry in importer.toc:
            if not entry.startswith(pkg_prefix):
                continue
            name = entry[pkg_prefix_len:]
            if name.count('.') != 0:
                continue
            is_pkg = importer.is_package(entry)
            yield pkgutil.ModuleInfo(importer, prefix + name, is_pkg)
Пример #22
0
def _load_functions():
    package = PyMCTranslate.code_functions
    package_prefix = package.__name__ + "."

    # python file support
    for _, name, _ in pkgutil.walk_packages(package.__path__, package_prefix):
        _load_function(name)

    # pyinstaller support
    toc = set()
    for importer in pkgutil.iter_importers(PyMCTranslate.__name__):
        if hasattr(importer, "toc"):
            toc |= importer.toc
    for module_name in toc:
        if module_name.startswith(package_prefix):
            _load_function(module_name)
Пример #23
0
def initialize():
	global _importers, _store
	
	import imp
	webModules = imp.new_module("webModules")
	webModules.__path__ = list()
	import sys
	sys.modules["webModules"] = webModules
	config.addConfigDirsToPythonPackagePath(webModules)
	webModules.__path__.insert(
		1 if config.conf["development"]["enableScratchpadDir"] else 0,
		os.path.join(globalVars.appArgs.configPath, "webModules")
	)
	_importers = list(pkgutil.iter_importers("webModules.__init__"))
	
	from ..store.webModule import WebModuleStore
	_store = WebModuleStore()
Пример #24
0
def dcs_modules():
    """Get names of DCS modules, depending on execution environment. If being packaged with PyInstaller,
    modules aren't discoverable dynamically by scanning source directory because `FrozenImporter` doesn't
    implement `iter_modules` method. But it is still possible to find all potential DCS modules by
    iterating through `toc`, which contains list of all "frozen" resources."""

    dcs_dirname = os.path.dirname(__file__)
    module_prefix = __package__ + '.'

    if getattr(sys, 'frozen', False):
        toc = set()
        for importer in pkgutil.iter_importers(dcs_dirname):
            if hasattr(importer, 'toc'):
                toc |= importer.toc
        return [module for module in toc if module.startswith(module_prefix) and module.count('.') == 2]
    else:
        return [module_prefix + name for _, name, is_pkg in pkgutil.iter_modules([dcs_dirname]) if not is_pkg]
Пример #25
0
    def _recursive_find(self, package_name: str):
        package = importlib.import_module(package_name)
        package_prefix = package.__name__ + "."

        # python file support
        for _, name, _ in pkgutil.walk_packages(package.__path__,
                                                package_prefix):
            self._load_obj(name)

        # pyinstaller support
        toc = set()
        for importer in pkgutil.iter_importers(amulet.__name__):
            if hasattr(importer, "toc"):
                toc |= importer.toc
        for module_name in toc:
            if module_name.startswith(package_prefix):
                self._load_obj(module_name)
Пример #26
0
def initialize():
    global store
    global _importers

    import imp
    webModules = imp.new_module("webModules")
    webModules.__path__ = list()
    import sys
    sys.modules["webModules"] = webModules
    config.addConfigDirsToPythonPackagePath(webModules)
    if nvdaVersion < (2019,
                      1) and not config.conf["webAccess"]["disableUserConfig"]:
        webModules.__path__.insert(
            0, os.path.join(globalVars.appArgs.configPath, "webModules"))
    _importers = list(pkgutil.iter_importers("webModules.__init__"))

    from ..store.webModule import WebModuleStore
    store = WebModuleStore()
 def _load_pyinstaller(self, package: str):
     # pyinstaller support
     toc = set()
     for importer in pkgutil.iter_importers(amulet_map_editor.__name__):
         if hasattr(importer, "toc"):
             toc |= importer.toc
     prefix = f"{package}."
     match = re.compile(f"^{re.escape(prefix)}[a-zA-Z0-9_]*$")
     for module_name in toc:
         if match.fullmatch(module_name):
             try:
                 mod = importlib.import_module(module_name)
             except ImportError:
                 log.warning(
                     f"Failed to import {module_name}.\n{traceback.format_exc()}"
                 )
             else:
                 self._load_module(module_name, mod)
def load_extensions():
    if not _extensions:
        _extensions.extend(_fixed_extensions)
        prefix = f"{programs.__name__}."

        # source support
        for _, name, _ in pkgutil.iter_modules(programs.__path__, prefix):
            load_extension(name)

        # pyinstaller support
        toc = set()
        for importer in pkgutil.iter_importers(amulet_map_editor.__name__):
            if hasattr(importer, "toc"):
                toc |= importer.toc
        match = re.compile(f"^{re.escape(prefix)}[a-zA-Z0-9_]*$")
        for name in toc:
            if match.fullmatch(name):
                load_extension(name)
Пример #29
0
def __find_all_plugins():
    """
    Finds all Bakefile plugins and yields them.
    """
    import pkgutil

    if hasattr(sys, 'frozen'):
        # Special handling for PyInstaller, which as of v3.4 doesn't support walk_packages
        # (see https://github.com/pyinstaller/pyinstaller/issues/1905)
        toc = set()
        for importer in pkgutil.iter_importers(__name__):
            if hasattr(importer, 'toc'):
                toc |= importer.toc
        for name in toc:
            if name.startswith(__name__ + '.'):
                yield name[len(__name__) + 1:]
    else:
        for _, name, _ in pkgutil.walk_packages(__path__):
            yield name
Пример #30
0
def __find_all_plugins():
    """
    Finds all Bakefile plugins and yields them.
    """
    import pkgutil

    if hasattr(sys, 'frozen'):
        # Special handling for PyInstaller, which as of v3.4 doesn't support walk_packages
        # (see https://github.com/pyinstaller/pyinstaller/issues/1905)
        toc = set()
        for importer in pkgutil.iter_importers(__name__):
            if hasattr(importer, 'toc'):
                toc |= importer.toc
        for name in toc:
            if name.startswith(__name__ + '.'):
                yield name[len(__name__) + 1:]
    else:
        for _, name, _ in pkgutil.walk_packages(__path__):
            yield name
Пример #31
0
def _dynamically_load():
    module_names = [
        m[1] for m in pkgutil.iter_modules(__path__, MODULE_PREFIX)
    ]

    # this is for pyinstaller
    # see https://github.com/pyinstaller/pyinstaller/issues/1905
    toc = set()
    for importer in pkgutil.iter_importers('dockermake'):
        if hasattr(importer, 'toc'):
            toc |= importer.toc
    for elm in toc:
        if elm.startswith(MODULE_PREFIX):
            module_names.append(elm)

    for name in module_names:
        try:
            importlib.import_module(name)
        except ImportError as msg:
            raise Exception("could not load module %s: %s" % (name, msg))
Пример #32
0
    def iter_modules(path=None, prefix=''):
        """Yield submodule names+loaders for path or sys.path"""
        if path is None:
            importers = iter_importers()
        else:
            importers = map(get_importer, path)

        yielded = {}
        for importer in importers:
            if hasattr(importer, 'iter_modules'):
                modules = importer.iter_modules(prefix)
            elif isinstance(importer, zipimporter):
                modules = iter_zipimport_modules(importer, prefix)
            else:
                modules = []
            for name, ispkg in modules:
                if name not in yielded:
                    yielded[name] = 1
                    yield importer, name, ispkg
        return
Пример #33
0
    def iter_modules(path=None, prefix=""):
        """Yield submodule names+loaders for path or sys.path"""
        if path is None:
            importers = iter_importers()
        else:
            importers = map(get_importer, path)

        yielded = {}
        for importer in importers:
            if hasattr(importer, "iter_modules"):
                modules = importer.iter_modules(prefix)
            elif isinstance(importer, zipimporter):
                modules = iter_zipimport_modules(importer, prefix)
            else:
                modules = []
            for name, ispkg in modules:
                if name not in yielded:
                    yielded[name] = 1
                    yield importer, name, ispkg
        return
Пример #34
0
def _iter_namespace(nsp):
    """
    Return an iterator of names of modules found in a specific namespace.

    The names are made absolute, with the namespace as prefix, to simplify
    import.
    """
    # Specifying the second argument (prefix) to iter_modules makes the
    # returned name an absolute name instead of a relative one. This allows
    # import_module to work without having to do additional modification to
    # the name.
    prefix = nsp.__name__ + "."
    for pkg in pkgutil.iter_modules(nsp.__path__, prefix):
        yield pkg[1]  # pkg is (finder, name, ispkg)
    # special handling when the package is bundled with PyInstaller
    # See https://github.com/pyinstaller/pyinstaller/issues/1905
    toc = set()  # table of content
    for importer in pkgutil.iter_importers(nsp.__name__.partition(".")[0]):
        if hasattr(importer, 'toc'):
            toc |= importer.toc
    for name in toc:
        if name.startswith(prefix):
            yield name
Пример #35
0
def import_tasks(module_name):
    """Convert module name into a path and call loader on the path.

    Example:
        .. code-block:: Python

            modules = import_tasks('rtl.tasks.*')

    Args:
        module_name (str): either a path or a name referencing a valid module.

    Returns:
        dict: a map of names and module references.

    """
    if '/' in module_name:
        return _loader(module_name)
    try:
        path = next(pkgutil.iter_importers(module_name)).path
    except ImportError as error:
        print('ERROR:', error)
        return {}
    return _loader(path)
 def test_iter_importers_avoids_emulation(self):
     with check_warnings() as w:
         for importer in pkgutil.iter_importers():
             pass
         self.assertEqual(len(w.warnings), 0)
Пример #37
0
def searchPaths(pattern):
    '''
    Finds all modules/packages available in the sys.path that respect the provided pattern. The search is done directly on the
    importers based on PEP 302. Basically this search guarantees that all modules that are defined (even if some might
    not be imported) respecting the pattern will be obtained.
    
    @param pattern: string
        The pattern is formed based on full module name, ex:
        
            __setup__
            Will return a map with the key setup and the values will contain all the paths that define a __setup__
            module.
            
            __setup__.*
            Will return all the modules that are found in __setup__ package.
            
            __setup__.**
            Will return all the modules and sub modules that are found in __setup__ package.
            
            __setup__.*_http
            Will return all the modules that are found in __setup__ package that end with _http.
    @return: dictionary{tuple(boolean, string), list[string]}
        A dictionary containing as a key a tuple with a flag indicating that the full name is a package and as a second value the package/module full path,
        and as a value a list of paths where this package/module is defined.
    '''
    assert isinstance(pattern, str), 'Invalid module pattern %s' % pattern
    modules, importers = {}, None
    k = pattern.rfind('.')
    if k >= 0:
        name = pattern[k + 1:]
        parent = searchPaths(pattern[:k])

        if name == '**':
            while parent:
                keyPack, pckgPaths = parent.popitem()
                isPackage, pckg = keyPack
                for path in pckgPaths:
                    if isPackage:
                        moduleImporter = get_importer(path)
                        for modulePath, isPkg in iter_importer_modules(moduleImporter):
                            path = dirname(moduleImporter.find_module(modulePath).get_filename(modulePath))
                            keyPack = (isPkg, pckg + ('.' if pckg else '') + modulePath)
                            if isPkg:
                                paths = parent.get(keyPack)
                                if paths is None: paths = parent[keyPack] = []
                                if path not in paths: paths.append(path)

                            paths = modules.get(keyPack)
                            if paths is None: paths = modules[keyPack] = []
                            if path not in paths: paths.append(path)
            return modules
        elif name.find('*') >= 0:
            matcher = re.compile('[a-zA-Z0-9_]*'.join([re.escape(e) for e in name.split('*')]))
            for keyPack, pckgPaths in parent.items():
                isPackage, pckg = keyPack
                for path in pckgPaths:
                    if isPackage:
                        moduleImporter = get_importer(path)
                        for modulePath, isPkg in iter_importer_modules(moduleImporter):
                            if matcher.match(modulePath):
                                path = dirname(moduleImporter.find_module(modulePath).get_filename(modulePath))
                                keyPack = (isPkg, pckg + ('.' if pckg else '') + modulePath)
                                paths = modules.get(keyPack)
                                if paths is None: paths = modules[keyPack] = []
                                if path not in paths: paths.append(path)
            return modules
        else: importers = [(keyPack[0], keyPack[1], get_importer(path)) for keyPack, paths in parent.items() for path in paths]
    else:
        name = pattern
        importers = [(True, '', imp) for imp in iter_importers()]

    for isPackage, package, importer in importers:
        if isPackage:
            moduleLoader = importer.find_module(name)
            if moduleLoader:
                path = dirname(moduleLoader.get_filename(name))
                keyPack = (moduleLoader.is_package(name), package + ('.' if package else '') + name)
            else: keyPack = None
        elif package == name or package.endswith('.' + name):
            nameMod = name
            kk = nameMod.rfind('.')
            if kk >= 0: nameMod = nameMod[kk + 1:]
            moduleLoader = importer.find_module(nameMod)
            path = dirname(moduleLoader.get_filename(nameMod))
            keyPack = (False, package)
        else: keyPack = None

        if keyPack:
            paths = modules.get(keyPack)
            if paths is None: paths = modules[keyPack] = []
            if path not in paths: paths.append(path)

    return modules
Пример #38
0
 def test_iter_importers_avoids_emulation(self):
     with check_warnings() as w:
         for importer in pkgutil.iter_importers(): pass
         self.assertEqual(len(w.warnings), 0)
Пример #39
0
def searchModules(pattern):
    '''
    Finds all modules available in the sys.path that respect the provided pattern. The search is done directly on the
    importers based on PEP 302. Basically this search guarantees that all modules that are defined (even if some might
    not be imported) respecting the pattern will be obtained.
    
    @param pattern: string
        The pattern is formed based on full module name, ex:
        
            __setup__
            Will return a map with the key setup and the values will contain all the paths that define a __setup__
            module.
            
            __setup__.*
            Will return all the modules that are found in __setup__ package.
            
            __setup__.**
            Will return all the modules and sub modules that are found in __setup__ package.
            
            __setup__.*_http
            Will return all the modules that are found in __setup__ package that end with _http.
    @return: dictionary{string, list[string]}
        A dictionary containing as a key the module full name, and as a value a list of paths where this module is
        defined.
    '''
    assert isinstance(pattern, str), 'Invalid module pattern %s' % pattern
    modules, importers = {}, None
    k = pattern.rfind('.')
    if k >= 0:
        name = pattern[k + 1:]
        parent = searchModules(pattern[:k])
        if name == '**':
            while parent:
                pckg, pckgPaths = parent.popitem()
                for path in pckgPaths:
                    moduleLoader = get_importer(dirname(path)).find_module(pckg)
                    if moduleLoader and moduleLoader.is_package(pckg):
                        moduleImporter = get_importer(path)
                        for modulePath, isPkg in iter_importer_modules(moduleImporter):
                            path = dirname(moduleImporter.find_module(modulePath).get_filename(modulePath))
                            if isPkg:
                                paths = parent.setdefault(pckg + ('.' if pckg else '') + modulePath, [])
                                if path not in paths: paths.append(path)
                            paths = modules.setdefault(pckg + ('.' if pckg else '') + modulePath, [])
                            if path not in paths: paths.append(path)
            return modules
        elif name.find('*') >= 0:
            matcher = re.compile('[a-zA-Z0-9_]*'.join([re.escape(e) for e in name.split('*')]))
            for pckg, pckgPaths in parent.items():
                for path in pckgPaths:
                    moduleLoader = get_importer(dirname(path)).find_module(pckg)
                    if moduleLoader and moduleLoader.is_package(pckg):
                        moduleImporter = get_importer(path)
                        for modulePath, isPkg in iter_importer_modules(moduleImporter):
                            if matcher.match(modulePath):
                                path = dirname(moduleImporter.find_module(modulePath).get_filename(modulePath))
                                paths = modules.setdefault(pckg + ('.' if pckg else '') + modulePath, [])
                                if path not in paths: paths.append(path)
            return modules
        else: importers = [(pckg, get_importer(path)) for pckg, paths in parent.items() for path in paths ]
    else:
        name = pattern
        importers = [('', imp) for imp in iter_importers()]

    for package, importer in importers:
        moduleLoader = importer.find_module(name)
        if moduleLoader:
            path = dirname(moduleLoader.get_filename(name))
            paths = modules.setdefault(package + ('.' if package else '') + name, [])
            if path not in paths: paths.append(path)
    return modules
Пример #40
0
    def setupUi(self, MainWindow):
        # Fonts
        font_headline = QtGui.QFont()
        font_headline.setPointSize(11 if platform.system() == 'Windows' else 13)
        font_headline.setBold(True)

        font_graphs = QtGui.QFont()
        font_graphs.setPixelSize(12)
        font_graphs.setBold(False)

        font_ee = QtGui.QFont()
        font_ee.setPointSize(9  if platform.system() == 'Windows' else 11)
        font_ee.setBold(False)

        # Graphs background
        pg.setConfigOption('background', (255, 255, 255))
        pg.setConfigOption('foreground', 'k')

        # Main window
        MainWindow_size = [1100, 809]  if platform.system() == 'Windows' else [1100, 789]
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(MainWindow_size[0], MainWindow_size[1])
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(MainWindow_size[0], MainWindow_size[1]))
        MainWindow.setMaximumSize(QtCore.QSize(MainWindow_size[0], MainWindow_size[1]))
        MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
        MainWindow.setDockOptions(QtWidgets.QMainWindow.AllowNestedDocks | QtWidgets.QMainWindow.AllowTabbedDocks | QtWidgets.QMainWindow.AnimatedDocks)
        MainWindow.setWindowTitle("pySAsum")
        # when we create .exe with pyinstaller, we need to store icon inside it. Then we find it inside unpacked temp directory.
        for i in pkgutil.iter_importers():
            path = str(i).split("'")[1].replace("\\\\", "\\") if str(i).find('FileFinder')>=0 else None
            if path != None: self.iconpath = path + "\\images\\icon.ico"
        MainWindow.setWindowIcon(QtGui.QIcon(self.iconpath))
        MainWindow.setIconSize(QtCore.QSize(30, 30))
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # Block: scan A
        self.label_scan_A = QtWidgets.QLabel(self.centralwidget)
        self.__create_element(self.label_scan_A, [15, 0, 80, 20], "label_scan_A", text="Scan A", font=font_headline, stylesheet="QLabel { color : blue; }")
        self.groupBox_scan_A = QtWidgets.QGroupBox(self.centralwidget)
        self.__create_element(self.groupBox_scan_A, [5, 22-self.groupbox_os_displ, 300, 359+self.groupbox_os_displ], "groupBox_scan_A")
        self.lineEdit_scan_A_name = QtWidgets.QLineEdit(self.groupBox_scan_A)
        self.__create_element(self.lineEdit_scan_A_name, [5, 6+self.groupbox_os_displ, 260, 20], "lineEdit_scan_A_name", font=font_ee)
        self.toolButton_scan_A = QtWidgets.QToolButton(self.groupBox_scan_A)
        self.__create_element(self.toolButton_scan_A, [275, 6+self.groupbox_os_displ, 20, 20], "toolButton_scan_A", text="...", font=font_ee)
        self.label_scan_A_type = QtWidgets.QLabel(self.groupBox_scan_A)
        self.__create_element(self.label_scan_A_type, [5, 29+self.groupbox_os_displ, 40, 20], "label_scan_A_type", text="Type:", font=font_ee)
        self.comboBox_scan_A_type = QtWidgets.QComboBox(self.groupBox_scan_A)
        self.__create_element(self.comboBox_scan_A_type, [45, 29+self.groupbox_os_displ, 150, 20], "comboBox_scan_A_type", combo=["Single point", "Integrated image", "2D map"], font=font_ee)
        self.graphicsView_scan_A = pg.ImageView(self.groupBox_scan_A)
        self.__create_element(self.graphicsView_scan_A, [3, 54+self.groupbox_os_displ, 295, 275], "graphicsView_scan_A")
        self.graphicsView_scan_A.ui.histogram.hide()
        self.graphicsView_scan_A.ui.menuBtn.hide()
        self.graphicsView_scan_A.ui.roiBtn.hide()
        self.label_scan_A_polarisation = QtWidgets.QLabel(self.groupBox_scan_A)
        self.__create_element(self.label_scan_A_polarisation, [5, 334+self.groupbox_os_displ, 75, 20], "label_scan_A_polarisation", text="Polarisation:", font=font_ee)
        self.comboBox_scan_A_polarisation = QtWidgets.QComboBox(self.groupBox_scan_A)
        self.__create_element(self.comboBox_scan_A_polarisation, [75, 334+self.groupbox_os_displ, 55, 20], "comboBox_scan_A_polarisation", font=font_ee)
        self.label_scan_A_pointNumber = QtWidgets.QLabel(self.groupBox_scan_A)
        self.__create_element(self.label_scan_A_pointNumber, [158, 334+self.groupbox_os_displ, 80, 20], "label_scan_A_pointNumber", text="Point number:", font=font_ee)
        self.comboBox_scan_A_pointNumber = QtWidgets.QComboBox(self.groupBox_scan_A)
        self.__create_element(self.comboBox_scan_A_pointNumber, [240, 334+self.groupbox_os_displ, 55, 20], "comboBox_scan_A_pointNumber", font=font_ee)

        # Block: scan B
        self.label_scan_B = QtWidgets.QLabel(self.centralwidget)
        self.__create_element(self.label_scan_B, [15, 385, 80, 20], "label_scan_B", text="Scan B", font=font_headline, stylesheet="QLabel { color : blue; }")
        self.groupBox_scan_B = QtWidgets.QGroupBox(self.centralwidget)
        self.__create_element(self.groupBox_scan_B, [5, 407-self.groupbox_os_displ, 300, 359+self.groupbox_os_displ], "groupBox_scan_B")
        self.lineEdit_scan_B_name = QtWidgets.QLineEdit(self.groupBox_scan_B)
        self.__create_element(self.lineEdit_scan_B_name, [5, 6+self.groupbox_os_displ, 260, 20], "lineEdit_scan_B_name", font=font_ee)
        self.toolButton_scan_B = QtWidgets.QToolButton(self.groupBox_scan_B)
        self.__create_element(self.toolButton_scan_B, [275, 6+self.groupbox_os_displ, 20, 20], "toolButton_scan_B", text="...", font=font_ee)
        self.label_scan_B_type = QtWidgets.QLabel(self.groupBox_scan_B)
        self.__create_element(self.label_scan_B_type, [5, 29+self.groupbox_os_displ, 40, 20], "label_scan_B_type", text="Type:", font=font_ee)
        self.comboBox_scan_B_type = QtWidgets.QComboBox(self.groupBox_scan_B)
        self.__create_element(self.comboBox_scan_B_type, [45, 29+self.groupbox_os_displ, 150, 20], "comboBox_scan_B_type", combo=["Single point", "Integrated image", "2D map"], font=font_ee)
        self.graphicsView_scan_B = pg.ImageView(self.groupBox_scan_B)
        self.__create_element(self.graphicsView_scan_B, [3, 54+self.groupbox_os_displ, 295, 275], "graphicsView_scan_B")
        self.graphicsView_scan_B.ui.histogram.hide()
        self.graphicsView_scan_B.ui.menuBtn.hide()
        self.graphicsView_scan_B.ui.roiBtn.hide()
        self.label_scan_B_polarisation = QtWidgets.QLabel(self.groupBox_scan_B)
        self.__create_element(self.label_scan_B_polarisation, [5, 334+self.groupbox_os_displ, 75, 20], "label_scan_B_polarisation", text="Polarisation:", font=font_ee)
        self.comboBox_scan_B_polarisation = QtWidgets.QComboBox(self.groupBox_scan_B)
        self.__create_element(self.comboBox_scan_B_polarisation, [75, 334+self.groupbox_os_displ, 55, 20], "comboBox_scan_B_polarisation", font=font_ee)
        self.label_scan_B_pointNumber = QtWidgets.QLabel(self.groupBox_scan_B)
        self.__create_element(self.label_scan_B_pointNumber, [158, 334+self.groupbox_os_displ, 80, 20], "label_scan_B_pointNumber", text="Point number:", font=font_ee)
        self.comboBox_scan_B_pointNumber = QtWidgets.QComboBox(self.groupBox_scan_B)
        self.__create_element(self.comboBox_scan_B_pointNumber, [240, 334+self.groupbox_os_displ, 55, 20], "comboBox_scan_B_pointNumber", font=font_ee)

        # Block: Result
        self.label_result = QtWidgets.QLabel(self.centralwidget)
        self.__create_element(self.label_result, [325, 0, 61, 20], "label_result", text="Result", font=font_headline, stylesheet="QLabel { color : blue; }")
        self.groupBox_result = QtWidgets.QGroupBox(self.centralwidget)
        self.__create_element(self.groupBox_result, [320, 22-self.groupbox_os_displ, 775, 744+self.groupbox_os_displ], "groupBox_result")
        # ROI part is hidden by default
        self.graphicsView_result_integratedRoi = pg.PlotWidget(self.groupBox_result)
        self.__create_element(self.graphicsView_result_integratedRoi, [13, 424+self.groupbox_os_displ, 770, 265], "graphicsView_result_integratedRoi")
        self.graphicsView_result_integratedRoi.getAxis("bottom").tickFont = font_graphs
        self.graphicsView_result_integratedRoi.getAxis("bottom").setStyle(tickTextOffset=10)
        self.graphicsView_result_integratedRoi.getAxis("left").tickFont = font_graphs
        self.graphicsView_result_integratedRoi.getAxis("left").setStyle(tickTextOffset=5)
        self.graphicsView_result_integratedRoi.showAxis("top")
        self.graphicsView_result_integratedRoi.getAxis("top").setStyle(showValues=False)
        self.graphicsView_result_integratedRoi.showAxis("right")
        self.graphicsView_result_integratedRoi.getAxis("right").setStyle(showValues=False)
        self.label_result_roi_left = QtWidgets.QLabel(self.groupBox_result)
        self.__create_element(self.label_result_roi_left, [10, 694+self.groupbox_os_displ, 130, 22], "label_result_roi_left", text="ROI coordinates: left", font=font_ee)
        self.lineEdit_result_roi_left = QtWidgets.QLineEdit(self.groupBox_result)
        self.__create_element(self.lineEdit_result_roi_left, [127, 694+self.groupbox_os_displ, 40, 22], "lineEdit_result_roi_left", text="10", font=font_ee)
        self.label_result_roi_right = QtWidgets.QLabel(self.groupBox_result)
        self.__create_element(self.label_result_roi_right, [183, 694+self.groupbox_os_displ, 40, 22], "label_result_roi_right", text="right", font=font_ee)
        self.lineEdit_result_roi_right = QtWidgets.QLineEdit(self.groupBox_result)
        self.__create_element(self.lineEdit_result_roi_right, [217, 694+self.groupbox_os_displ, 40, 22], "lineEdit_result_roi_right", text="20", font=font_ee)
        self.label_result_roi_top = QtWidgets.QLabel(self.groupBox_result)
        self.__create_element(self.label_result_roi_top, [270, 694+self.groupbox_os_displ, 40, 22], "label_result_roi_top", text="top", font=font_ee)
        self.lineEdit_result_roi_top = QtWidgets.QLineEdit(self.groupBox_result)
        self.__create_element(self.lineEdit_result_roi_top, [297, 694+self.groupbox_os_displ, 40, 22], "lineEdit_result_roi_top", text="10", font=font_ee)
        self.label_result_roi_bottom = QtWidgets.QLabel(self.groupBox_result)
        self.__create_element(self.label_result_roi_bottom, [348, 694+self.groupbox_os_displ, 42, 22], "label_result_roi_bottom", text="bottom", font=font_ee)
        self.lineEdit_result_roi_bottom = QtWidgets.QLineEdit(self.groupBox_result)
        self.__create_element(self.lineEdit_result_roi_bottom, [397, 694+self.groupbox_os_displ, 40, 22], "lineEdit_result_roi_bottom", text="20", font=font_ee)
        self.pushButton_result_roi_turn = QtWidgets.QPushButton(self.groupBox_result)
        self.__create_element(self.pushButton_result_roi_turn, [535, 694+self.groupbox_os_displ, 80, 22], "pushButton_result_roi_turn", text="Turn ROI", font=font_headline)
        self.pushButton_result_integratedRoi_export = QtWidgets.QPushButton(self.groupBox_result)
        self.__create_element(self.pushButton_result_integratedRoi_export, [620, 694+self.groupbox_os_displ, 151, 22], "pushButton_result_integratedRoi_export", text="Export int. ROI", font=font_headline)

        # This part of Result block is visible
        self.checkBox_result_devideByMonitor = QtWidgets.QCheckBox(self.groupBox_result)
        self.__create_element(self.checkBox_result_devideByMonitor, [5, 6+self.groupbox_os_displ, 241, 22], "checkBox_result_devideByMonitor", text="Devide by monitors", font=font_ee)
        self.label_result_aspectRatio = QtWidgets.QLabel(self.groupBox_result)
        self.__create_element(self.label_result_aspectRatio, [165, 6+self.groupbox_os_displ, 75, 20], "label_result_aspectRatio", text="Aspect ratio:", font=font_ee)
        self.horizontalSlider_result_aspectRatio = QtWidgets.QSlider(self.groupBox_result)
        self.__create_element(self.horizontalSlider_result_aspectRatio, [245, 6+self.groupbox_os_displ, 120, 22], "horizontalSlider_result_aspectRatio")
        self.horizontalSlider_result_aspectRatio.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider_result_aspectRatio.setMinimum(1)
        self.horizontalSlider_result_aspectRatio.setMaximum(30)
        self.horizontalSlider_result_aspectRatio.setValue(1)
        self.label_result_2Dmap_View_scale = QtWidgets.QLabel(self.groupBox_result)
        self.__create_element(self.label_result_2Dmap_View_scale, [395, 6+self.groupbox_os_displ, 40, 22], "label_result_2Dmap_View_scale", text="View", font=font_ee)
        self.comboBox_result_2Dmap_scale = QtWidgets.QComboBox(self.groupBox_result)
        self.__create_element(self.comboBox_result_2Dmap_scale, [425, 6+self.groupbox_os_displ, 50, 22], "comboBox_result_2Dmap_scale", font=font_ee, combo=["Log", "Lin"])
        self.comboBox_result_operation_sign = QtWidgets.QComboBox(self.groupBox_result)
        self.__create_element(self.comboBox_result_operation_sign, [500, 6 + self.groupbox_os_displ, 40, 22], "comboBox_result_operation_sign", font=font_ee, combo=["-", "+"])

        self.lineEdit_result_operation = QtWidgets.QLineEdit(self.groupBox_result)
        self.__create_element(self.lineEdit_result_operation, [545, 6+self.groupbox_os_displ, 130, 22], "lineEdit_result_operation", stylesheet="color:rgb(0,0,0)", enabled=False, font=font_ee)
        self.pushButton_result_swapAB = QtWidgets.QPushButton(self.groupBox_result)
        self.__create_element(self.pushButton_result_swapAB, [680, 6+self.groupbox_os_displ, 90, 22], "pushButton_result_swapAB", text="(A <-> B)", font=font_headline)
        self.graphicsView_result = pg.ImageView(self.groupBox_result)
        self.__create_element(self.graphicsView_result, [3, 32+self.groupbox_os_displ, 770, 684], "graphicsView_result")
        self.graphicsView_result.ui.menuBtn.hide()
        self.graphicsView_result.ui.roiBtn.hide()
        self.graphicsView_result.ui.histogram.clickAccepted
        colmap = pg.ColorMap(np.array([0.4, 0.5, 0.6]),
                             np.array([[0, 0, 255, 255], [0, 0, 0, 255], [0, 255, 0, 255]], dtype=np.ubyte))
        self.graphicsView_result.setColorMap(colmap)

        self.label_result_f_numberOfPixels_reduce = QtWidgets.QLabel(self.groupBox_result)
        self.__create_element(self.label_result_f_numberOfPixels_reduce, [10, 720+self.groupbox_os_displ, 250, 20], "label_result_f_numberOfPixels_reduce", text="Reduce number of pixels in each direction by:", font=font_ee)
        self.checkBox_result_f_numberOfPixels_reduce_by2 = QtWidgets.QCheckBox(self.groupBox_result)
        self.__create_element(self.checkBox_result_f_numberOfPixels_reduce_by2, [270, 720+self.groupbox_os_displ, 241, 20], "checkBox_result_f_numberOfPixels_reduce_by2", text="x2", font=font_ee)
        self.checkBox_result_f_numberOfPixels_reduce_by4 = QtWidgets.QCheckBox(self.groupBox_result)
        self.__create_element(self.checkBox_result_f_numberOfPixels_reduce_by4, [315, 720+self.groupbox_os_displ, 241, 20], "checkBox_result_f_numberOfPixels_reduce_by4", text="x4", font=font_ee)
        self.checkBox_result_f_numberOfPixels_reduce_by8 = QtWidgets.QCheckBox(self.groupBox_result)
        self.__create_element(self.checkBox_result_f_numberOfPixels_reduce_by8, [360, 720+self.groupbox_os_displ, 241, 20], "checkBox_result_f_numberOfPixels_reduce_by8", text="x8", font=font_ee)
        self.pushButton_result_export = QtWidgets.QPushButton(self.groupBox_result)
        self.__create_element(self.pushButton_result_export, [620, 719+self.groupbox_os_displ, 151, 22], "pushButton_result_export", text="Export result (2D)", font=font_headline)
        self.pushButton_result_ROI = QtWidgets.QPushButton(self.groupBox_result)
        self.__create_element(self.pushButton_result_ROI, [535, 719+self.groupbox_os_displ, 80, 22], "pushButton_result_ROI", text="ROI", font=font_headline)
        self.pushButton_result_Clear = QtWidgets.QPushButton(self.groupBox_result)
        self.__create_element(self.pushButton_result_Clear, [450, 719 + self.groupbox_os_displ, 80, 22], "pushButton_result_Clear", text="Clear", font=font_headline)

        # Menu and statusbar
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.__create_element(self.menubar, [0, 0, 717, 21], "menubar", font=font_ee)
        self.menu_help = QtWidgets.QMenu(self.menubar)
        self.__create_element(self.menu_help, [999, 999, 999, 999], "menu_help", title="Help", font=font_ee)
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.action_version = QtWidgets.QAction(MainWindow)
        self.__create_element(self.action_version, [999, 999, 999, 999], "action_version", text="Version 1.4.1", font=font_ee)
        self.menu_help.addAction(self.action_version)
        self.menubar.addAction(self.menu_help.menuAction())