当前位置: 首页>>代码示例>>Python>>正文


Python importlib.import_module方法代码示例

本文整理汇总了Python中importlib.import_module方法的典型用法代码示例。如果您正苦于以下问题:Python importlib.import_module方法的具体用法?Python importlib.import_module怎么用?Python importlib.import_module使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在importlib的用法示例。


在下文中一共展示了importlib.import_module方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: enable_plugin

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def enable_plugin(self, plugin):
        """Enable a ingester plugin for use parsing design documents.

        :params plugin: - A string naming a class object denoting the ingester plugin to be enabled
        """
        if plugin is None or plugin == '':
            self.log.error("Cannot have an empty plugin string.")

        try:
            (module, x, classname) = plugin.rpartition('.')

            if module == '':
                raise Exception()
            mod = importlib.import_module(module)
            klass = getattr(mod, classname)
            self.registered_plugin = klass()
        except Exception as ex:
            self.logger.error(
                "Could not enable plugin %s - %s" % (plugin, str(ex)))

        if self.registered_plugin is None:
            self.logger.error("Could not enable at least one plugin")
            raise Exception("Could not enable at least one plugin") 
开发者ID:airshipit,项目名称:drydock,代码行数:25,代码来源:ingester.py

示例2: load_module

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def load_module(self, fullname):
        print('load_module {}'.format(fullname))
        if fullname in sys.modules:
            return sys.modules[fullname]

        # 先从 sys.meta_path 中删除自定义的 finder
        # 防止下面执行 import_module 的时候再次触发此 finder
        # 从而出现递归调用的问题
        finder = sys.meta_path.pop(0)
        # 导入 module
        module = importlib.import_module(fullname)

        module_hook(fullname, module)

        sys.meta_path.insert(0, finder)
        return module 
开发者ID:mozillazg,项目名称:apm-python-agent-principle,代码行数:18,代码来源:_hook.py

示例3: register_all

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def register_all():
    # NOTE(sh8121att) - Import all versioned objects so
    # they are available via RPC. Any new object definitions
    # need to be added here.
    importlib.import_module('drydock_provisioner.objects.network')
    importlib.import_module('drydock_provisioner.objects.node')
    importlib.import_module('drydock_provisioner.objects.hostprofile')
    importlib.import_module('drydock_provisioner.objects.hwprofile')
    importlib.import_module('drydock_provisioner.objects.site')
    importlib.import_module('drydock_provisioner.objects.promenade')
    importlib.import_module('drydock_provisioner.objects.rack')
    importlib.import_module('drydock_provisioner.objects.bootaction')
    importlib.import_module('drydock_provisioner.objects.task')
    importlib.import_module('drydock_provisioner.objects.builddata')
    importlib.import_module('drydock_provisioner.objects.validation')


# Utility class for calculating inheritance 
开发者ID:airshipit,项目名称:drydock,代码行数:20,代码来源:__init__.py

示例4: load_project

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def load_project(project_name):
    # load project and check that it looks okay
    try:
        importlib.import_module(project_name)
    except ImportError as e:
        try:
            #TODO: relative module imports in a projects/Project will fail for some reason
            importlib.import_module("projects.%s" % project_name)
        except ImportError as e:
            log.error("Failed to import project %s", project_name, exc_info=1)
            sys.exit(1)
    if len(_registered) != 1:
        log.error("Project must register itself using alf.register(). "
                  "%d projects registered, expecting 1.", len(_registered))
        sys.exit(1)
    project_cls = _registered.pop()
    if not issubclass(project_cls, Fuzzer):
        raise TypeError("Expecting a Fuzzer, not '%s'" % type(project_cls))
    return project_cls 
开发者ID:blackberry,项目名称:ALF,代码行数:21,代码来源:local.py

示例5: __init__

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def __init__(self,
        name=None,          # Network name. Used to select TensorFlow name and variable scopes.
        func=None,          # Fully qualified name of the underlying network construction function.
        **static_kwargs):   # Keyword arguments to be passed in to the network construction function.

        self._init_fields()
        self.name = name
        self.static_kwargs = dict(static_kwargs)

        # Init build func.
        module, self._build_func_name = import_module(func)
        self._build_module_src = inspect.getsource(module)
        self._build_func = find_obj_in_module(module, self._build_func_name)

        # Init graph.
        self._init_graph()
        self.reset_vars() 
开发者ID:zalandoresearch,项目名称:disentangling_conditional_gans,代码行数:19,代码来源:tfutil.py

示例6: add_step

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def add_step(self,module_name_and_params, extra_args):
        config=module_name_and_params.split()
        module_name=config[0]
        params=config[1:]

        # collect extra arguments from command line meant for this particular module
        if extra_args is not None: 
            for _name, _value in extra_args.__dict__.items():
                if _name.startswith(module_name):
                    _modname,_argname=_name.split(".",1) # for example lemmatizer_mod.gpu
                    params.append("--"+_argname)
                    params.append(str(_value))

        mod=importlib.import_module(module_name)
        step_in=self.q_out
        self.q_out=Queue(self.max_q_size) #new pipeline end
        args=mod.argparser.parse_args(params)
        process=Process(target=mod.launch,args=(args,step_in,self.q_out))
        process.daemon=True
        process.start()
        self.processes.append(process) 
开发者ID:TurkuNLP,项目名称:Turku-neural-parser-pipeline,代码行数:23,代码来源:pipeline.py

