python类import_module()的实例源码

navigation.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _get_page_class(self, path, page_cls_name):

        # last module name does not contain '_'
        final_module = self.unify_page_path(path[-1],
                                            preserve_spaces=False)
        page_cls_path = ".".join(path[:-1] + (final_module,))
        page_cls_path = self.unify_page_path(page_cls_path)
        # append 'page' as every page module ends with this keyword
        page_cls_path += "page"

        page_cls_name = page_cls_name or self._get_page_cls_name(final_module)

        module = None
        # return imported class
        for path in self.PAGES_IMPORT_PATH:
            try:
                module = importlib.import_module(path %
                                                 page_cls_path)
                break
            except ImportError:
                pass
        if module is None:
            raise ImportError("Failed to import module: " +
                              (path % page_cls_path))
        return getattr(module, page_cls_name)
qt.py 文件源码 项目:zoocore 作者: dsparrow27 项目源码 文件源码 阅读 126 收藏 0 点赞 0 评论 0
def _setup(module, extras):
    """Install common submodules"""

    Qt.__binding__ = module.__name__

    for name in list(_common_members) + extras:
        try:
            submodule = importlib.import_module(
                module.__name__ + "." + name)
        except ImportError:
            continue

        setattr(Qt, "_" + name, submodule)

        if name not in extras:
            # Store reference to original binding,
            # but don't store speciality modules
            # such as uic or QtUiTools
            setattr(Qt, name, _new_module(name))
python_linter.py 文件源码 项目:sublime-text-3-packages 作者: nickjj 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_module_version(cls):
        """
        Return the string version of the imported module, without any prefix/suffix.

        This method handles the common case where a module (or one of its parents)
        defines a __version__ string. For other cases, subclasses should override
        this method and return the version string.

        """

        if cls.module:
            module = cls.module

            while True:
                if isinstance(getattr(module, '__version__', None), str):
                    return module.__version__

                if hasattr(module, '__package__'):
                    try:
                        module = importlib.import_module(module.__package__)
                    except ImportError:
                        return None
        else:
            return None
__init__.py 文件源码 项目:routersploit 作者: reverse-shell 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def import_exploit(path):
    """ Import exploit module

    :param path: absolute path to exploit e.g. routersploit.modules.exploits.asus.pass_bypass
    :return: exploit module or error
    """
    try:
        module = importlib.import_module(path)
        return getattr(module, 'Exploit')
    except (ImportError, AttributeError, KeyError) as err:
        raise RoutersploitException(
            "Error during loading '{}'\n\n"
            "Error: {}\n\n"
            "It should be valid path to the module. "
            "Use <tab> key multiple times for completion.".format(humanize_path(path), err)
        )
ampersand.py 文件源码 项目:ampersand 作者: natejms 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plugin_run(self, name, method, content):
        root = relative(self.root)

        try:
            # Retrieve the _plugin.json file
            plugin = build.get_json(
                root(self.config["plugins"][name], "_plugin.json"))

            # Load and run the module
            if plugin["method"] == method:
                sys.path.append(root(self.config["plugins"][name]))
                module = importlib.import_module(plugin["init"], name)
                content = module.main(content, self)

            return content

        except (KeyError, OSError, TypeError,
                ImportError, AttributeError) as e:
            return content
session.py 文件源码 项目:smc-python 作者: gabstopper 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def import_submodules(package, recursive=True):
    """
    Import all submodules of a module, recursively,
    including subpackages.

    From http://stackoverflow.com/questions/3365740/how-to-import-all-submodules

    :param package: package (name or actual module)
    :type package: str | module
    :rtype: dict[str, types.ModuleType]
    """
    import importlib
    import pkgutil
    if isinstance(package, str):
        package = importlib.import_module(package)
    results = {}
    for _loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
        full_name = package.__name__ + '.' + name
        results[full_name] = importlib.import_module(full_name)
        if recursive and is_pkg:
            results.update(import_submodules(full_name))
commands_collector.py 文件源码 项目:quokka_ng 作者: rochacbruno 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def get_command(self, ctx, name):
        try:
            if sys.version_info[0] == 2:
                name = name.encode('ascii', 'replace')
            splitted = name.split('_')
            if len(splitted) <= 1:
                return
            module_name, command_name = splitted
            if not all([module_name, command_name]):
                return
            module = '{0}.{1}.commands.{2}'.format(
                self.base_module_name,
                module_name,
                command_name)
            mod = importlib.import_module(module)
        except ImportError:
            return
        return getattr(mod, 'cli', None)
action_editor.py 文件源码 项目:sc-controller 作者: kozec 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def load_component(self, class_name):
        """
        Loads and adds new component to editor.
        Returns component instance.
        """
        if class_name in self.loaded_components:
            return self.loaded_components[class_name]
        mod = importlib.import_module("scc.gui.ae.%s" % (class_name,))
        for x in mod.__all__:
            cls = getattr(mod, x)
            if isinstance(cls, (type, types.ClassType)) and issubclass(cls, AEComponent):
                if cls is not AEComponent:
                    instance = cls(self.app, self)
                    self.loaded_components[class_name] = instance
                    self.components.append(instance)
                    return instance
install_package.py 文件源码 项目:ExcelToCode 作者: youlanhai 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def check_plugin(plugins):
    need_restart = False
    for name in plugins:
        try:
            importlib.import_module(name)
        except ImportError, e:
            print "??????????'%s'??????? ..." % (name, )

            ret = install(name)
            print "-" * 60
            print "????%s? '%s'" % ("??" if ret else "??", name, )

            if not ret: return False

            need_restart = True

    if need_restart: print "???????"
    return True
__init__.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def import_exploit(path):
    """ Import exploit module

    :param path: absolute path to exploit e.g. routersploit.modules.exploits.asus.pass_bypass
    :return: exploit module or error
    """
    try:
        module = importlib.import_module(path)
        return getattr(module, 'Exploit')
    except (ImportError, AttributeError, KeyError) as err:
        raise RoutersploitException(
            "Error during loading '{}'\n\n"
            "Error: {}\n\n"
            "It should be valid path to the module. "
            "Use <tab> key multiple times for completion.".format(humanize_path(path), err)
        )
__init__.py 文件源码 项目:drift 作者: dgnorth 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def do_execute_cmd(argv):
    valid_commands = get_commands()
    parser = argparse.ArgumentParser(description="")
    parser.add_argument("-v", "--verbose", help="I am verbose!", action="store_true")
    parser.add_argument("-t", "--tier", help="Tier to use (overrides drift_TIER from environment)")
    subparsers = parser.add_subparsers(help="sub-command help")
    for cmd in valid_commands:
        module = importlib.import_module("drift.management.commands." + cmd)
        subparser = subparsers.add_parser(cmd, help="Subcommands for {}".format(cmd))
        if hasattr(module, "get_options"):
            module.get_options(subparser)
        subparser.set_defaults(func=module.run_command)

    args = parser.parse_args(argv)

    if args.tier:
        os.environ["drift_TIER"] = args.tier

    args.func(args)
generate.py 文件源码 项目:latplan 作者: guicho271828 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def puzzle_longest(type='mnist', width=3, height=3):
    global output_dirs
    output_dirs = ["longest"]
    import importlib
    p = importlib.import_module('latplan.puzzles.puzzle_{}'.format(type))
    p.setup()
    ics = [
        # from Reinfield '93
        # [8,0,6,5,4,7,2,3,1], # the second instance with the longest optimal solution 31
        [3,5,6,8,4,7,2,1,0],
        # [8,7,6,0,4,1,2,5,3], # the first instance with the longest optimal solution 31
        [1,8,6,7,4,3,2,5,0],
        # [8,5,6,7,2,3,4,1,0], # the first instance with the most solutions
        [8,7,4,5,6,1,2,3,0],
        # [8,5,4,7,6,3,2,1,0], # the second instance with the most solutions
        [8,7,6,5,2,1,4,3,0],
        # [8,6,7,2,5,4,3,0,1], # the "wrong"? hardest eight-puzzle from
        [7,8,3,6,5,4,1,2,0],
        # [6,4,7,8,5,0,3,2,1], # w01fe.com/blog/2009/01/the-hardest-eight-puzzle-instances-take-31-moves-to-solve/
        [5,8,7,6,1,4,0,2,3],
    ]
    gcs = np.arange(width*height).reshape((1,width*height))
    generate(p, ics, gcs, width, height)
cli.py 文件源码 项目:monitorstack 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def process_result(results, output_format, **kwargs):
    """Render the output into the proper format."""
    module_name = 'monitorstack.common.formatters'
    method_name = 'write_{}'.format(output_format.replace('-', '_'))
    output_formatter = getattr(
        importlib.import_module(module_name),
        method_name
    )

    # Force the output formatter into a list
    if not isinstance(results, list):  # pragma: no cover
        results = [results]

    exit_code = 0
    for result in results:
        output_formatter(result)
        if result['exit_code'] != 0:
            exit_code = result['exit_code']
    else:
        sys.exit(exit_code)
model_trainers.py 文件源码 项目:triage 作者: dssg 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _train(self, matrix_store, class_path, parameters):
        """Fit a model to a training set. Works on any modeling class that
        is available in this package's environment and implements .fit

        Args:
            class_path (string) A full classpath to the model class
            parameters (dict) hyperparameters to give to the model constructor

        Returns:
            tuple of (fitted model, list of column names without label)
        """
        module_name, class_name = class_path.rsplit(".", 1)
        module = importlib.import_module(module_name)
        cls = getattr(module, class_name)
        instance = cls(**parameters)
        y = matrix_store.labels()

        return instance.fit(matrix_store.matrix, y), matrix_store.matrix.columns
