• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python __import__函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中__import__函数的典型用法代码示例。如果您正苦于以下问题:Python __import__函数的具体用法?Python __import__怎么用?Python __import__使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: init_func

    def init_func(self, creator_fd, raw_socket_fd, tun_fd, cs, caddr, debug=True):
        self.__debug = debug
        self.__caddr = caddr

        name = "freenet.lib.crypto.%s" % fns_config.configs["tcp_crypto_module"]["name"]
        __import__(name)

        crypto = sys.modules[name]

        args = fns_config.configs["tcp_crypto_module"]["args"]

        self.__encrypt = crypto.encrypt(*args)
        self.__decrypt = crypto.decrypt(*args)
        self.__creator_fd = creator_fd
        self.__traffic_send_fd = raw_socket_fd
        self.__vlan_ips = []
        self.__udp_natp_to_fd = {}
        self.__tun_fd = tun_fd

        self.set_socket(cs)

        self.register(self.fileno)
        self.add_evt_read(self.fileno)

        self.set_timeout(self.fileno, self.__TIMEOUT_NO_AUTH)
        self.print_access_log("connect")

        return self.fileno
开发者ID:alexliyu,项目名称:fdslight,代码行数:28,代码来源:tunnels_tcp_base.py


示例2: get_versions

def get_versions(module_list=None):
    if not module_list:
        return {}

    ext_module_list = set()
    for m in module_list:
        parts = m.split('.')
        ext_module_list.update('.'.join(parts[:idx])
                               for idx in range(1, len(parts) + 1))

    versions = {}
    for module_name in ext_module_list:
        if module_name not in _VERSION_CACHE:
            try:
                __import__(module_name)
            except ImportError:
                continue

            try:
                app = sys.modules[module_name]
            except KeyError:
                continue

            try:
                version = get_version_from_app(module_name, app)
            except Exception as e:
                logger.exception(e)
                version = None

            _VERSION_CACHE[module_name] = version
        else:
            version = _VERSION_CACHE[module_name]
        if version is not None:
            versions[module_name] = version
    return versions
开发者ID:inasafe,项目名称:inasafe,代码行数:35,代码来源:__init__.py


示例3: wrap

    def wrap(f):
        if modules:
            # attach import to function
            setattr(f, 'imports', modules)
            for alternatives in modules:
                # alternatives are comma seperated
                alternatives = alternatives.split(',')
                # we import the part of the import X.Y.Z -> Z
                mod_name = alternatives[0].split('.')[-1]
                for mod in alternatives:
                    mod = mod.strip().split('.')

                    try:
                        if len(mod) == 1:
                            module = __import__(mod[0])
                        else:
                            module = getattr(__import__('.'.join(mod[:-1]), \
                                            fromlist=[mod[-1]]), mod[-1])
                        f.func_globals[mod_name] = module
                        break # import only one
                    except ImportError:
                        pass
                else:
                    if forgive: # no break -> no import
                        warnings.warn('Failed to import %s' % alternatives)
                    else:
                        raise ImportError('Failed to import %s' % alternatives)
        return f
开发者ID:mcieslik-mctp,项目名称:papy,代码行数:28,代码来源:NuMap.py


示例4: module_exists