示例7: get_model_function

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def get_model_function(model_type):
    """
        Get tensorflow function of the model to be applied to the input tensor.
        For instance "unet.softmax_unet" will return the softmax_unet function
        in the "unet.py" submodule of the current module (spleeter.model).

        Params:
        - model_type: str
        the relative module path to the model function.

        Returns:
        A tensorflow function to be applied to the input tensor to get the
        multitrack output.
    """
    relative_path_to_module = '.'.join(model_type.split('.')[:-1])
    model_name = model_type.split('.')[-1]
    main_module = '.'.join((__name__, 'functions'))
    path_to_module = f'{main_module}.{relative_path_to_module}'
    module = importlib.import_module(path_to_module)
    model_function = getattr(module, model_name)
    return model_function 
开发者ID:deezer,项目名称:spleeter,代码行数:23,代码来源:__init__.py

示例8: _import_channel

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def _import_channel(channel_alias):
    """
    helper to import channels aliases from string paths.

    raises an AttributeError if a channel can't be found by it's alias
    """
    try:
        channel_path = settings.NOTIFICATIONS_CHANNELS[channel_alias]
    except KeyError:
        raise AttributeError(
            '"%s" is not a valid delivery channel alias. '
            'Check your applications settings for NOTIFICATIONS_CHANNELS'
            % channel_alias
        )
    package, attr = channel_path.rsplit('.', 1)

    return getattr(importlib.import_module(package), attr) 
开发者ID:danidee10,项目名称:django-notifs,代码行数:19,代码来源:tasks.py

示例9: use_of_force

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def use_of_force():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    uof_class = getattr(importlib.import_module("comport.data.models"), "UseOfForceIncident{}".format(department.short_name))

    for incident in request_json['data']:
        added = uof_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
开发者ID:codeforamerica,项目名称:comport,代码行数:23,代码来源:views.py

示例10: officer_involved_shooting

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def officer_involved_shooting():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    ois_class = getattr(importlib.import_module("comport.data.models"), "OfficerInvolvedShooting{}".format(department.short_name))

    for incident in request_json['data']:
        added = ois_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
开发者ID:codeforamerica,项目名称:comport,代码行数:23,代码来源:views.py

示例11: complaints

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def complaints():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    complaint_class = getattr(importlib.import_module("comport.data.models"), "CitizenComplaint{}".format(department.short_name))

    for incident in request_json['data']:
        added = complaint_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
开发者ID:codeforamerica,项目名称:comport,代码行数:23,代码来源:views.py

示例12: pursuits

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def pursuits():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    pursuit_class = getattr(importlib.import_module("comport.data.models"), "Pursuit{}".format(department.short_name))

    for incident in request_json['data']:
        added = pursuit_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
开发者ID:codeforamerica,项目名称:comport,代码行数:23,代码来源:views.py

示例13: assaults

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def assaults():
    username = request.authorization.username
    extractor = Extractor.query.filter_by(username=username).first()
    department = extractor.first_department()
    request_json = request.json
    added_rows = 0
    updated_rows = 0

    assaults_class = getattr(importlib.import_module("comport.data.models"), "AssaultOnOfficer{}".format(department.short_name))

    for incident in request_json['data']:
        added = assaults_class.add_or_update_incident(department, incident)
        if added is True:
            added_rows += 1
        elif added is False:
            updated_rows += 1

    extractor.next_month = None
    extractor.next_year = None
    extractor.save()
    return json.dumps({"added": added_rows, "updated": updated_rows}) 
开发者ID:codeforamerica,项目名称:comport,代码行数:23,代码来源:views.py

示例14: _make_context

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def _make_context():
    ''' Return context dict for a shell session.
    '''
    # generate a list of all the incident classes
    class_lookup = [
        {"UseOfForceIncident": ["IMPD", "BPD", "LMPD"]},
        {"CitizenComplaint": ["IMPD", "BPD"]},
        {"OfficerInvolvedShooting": ["IMPD", "BPD"]},
        {"AssaultOnOfficer": ["IMPD"]}
    ]
    incident_classes = {}
    for guide in class_lookup:
        prefix, departments = guide.popitem()
        for name in departments:
            class_name = prefix + name
            incident_classes[class_name] = getattr(importlib.import_module("comport.data.models"), class_name)

    context = {'app': app, 'db': db, 'User': User, 'Department': Department, 'Extractor': Extractor, 'IncidentsUpdated': IncidentsUpdated, 'JSONTestClient': JSONTestClient}
    # update the context with the incident classes
    context.update(incident_classes)

    return context 
开发者ID:codeforamerica,项目名称:comport,代码行数:24,代码来源:manage.py

示例15: test_csv_filtered_by_dept

# 需要导入模块: import importlib [as 别名]
# 或者: from importlib import import_module [as 别名]
def test_csv_filtered_by_dept(self, testapp):
        # create a department
        department1 = Department.create(name="IM Police Department", short_name="IMPD", load_defaults=False)
        department2 = Department.create(name="B Police Department", short_name="BPD", load_defaults=False)

        incidentclass1 = getattr(importlib.import_module("comport.data.models"), "UseOfForceIncident{}".format(department1.short_name))
        incidentclass2 = getattr(importlib.import_module("comport.data.models"), "UseOfForceIncident{}".format(department2.short_name))

        incidentclass1.create(opaque_id="123ABC", department_id=department1.id)
        incidentclass2.create(opaque_id="123XYZ", department_id=department2.id)

        response1 = testapp.get("/department/{}/uof.csv".format(department1.id))
        response2 = testapp.get("/department/{}/uof.csv".format(department2.id))

        incidents1 = list(csv.DictReader(io.StringIO(response1.text)))
        incidents2 = list(csv.DictReader(io.StringIO(response2.text)))

        assert len(incidents1) == 1 and len(incidents2) == 1
        assert incidents1[0]['id'] == '123ABC' and incidents2[0]['id'] == '123XYZ' 
开发者ID:codeforamerica,项目名称:comport,代码行数:21,代码来源:test_functional.py


注:本文中的importlib.import_module方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。