validate.py 文件源码 项目:triage 作者: dssg 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def run(self, grid_config):
        for classpath, parameter_config in grid_config.items():
            try:
                module_name, class_name = classpath.rsplit(".", 1)
                module = importlib.import_module(module_name)
                cls = getattr(module, class_name)
                for parameters in ParameterGrid(parameter_config):
                    try:
                        cls(**parameters)
                    except Exception as e:
                        raise ValueError(dedent('''Section: grid_config -
                        Unable to instantiate classifier {} with parameters {}, error thrown: {}
                        '''.format(classpath, parameters, e)))
            except Exception as e:
                raise ValueError(dedent('''Section: grid_config -
                Unable to import classifier {}, error thrown: {}
                '''.format(classpath, e)))
cli.py 文件源码 项目:rq-scheduler-dashboard 作者: lamflam 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def make_flask_app(config, username, password, url_prefix):
    """Return Flask app with default configuration and registered blueprint."""
    app = Flask(__name__)

    # Start configuration with our built in defaults.
    app.config.from_object(default_settings)

    # Override with any settings in config file, if given.
    if config:
        app.config.from_object(importlib.import_module(config))

    # Override from a configuration file in the env variable, if present.
    if 'RQ_SCHEDULER_DASHBOARD_SETTINGS' in os.environ:
        app.config.from_envvar('RQ_SCHEDULER_DASHBOARD_SETTINGS')

    # Optionally add basic auth to blueprint and register with app.
    if username:
        add_basic_auth(blueprint, username, password)
    app.register_blueprint(blueprint, url_prefix=url_prefix)

    return app
better_apidoc.py 文件源码 项目:better-apidoc 作者: goerz 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _get_mod_ns(name, fullname, includeprivate):
    """Return the template context of module identified by `fullname` as a
    dict"""
    ns = {  # template variables
        'name': name, 'fullname': fullname, 'members': [], 'functions': [],
        'classes': [], 'exceptions': [], 'subpackages': [], 'submodules': [],
        'all_refs': [], 'members_imports': [], 'members_imports_refs': [],
        'data': []}
    p = 0
    if includeprivate:
        p = 1
    mod = importlib.import_module(fullname)
    ns['members'] = _get_members(mod)[p]
    ns['functions'] = _get_members(mod, typ='function')[p]
    ns['classes'] = _get_members(mod, typ='class')[p]
    ns['exceptions'] = _get_members(mod, typ='exception')[p]
    ns['all_refs'] = _get_members(mod, include_imported=True, in__all__=True, as_refs=True)[p]
    ns['members_imports'] = _get_members(mod, include_imported=True)[p]
    ns['members_imports_refs'] = _get_members(mod, include_imported=True, as_refs=True)[p]
    ns['data'] = _get_members(mod, typ='data')[p]
    return ns
configure.py 文件源码 项目:artman 作者: googleapis 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def _configure_publish(publish=None):
    """Determine and return the default publisher.

    Args:
        publish (str): The current default publisher (may be None).

    Returns:
        str: The new default publisher.
    """
    # Set up publishing defaults.
    logger.info('Where do you want to publish code by default?')
    logger.info('The common valid options are "github" and "local".')
    publish = six.moves.input('Default publisher: ').lower()
    try:
        importlib.import_module('artman.tasks.publish.%s' % publish)
        return publish
    except ImportError:
        logger.error('Invalid publisher.')
        return _configure_publish()
code_generation.py 文件源码 项目:artman 作者: googleapis 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _get_publish_tasks(self, publish, **kwargs):
        """Dynamically import publisher tasks based on the selected publisher.

        This will raise ImportError if the publisher does not have a module
        in `pipeline.tasks.publish`.

        Args:
            publish (str): A string of a publisher in pipeline.tasks.publish.*.

        Returns:
            list: A list of Task subclasses defined by the publisher module.
        """
        module = importlib.import_module(
            'artman.tasks.publish.{}'.format(publish),
        )
        return module.TASKS
build.py 文件源码 项目:EMFT 作者: 132nd-etcher 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def ensure_module(module_name: str):
    """
    Makes sure that a module is importable.

    In case the module cannot be found, print an error and exit.

    Args:
        module_name: name of the module to look for
    """
    try:
        importlib.import_module(module_name)
    except ModuleNotFoundError:
        click.secho(
            f'Module not found: {module_name}\n'
            f'Install it manually with: "pip install {module_name}"\n'
            f'Or install all dependencies with: "pip install -r requirements-dev.txt"',
            fg='red', err=True)
        exit(-1)


问题


面经


文章

微信
公众号

扫码关注公众号