def module_exists(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return False
    else:
        return True
开发者ID:biomodels,项目名称:MODEL1204280021,代码行数:7,代码来源:model.py


示例5: load_module

def load_module(module_name):
  """Imports a module given its name and returns a handle to it."""
  try:
    __import__(module_name)
  except ImportError:
    raise ImportError('No module named %s' % module_name)
  return sys.modules[module_name]
开发者ID:AnkurDedania,项目名称:watchdog,代码行数:7,代码来源:__init__.py


示例6: wrap

 def wrap(*args, **kwargs):
     __import__('time').sleep(seconds)
     try:
         result = target(*args, **kwargs)
     except:
         result = None
     return result
开发者ID:GitHublong,项目名称:XX-Net,代码行数:7,代码来源:gae_handler.py


示例7: import_module

def import_module(module_name):
    """
    Imports a module. A single point of truth for importing modules to
    be documented by `pdoc`. In particular, it makes sure that the top
    module in `module_name` can be imported by using only the paths in
    `pdoc.import_path`.

    If a module has already been imported, then its corresponding entry
    in `sys.modules` is returned. This means that modules that have
    changed on disk cannot be re-imported in the same process and have
    its documentation updated.
    """
    if import_path != sys.path:
        # Such a kludge. Only restrict imports if the `import_path` has
        # been changed. We don't want to always restrict imports, since
        # providing a path to `imp.find_module` stops it from searching
        # in special locations for built ins or frozen modules.
        #
        # The problem here is that this relies on the `sys.path` not being
        # independently changed since the initialization of this module.
        # If it is changed, then some packages may fail.
        #
        # Any other options available?

        # Raises an exception if the parent module cannot be imported.
        # This hopefully ensures that we only explicitly import modules
        # contained in `pdoc.import_path`.
        imp.find_module(module_name.split('.')[0], import_path)

    if module_name in sys.modules:
        return sys.modules[module_name]
    else:
        __import__(module_name)
        return sys.modules[module_name]
开发者ID:knadh,项目名称:pdoc,代码行数:34,代码来源:__init__.py


示例8: getargs

    def getargs(self,moduleName,className,method) :
        '''
          This will return the list of arguments in a method of python module of class.
          It accepts method list as an argument.
        '''
        print "Message : Argument list is being obtained for each method"
        methodArgsDict = {}
        if className == None:
            moduleList = moduleName.split(".")
            for index,name in enumerate(method) :
                Module = __import__(moduleList[len(moduleList) -1], globals(), locals(), [moduleList[len(moduleList) -2]], -1)
                try :
                    names = vars(Module)[name]
                except KeyError:
                    print "Message : method '" + name + "'does not exists,Continued with including it. "
                    return False
                argumentList = inspect.getargspec(names) #inspect.getargvalues(name)
                methodArgsDict[name] = argumentList[0]
        else :
            moduleList = moduleName.split(".")
            for index,name in enumerate(method) :
                Module = __import__(moduleList[len(moduleList) - 1], globals(), locals(), [className], -1)
                Class = getattr(Module, className)
                try :
                    names = vars(Class)[name]
                except KeyError :
                    print "Message : method '" + name + "'does not exists,Continued with include it."
                    return False

                argumentList = inspect.getargspec(names) #inspect.getargvalues(name)
                methodArgsDict[name] = argumentList[0]

        return methodArgsDict
开发者ID:AntonySilvester,项目名称:OnosSystemTest,代码行数:33,代码来源:updatedriver.py


示例9: check_config

def check_config(dbdriver, dbtype, dbhost, dbuser, dbpasswd, testdb):
    global DBDRIVER, DBTYPE, DBHOST, DBUSER, DBPASSWD, TESTDB, DBSCHEMA, SQL_FILE
    DBDRIVER = dbdriver
    DBTYPE = dbtype
    DBHOST = dbhost
    DBUSER = dbuser
    DBPASSWD = dbpasswd
    TESTDB = testdb

    #Check the database driver is installed:
    try:
        __import__(DBDRIVER)
    except ImportError:
        message = "Install %s if you want to use %s with BioSQL " % (DBDRIVER, DBTYPE)
        raise MissingExternalDependencyError(message)

    try:
        if DBDRIVER in ["sqlite3"]:
            server = BioSeqDatabase.open_database(driver = DBDRIVER, db = TESTDB)
        else:
            server = BioSeqDatabase.open_database(driver = DBDRIVER,
                                                  user = DBUSER, passwd = DBPASSWD,
                                                  host = DBHOST)
            server.close()
            del server
    except Exception, e:
        message = "Connection failed, check settings if you plan to use BioSQL: %s" % str(e)
        raise MissingExternalDependencyError(message)
开发者ID:BioinformaticsArchive,项目名称:biopython,代码行数:28,代码来源:common_BioSQL.py


示例10: test_package_import__semantics

    def test_package_import__semantics(self):

        # Generate a couple of broken modules to try importing.

        # ...try loading the module when there's a SyntaxError
        self.rewrite_file('for')
        try: __import__(self.module_name)
        except SyntaxError: pass
        else: raise RuntimeError, 'Failed to induce SyntaxError'
        self.assertNotIn(self.module_name, sys.modules)
        self.assertFalse(hasattr(sys.modules[self.package_name], 'foo'))

        # ...make up a variable name that isn't bound in __builtins__
        var = 'a'
        while var in dir(__builtins__):
            var += random.choose(string.letters)

        # ...make a module that just contains that
        self.rewrite_file(var)

        try: __import__(self.module_name)
        except NameError: pass
        else: raise RuntimeError, 'Failed to induce NameError.'

        # ...now  change  the module  so  that  the NameError  doesn't
        # happen
        self.rewrite_file('%s = 1' % var)
        module = __import__(self.module_name).foo
        self.assertEqual(getattr(module, var), 1)
开发者ID:BillyboyD,项目名称:main,代码行数:29,代码来源:test_pkgimport.py


示例11: getmethods

    def getmethods(self,modulePath,Class) :
        '''
         This will get the list of methods in given module or class.
         It accepts the module path and class name. If there is no
         class name then it has be mentioned as None.
        '''
        methodList = []
        moduleList = modulePath.split("/")
        newModule = ".".join([moduleList[len(moduleList) - 2],moduleList[len(moduleList) - 1]])
        print "Message : Method list is being obatined , Please wait ..."
        try :
            if Class :
                Module = __import__(moduleList[len(moduleList) - 1], globals(), locals(), [Class], -1)
                ClassList = [x.__name__ for x in Module.__dict__.values() if inspect.isclass(x)]
                self.ClassList = ClassList
                Class = vars(Module)[Class]
                methodList = [x.__name__ for x in Class.__dict__.values() if inspect.isfunction(x)]
            else :
                Module = __import__(moduleList[len(moduleList) - 1], globals(), locals(),[moduleList[len(moduleList) - 2]], -1)
                methodList = [x.__name__ for x in Module.__dict__.values() if inspect.isfunction(x)]
                ClassList = [x.__name__ for x in Module.__dict__.values() if inspect.isclass(x)]
                self.ClassList = ClassList
        except :
            print "Error : " +str(sys.exc_info()[1])


        self.method = methodList
        return self.method
开发者ID:AntonySilvester,项目名称:OnosSystemTest,代码行数:28,代码来源:updatedriver.py


示例12: main

def main(listener_fd, alive_r, preload, main_path=None, sys_path=None):
    '''Run forkserver.'''
    if preload:
        if '__main__' in preload and main_path is not None:
            process.current_process()._inheriting = True
            try:
                spawn.import_main_path(main_path)
            finally:
                del process.current_process()._inheriting
        for modname in preload:
            try:
                __import__(modname)
            except ImportError:
                pass

    util._close_stdin()

    # ignoring SIGCHLD means no need to reap zombie processes
    # letting SIGINT through avoids KeyboardInterrupt tracebacks
    handlers = {
        signal.SIGCHLD: signal.SIG_IGN,
        signal.SIGINT: signal.SIG_DFL,
        }
    old_handlers = {sig: signal.signal(sig, val)
                    for (sig, val) in handlers.items()}

    with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \
         selectors.DefaultSelector() as selector:
        _forkserver._forkserver_address = listener.getsockname()

        selector.register(listener, selectors.EVENT_READ)
        selector.register(alive_r, selectors.EVENT_READ)

        while True:
            try:
                while True:
                    rfds = [key.fileobj for (key, events) in selector.select()]
                    if rfds:
                        break

                if alive_r in rfds:
                    # EOF because no more client processes left
                    assert os.read(alive_r, 1) == b''
                    raise SystemExit

                assert listener in rfds
                with listener.accept()[0] as s:
                    code = 1
                    if os.fork() == 0:
                        try:
                            _serve_one(s, listener, alive_r, old_handlers)
                        except Exception:
                            sys.excepthook(*sys.exc_info())
                            sys.stderr.flush()
                        finally:
                            os._exit(code)

            except OSError as e:
                if e.errno != errno.ECONNABORTED:
                    raise
开发者ID:uqfoundation,项目名称:multiprocess,代码行数:60,代码来源:forkserver.py


示例13: import_backends

def import_backends():
    """
    Import files in the duplicity/backends directory where
    the filename ends in 'backend.py' and ignore the rest.

    @rtype: void
    @return: void
    """
    path = duplicity.backends.__path__[0]
    assert path.endswith("duplicity/backends"), duplicity.backends.__path__

    files = os.listdir(path)
    files.sort()
    for fn in files:
        if fn.endswith("backend.py"):
            fn = fn[:-3]
            imp = "duplicity.backends.%s" % (fn,)
            try:
                __import__(imp)
                res = "Succeeded"
            except Exception:
                res = "Failed: " + str(sys.exc_info()[1])
            log.Log(_("Import of %s %s") % (imp, res), log.INFO)
        else:
            continue
开发者ID:mjuric,项目名称:duplicity,代码行数:25,代码来源:backend.py


示例14: get_config

def get_config(config_path):
    __import__('errbot.config-template')  # - is on purpose, it should not be imported normally ;)
    template = sys.modules['errbot.config-template']
    config_fullpath = config_path
    if not path.exists(config_fullpath):
        log.error(
            'I cannot find the file %s \n'
            '(You can change this path with the -c parameter see --help)' % config_path
        )
        log.info(
            'You can use the template %s as a base and copy it to %s. \nYou can then customize it.' % (
                path.dirname(template.__file__) + sep + 'config-template.py', config_path + sep)
        )
        exit(-1)

    # noinspection PyBroadException
    try:
        config = __import__(path.splitext(path.basename(config_fullpath))[0])

        diffs = [item for item in set(dir(template)) - set(dir(config)) if not item.startswith('_')]
        if diffs:
            log.error('You are missing configs defined from the template :')
            for diff in diffs:
                log.error('Missing config : %s' % diff)
            exit(-1)
    except Exception as _:
        log.exception('I could not import your config from %s, please check the error below...' % config_fullpath)
        exit(-1)
    log.info('Config check passed...')
    return config
开发者ID:rroemhild,项目名称:err,代码行数:30,代码来源:err.py


示例15: find_controller

    def find_controller(self, controller):
        """Locates a controller by attempting to import it then grab
        the SomeController instance from the imported module.

        Override this to change how the controller object is found once
        the URL has been resolved.

        """
        # Check to see if we've cached the class instance for this name
        if controller in self.controller_classes:
            return self.controller_classes[controller]

        # Pull the controllers class name, import controller
        full_module_name = self.package_name + '.controllers.' \
            + controller.replace('/', '.')

        # Hide the traceback here if the import fails (bad syntax and such)
        __traceback_hide__ = 'before_and_this'

        __import__(full_module_name)
        if hasattr(sys.modules[full_module_name], '__controller__'):
            mycontroller = getattr(
                sys.modules[full_module_name],
                sys.modules[full_module_name].__controller__)
        else:
            module_name = controller.split('/')[-1]
            class_name = class_name_from_module_name(module_name) + \
                'Controller'
            if self.log_debug:
                log.debug("Found controller, module: '%s', class: '%s'",
                          full_module_name, class_name)
            mycontroller = getattr(sys.modules[full_module_name], class_name)
        self.controller_classes[controller] = mycontroller
        return mycontroller
开发者ID:solos,项目名称:pylons,代码行数:34,代码来源:wsgiapp.py


示例16: import_app

def import_app(module):
    parts = module.split(":", 1)
    if len(parts) == 1:
        module, obj = module, "application"
    else:
        module, obj = parts[0], parts[1]

    try:
        __import__(module)
    except ImportError:
        if module.endswith(".py") and os.path.exists(module):
            raise ImportError("Failed to find application, did "
                "you mean '%s:%s'?" % (module.rsplit(".", 1)[0], obj))
        else:
            raise

    mod = sys.modules[module]

    try:
        app = eval(obj, mod.__dict__)
    except NameError:
        raise AppImportError("Failed to find application: %r" % module)

    if app is None:
        raise AppImportError("Failed to find application object: %r" % obj)

    return app
开发者ID:pr65536,项目名称:culexx,代码行数:27,代码来源:util.py


示例17: load_plugins

    def load_plugins(cls, modules, config, debug=None):
        """Load plugins from `modules`.

        Returns a list of loaded and configured plugins.

        """
        plugins = cls()
        plugins.debug = debug

        for module in modules:
            plugins.current_module = module
            __import__(module)
            mod = sys.modules[module]

            coverage_init = getattr(mod, "coverage_init", None)
            if not coverage_init:
                raise CoverageException(
                    "Plugin module %r didn't define a coverage_init function" % module
                )

            options = config.get_plugin_options(module)
            coverage_init(plugins, options)

        plugins.current_module = None
        return plugins
开发者ID:silviot,项目名称:coveragepy,代码行数:25,代码来源:plugin_support.py


示例18: setup

 def setup(self):
     try:
         __import__('multiprocessing')
     except ImportError:
         raise SkipTest('multiprocessing not supported')
     from celery.concurrency.prefork import TaskPool
     self.TaskPool = TaskPool
开发者ID:OnShift,项目名称:celery,代码行数:7,代码来源:test_pool.py


示例19: init_app

def init_app(app):
    # Load all core APIs
    import udata.core.spatial.api
    import udata.core.metrics.api
    import udata.core.user.api
    import udata.core.dataset.api
    import udata.core.issues.api
    import udata.core.discussions.api
    import udata.core.reuse.api
    import udata.core.organization.api
    import udata.core.followers.api
    import udata.core.jobs.api
    import udata.core.site.api
    import udata.core.tags.api
    import udata.core.topic.api
    import udata.core.post.api
    import udata.features.transfer.api

    # Load plugins API
    for plugin in app.config['PLUGINS']:
        name = 'udata.ext.{0}.api'.format(plugin)
        try:
            __import__(name)
        except ImportError:
            pass
        except Exception as e:
            log.error('Error importing %s: %s', name, e)

    # api.init_app(app)
    app.register_blueprint(apidoc)
    app.register_blueprint(apiv1)

    oauth2.init_app(app)
开发者ID:grouan,项目名称:udata,代码行数:33,代码来源:__init__.py


示例20: load_plugins

def load_plugins():
    with open(__config_file__, "r") as fh:
        for line in fh:
            line = line.strip()
            if line.startswith("#") or line == "":
                continue
            # just load the whole shit...
            try:
                __import__(pluginPath+"."+line,  globals(), locals(), [], -1)
            except NecessaryModuleNotFound as e:
                logger.critical("Failed loading plugin due to missing module: "+str(e))
            except ApiKeyNotFoundException as e:
                logger.critical("Failed loading plugin due to missing API key: "+str(e))
            except:
                logger.exception("Plugin loading failed")
            
    # as they are loaded in the order in the file we will have the same order in __subclasses__()... I hope

    for clazz in Plugin.__subclasses__():
        # look at all functions of a class lets filter them first
        methods = filter(lambda x: type(x) == FunctionType, clazz.__dict__.values())
        # now we check if the method is decorated by register
        for method in methods:
            if __criteria_key__ in method.__dict__:
                criterias = method.__dict__[__criteria_key__]
                for lang, regex in criterias.items():
                    if not lang in plugins:
                        plugins[lang] = []
                    # yeah... save the regex, the clazz and the method, shit just got loaded...
                    plugins[lang].append((regex, clazz, method))
开发者ID:sullenlook,项目名称:Siriserver-Windows,代码行数:30,代码来源:PluginManager.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python abs函数代码示例发布时间:2022-05-24
下一篇:
Python cmd.count_atoms函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap