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

Python pyclbr.readmodule函数代码示例

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

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



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

示例1: get_pyclbr

    def get_pyclbr ( self ):
        if not self.cache:
            return pyclbr.readmodule( self.full_name, [ self.parent.path ] )

        pyclbr_name = join( self.parent.path, self.name + '.pyclbr' )
        if exists( pyclbr_name ):
            pyclbr_stat = stat( pyclbr_name )
            py_stat     = stat( self.path )
            if pyclbr_stat.st_mtime >= py_stat.st_mtime:
                try:
                    file = open( pyclbr_name, 'rb' )
                    try:
                        dic = load( file )
                    finally:
                        file.close()
                    return dic
                except:
                    pass

        dic = pyclbr.readmodule( self.full_name, [ self.parent.path ] )
        try:
            file = open( pyclbr_name, 'wb' )
            try:
                dump( dic, file )
            finally:
                file.close()
        except:
            pass

        return dic
开发者ID:enthought,项目名称:etsdevtools,代码行数:30,代码来源:class_browser.py


示例2: procesar_modulo

def procesar_modulo(file_handler, modulenames, path):
    # para guardar las declaraciones de herencia multiple pendientes: (derivada, base)
    hm = []
    #path, name = os.path.split(modname)

    clsdict = {}

    for modname in modulenames:
        if path:
            new_classes = pyclbr.readmodule(modname, [path])
        else:
            new_classes = pyclbr.readmodule(modname)

        clsdict.update(new_classes)

    clslist = clsdict.values()
    for cls in clslist:
        cls.super = sorted(s.name if hasattr(s, 'name') else s for s in cls.super)
    # las bases primero, queda mejor :)
    clslist.sort(key=lambda c:(len(c.super), c.super))
    for cls in clslist:
        if cls.name not in clsdict:
            continue
        procesar_cls(file_handler, cls, clsdict, hm)
        # herencia multiple pendiente
        # (trato de mostrarla tan pronto como sea posible)
        while hm:
            subcls, base = hm.pop(0)
            file_handler.write("%s -> %s\n" % (subcls, base))
开发者ID:hugoruscitti,项目名称:quickdiagrams,代码行数:29,代码来源:genqd.py


示例3: _get_classes_by_module_name

 def _get_classes_by_module_name(pkg_name, mod_name):
     full_mod_name = mod_name
     if pkg_name:
         full_mod_name = '.'.join((pkg_name, mod_name))
     classes = pyclbr.readmodule(full_mod_name)  # a dict of 'class_name': pyclbr.Class obj
     # TODO filter classes to get only subclasses of unittest.TestCase
     return classes
开发者ID:kaushik94,项目名称:unishark,代码行数:7,代码来源:loader.py


示例4: get_parsers_names

def get_parsers_names():
    """Returns a list of the parsers names."""

    name = os.path.splitext(os.path.basename(__file__))[0]
    list_cls_names = (pyclbr.readmodule(name).keys())

    return list_cls_names
开发者ID:DesignPatternsClub,项目名称:Design-Patterns,代码行数:7,代码来源:parsers_1.py


示例5: load_service

 def load_service(self, service_path):
     """
     Load the service class pointed to by `service_path` and return an
     object of the service.
     """
     log.debug("Loading service class in module '{0}'".format(service_path))
     module_name = os.path.splitext(os.path.basename(service_path))[0]
     module_dir = os.path.dirname(service_path)
     module = (os.path.splitext(service_path)[0]).replace('/', '.')
     # Figure out the class name for the service
     module_classes = pyclbr.readmodule(module_name, [module_dir])
     # log.debug("Module {0} classes: {1}".format(module_name, module_classes))
     service_class_name = None
     for c in module_classes.iterkeys():
         if c.lower() == ('{0}service'.format(module_name)).lower():
             service_class_name = c
             break
     # log.debug('service_class_name: %s' % service_class_name)
     # Import the service module and instantiate the service class
     service = None
     if service_class_name:
         log.debug("Importing service name {0} as module {1}".format(
                   service_class_name, module))
         service_module = importlib.import_module(module)
         service = getattr(service_module, service_class_name)(self.app)
     else:
         log.warning("Could not extract service class name from module at {0}"
                     .format(service_path))
     # log.debug("Loaded service {0}".format(service))
     return service
开发者ID:blankenberg,项目名称:cloudman,代码行数:30,代码来源:registry.py


示例6: __init__

 def __init__(self, categories, parent=None):
     super(_LgsipGatesWidget, self).__init__(parent)
     self.setRootIsDecorated(False)
     self.setItemDelegate(_Delegate())
     self.setIndentation(0)
     self.setFixedWidth(110)
     self.setExpandsOnDoubleClick(False)
     self.setDragDropMode(self.DragOnly)
     self.header().close()
     self.itemClicked.connect(self._expandCollapse)
     for name, id in categories:
         module = self._module + id.lower()
         item = QtGui.QTreeWidgetItem([name])
         self.addTopLevelItem(item)
         g = pyclbr.readmodule(module)
         for gate in g.keys():
             if gate[0] != '_':
                 subitem = QtGui.QTreeWidgetItem()
                 item.addChild(subitem)
                 module_ = __import__(module, globals(), locals(), gate)
                 widget = getattr(module_, gate)()
                 pixmap = self.createPixmap(widget)
                 subitem.setData(0, 666, pixmap)
                 subitem.setData(0, 667, gate)
                 subitem.setData(0, 668, module)
     self.expandAll()
开发者ID:KenjiTakahashi,项目名称:lgsip,代码行数:26,代码来源:treewidgets.py


示例7: create

def create(config, logger = None,  options = None):
    ''' instantiate notifiers '''
    if logger:
        logger.info("loading notifiers ...")

    if not config.has_option('notification', 'plugins'):
        return []

    plugins = config.get('notification', 'plugins')

    notifiers = []
    for modname in [ p.strip() for p in plugins.split(',') if p.strip() ]:
        mod = __import__(modname, globals(), locals(), [modname], -1)
        for clzname in pyclbr.readmodule(mod.__name__).keys():
            if clzname == 'Notifier':
                continue
            clz = getattr(mod, clzname)
            if issubclass(clz, Notifier):
                if logger: 
                    logger.info("instantiating notifier: {0}".format(clzname))
                inits = dict(config.items(clzname)) if config.has_section(clzname) else {}
                if options:
                    inits.update( options )

                notifier = clz(**inits)
                notifier.use_logger(logger)
                notifiers.append(notifier)

    return notifiers
开发者ID:DevOps-TangoMe,项目名称:BucketSyncer,代码行数:29,代码来源:notifier.py


示例8: main

def main(argv, failfast=False, test_labels=None):
    testlist = []
    for module in [name for _, name, _ in pkgutil.iter_modules([os.path.join("cms","tests")])]:
        clsmembers = pyclbr.readmodule("cms.tests.%s" % module)
        for clsname,cls in clsmembers.items():
            testlist.append(cls)

    failures = []

    for cls in testlist:
        for method, line in cls.methods.items():
            if not method.startswith('test_'):
                continue
            test = '%s.%s' % (cls.name, method)
            if not test_labels or filter(lambda x: test.find(x)>-1, test_labels):
                print("Running ",test)
                args = ['python', 'runtests.py'] + argv + [test]
                p = subprocess.Popen(args, stdout = subprocess.PIPE, stderr= subprocess.PIPE)
                output, error = p.communicate()
                if p.returncode > 0:
                    print(error)
                    if failfast:
                        sys.exit(p.returncode)
                    else:
                        failures.append(test)
                else:
                    print()
    print("Result: %s" % ('FAIL' if failures else 'OK'))
    print("%s Failures:" % len(failures))
    for failure in failures:
        print("- %s" % failure)
    sys.exit(len(failures))
开发者ID:conrado,项目名称:django-cms,代码行数:32,代码来源:runtests-isolated.py


示例9: loadPluginsFromFolderName

	def loadPluginsFromFolderName(self, folder_file):
		pluginClass = folder_file.rstrip("/")
		pluginClass_module = pluginClass.replace("/", ".")[:-3]

		pluginModule = pyclbr.readmodule(pluginClass_module)
		for name, Class in pluginModule.iteritems():
			self.loadPlugin(name, pluginClass_module)
开发者ID:valid22,项目名称:Base-Line,代码行数:7,代码来源:World.py


示例10: find_injectable_classes

def find_injectable_classes(search_paths, exclude_injectable_module_paths=None):
    modules = set()
    for path in search_paths:
        for root, dirs, fnames in os.walk(path):
            for fname in fnames:
                if fname.endswith('.py'):
                    module_path = os.path.relpath(os.path.join(root, fname), path)
                    module = module_path.replace('/', '.')[:-3]
                    fpath = os.path.join(root, fname)
                    has_import = False
                    has_decorator = False
                    with open(fpath) as f:
                        for line in f:
                            if 'dart.context.locator' in line:
                                has_import = True
                            if '@injectable' in line:
                                has_decorator = True
                            if has_import and has_decorator:
                                break
                    if has_import and has_decorator and not path_excluded(module, exclude_injectable_module_paths):
                        modules.add(module)

    for module in modules:
        class_metadata = readmodule(module)
        for class_name in class_metadata.keys():
            # the line below will load the class, which causes the @injectable code to run,
            # registering the class (assuming the module search was not a false positive)
            locate(module + '.' + class_name)

    classes_by_name = {cls.__name__: cls for cls in class_registry.classes}
    for class_name in sorted(classes_by_name.keys()):
        _logger.info('injectable class registered: %s' % class_name)

    return classes_by_name.values()
开发者ID:RetailMeNotSandbox,项目名称:dart,代码行数:34,代码来源:locator.py


示例11: toPlantUML

def toPlantUML(module, outputFile):
    if os.path.isfile(module):
        module = os.path.splitext(os.path.basename(module))[0]

    with open(outputFile, "w") as f:
        f.write(STARTUML)
        f.write(STYLE)
        title = TITLE.format(package=module)
        f.write(title)

        classDescriptors = pyclbr.readmodule(module)
        for className, classData in classDescriptors.items():
            child = className
            methods = sorted([m + "()" for m in classData.methods])
            parents = [p.name if hasattr(p, "name") else str(p) for p in classData.super]

            for parent in parents:
                relationLine = getRelationLine(parent, child)
                f.write(relationLine)

            for method in methods:
                methodLine = getMethodLine(child, method)
                f.write(methodLine)
        f.write(ENDUML)

    os.system("notepad " + outputFile)
开发者ID:cb109,项目名称:pyplantuml,代码行数:26,代码来源:py2plantuml.py


示例12: findInstrumentModule

 def findInstrumentModule(self, instrumentModuleName):
     """
     Walks down the instrument directory tree, looks for the first valid instrument module with specified name instrumentModuleName,
     and returns:
       - a tuple (module name, filename) if a valid module was found
       - or None if no valid module was found.
     instrumentModuleName is a dotted module name string possibly including '.' chars; it is NOT a filename string.
     The instrument module is considered as valid when it has the specified name and contains a definition for the class Instr.
     """
     found = None
     for (dirpath, dirnames, filenames) in os.walk(self._instrumentsRootDir):  # start walking down the directory tree and at each step
         # builds a list of all python file names (except _init__.py)
         pyFilenames = [filename for filename in filenames if (
             os.path.splitext(filename)[1] == '.py' and filename != '__init__.py')]
         pyFilenames = [os.path.splitext(filename)[0] for filename in pyFilenames]
         if instrumentModuleName in pyFilenames:
             try:
                 # build the class dictionary with the pyclbr python class browser
                 dic = pyclbr.readmodule(instrumentModuleName, [dirpath])
                 # check that the module contains a class definition Instr in the file and not through an import.
                 if 'Instr' in dic:
                     path1 = os.path.realpath(dic['Instr'].file)
                     path2 = os.path.join(os.path.realpath(dirpath), instrumentModuleName + '.py')
                     if path1 == path2:
                         found = (dic['Instr'].module, path1)
                         break  # stop the walk
             except:
                 print 'an error occured when trying to read the module.'
             finally:
                 pass
     return found
开发者ID:denisvion,项目名称:quantrolab,代码行数:31,代码来源:instrumentmgr.py


示例13: register_all_models

def register_all_models(module=None,path=None):
    """ This function registers all modules in with the django admin. 
    The module name should be a string, and defaults to 'models' and the path can be a string, list or tuple
    If you include the admin.ModelAdmin in the models.py module with the same name + Admin
    then it will register them too. Example if the model class is Pizza, then the admin model
    class would be PizzaAdmin """
    if module is None:
        module='models'
    if path is None:
        path=os.path.dirname(os.path.abspath(__file__))
        classes = pyclbr.readmodule(module,[path])
    elif type(path) is str:
        classes = pyclbr.readmodule(module,[path])
    else:
        classes = pyclbr.readmodule(module,path)
    # first make a list of string only parents
    for model in classes:
        if classes[model].super[0] in classes.values():
            classes[model].super=classes[model].super[0].super

    # make a list of admin classes
    admin_classes=[]
    for model in classes:
        for superclass in classes[model].super:
            try:
                if re.search('admin.ModelAdmin',superclass):
                    admin_classes.append(model)
            except:pass
    for model in classes:
        # now the dirty part, check that the models are classes that inherit from models.Model
        # if this inhertance is not explicit in the class call it will not be registered
        for superclass in classes[model].super:
            try:
                if re.search('models.Model',superclass):
                    try:
                        # Check to see if the modelNameAdmin is in the list of admin classes
                        test_name=model+'Admin'
                        if test_name in admin_classes:
                            exec('from %s import %s,%s'%(module,model,test_name))
                            exec('admin.site.register(%s,%s)'%(model,test_name))
                        else:
                        # this could be a from module import * above this loop
                            exec('from %s import %s'%(module,model))
                            exec('admin.site.register(%s)'%model)
                    except:raise
            except:pass
开发者ID:aricsanders,项目名称:test_site,代码行数:46,代码来源:admin.py


示例14: find_modules_with_super_class

def find_modules_with_super_class(pkg, super_class):
    for importer, modname, ispkg in pkgutil.walk_packages(pkg.__path__):
        if ispkg: continue
        import_path = "%s.%s" % (pkg.__name__, modname)
        module = pyclbr.readmodule(import_path)
        for item, val in module.items():
            if super_class.__name__ in val.super:
                yield item, import_path
开发者ID:jandob,项目名称:omniSync,代码行数:8,代码来源:packages.py


示例15: init

def init():
    global pattern_class
    for _,name,_ in pkgutil.iter_modules(path=patterns.__path__):
        module_path = 'patterns.{}'.format(name)
        module = importlib.import_module(name=module_path)
        cls_list = pyclbr.readmodule(module_path)
        for cls in cls_list:
            pattern_class.append(getattr(module,cls))
开发者ID:nemochin,项目名称:pythonlearn,代码行数:8,代码来源:main.py


示例16: find

 def find(self, path, reset=False):
     py_files = self._find_modules(path, reset=reset)
     for module_str in py_files:
         browser = pyclbr.readmodule(module_str)
         for name in browser.keys():
             obj = get_module('{}'.format(module_str), name)
             if issubclass(obj, self.superclass):
                 yield obj
开发者ID:MCRSoftwares,项目名称:RainCife-API,代码行数:8,代码来源:utils.py


示例17: is_python_module_name

def is_python_module_name(filename):
    path, name = os.path.split(filename)
    try:
        clsdict = pyclbr.readmodule(name, path)
    except ImportError:
        return False

    return True
开发者ID:hugoruscitti,项目名称:quickdiagrams,代码行数:8,代码来源:genqd.py


示例18: retrieve_migrations

    def retrieve_migrations(self):
        if self.migrations_module is not None:
            class_names = pyclbr.readmodule(self.migrations_mstr).keys()

            for name in class_names:
                if name != 'Migration' and 'Migration' in name:
                    cobject = getattr(self.migrations_module, name)
                    self.migrations.append(cobject)
开发者ID:aacanakin,项目名称:glim-extensions,代码行数:8,代码来源:migration.py


示例19: get_parsers_names

def get_parsers_names():
    """Returns a list of the parsers names, whith no Base classes."""

    name = os.path.splitext(os.path.basename(__file__))[0]
    list_cls_names = (pyclbr.readmodule(name).keys())
    list_no_base_cls_names = [cls_name for cls_name in list_cls_names
                              if cls_name[:4] != "Base"]

    return list_no_base_cls_names
开发者ID:DesignPatternsClub,项目名称:Design-Patterns,代码行数:9,代码来源:parsers_4.py


示例20: _get_test_labels

def _get_test_labels():
    test_labels = []
    for module in [name for _, name, _ in pkgutil.iter_modules([os.path.join("cms","tests")])]:
        clsmembers = pyclbr.readmodule("cms.tests.%s" % module)
        for clsname, cls in clsmembers.items():
            for method, _ in cls.methods.items():
                if method.startswith('test_'):
                    test_labels.append('cms.%s.%s' % (clsname, method))
    return test_labels
开发者ID:CenturyGlorion,项目名称:django-cms,代码行数:9,代码来源:develop.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python pyclbr.readmodule_ex函数代码示例发布时间:2022-05-25
下一篇:
Python util.run_app_from_main函数代码示例发布时间: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