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


Python pyclbr.readmodule函数代码示例

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


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


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