本文整理汇总了Python中pyclbr.readmodule_ex函数的典型用法代码示例。如果您正苦于以下问题:Python readmodule_ex函数的具体用法?Python readmodule_ex怎么用?Python readmodule_ex使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了readmodule_ex函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: listclasses
def listclasses(self):
dir, file = os.path.split(self.file)
name, ext = os.path.splitext(file)
if os.path.normcase(ext) != ".py":
return []
try:
dict = pyclbr.readmodule_ex(name, [dir] + sys.path)
except ImportError as msg:
return []
items = []
self.classes = {}
for key, cl in dict.items():
if cl.module == name:
s = key
if hasattr(cl, 'super') and cl.super:
supers = []
for sup in cl.super:
if type(sup) is type(''):
sname = sup
else:
sname = sup.name
if sup.module != cl.module:
sname = "%s.%s" % (sup.module, sname)
supers.append(sname)
s = s + "(%s)" % ", ".join(supers)
items.append((cl.lineno, s))
self.classes[s] = cl
items.sort()
list = []
for item, s in items:
list.append(s)
return list
开发者ID:GoMADAO,项目名称:Lessa-PLT,代码行数:32,代码来源:ClassBrowser.py
示例2: monkey_patch
def monkey_patch():
"""If the CONF.monkey_patch set as True,
this function patches a decorator
for all functions in specified modules.
You can set decorators for each modules
using CONF.monkey_patch_modules.
The format is "Module path:Decorator function".
Parameters of the decorator is as follows.
name - name of the function
function - object of the function
"""
# If CONF.monkey_patch is not True, this function do nothing.
if not CONF.monkey_patch:
return
# Get list of modules and decorators
for module_and_decorator in CONF.monkey_patch_modules:
module, decorator_name = module_and_decorator.split(':')
# import decorator function
decorator = importutils.import_class(decorator_name)
__import__(module)
# Retrieve module information using pyclbr
module_data = pyclbr.readmodule_ex(module)
for key in module_data.keys():
# set the decorator for the class methods
if isinstance(module_data[key], pyclbr.Class):
clz = importutils.import_class("%s.%s" % (module, key))
for method, func in inspect.getmembers(clz, inspect.ismethod):
setattr(clz, method,
decorator("%s.%s.%s" % (module, key, method), func))
# set the decorator for the function
if isinstance(module_data[key], pyclbr.Function):
func = importutils.import_class("%s.%s" % (module, key))
setattr(sys.modules[module], key,
decorator("%s.%s" % (module, key), func))
开发者ID:yianjiajia,项目名称:my_all_codes,代码行数:35,代码来源:utils.py
示例3: main
def main(args, out_name):
dict = {}
for mod in args:
if os.path.exists(mod):
path = [os.path.dirname(mod)]
mod = os.path.basename(mod)
if mod.lower().endswith(".py"):
mod = mod[:-3]
else:
path = []
dict.update(pyclbr.readmodule_ex(mod, path))
G = AGraph(strict=False,directed=True)
G.graph_attr['fontname'] = 'Bitstream Vera Sans'
G.graph_attr['fontsize'] = '8'
G.graph_attr['rankdir'] = 'BT'
G.node_attr['fontname'] = 'Bitstream Vera Sans'
G.node_attr['fontsize'] = '8'
G.node_attr['shape'] = 'record'
G.edge_attr['fontname'] = 'Bitstream Vera Sans'
G.edge_attr['fontsize'] = '8'
G.edge_attr['arrowhead'] = 'empty'
for obj in dict.values():
if isinstance(obj, pyclbr.Class):
G.add_node(obj.name)
n = G.get_node(obj.name)
n.attr['label'] = '{%s|%s|%s}' % (obj.name, get_members(obj), get_methods(obj))
for sclass in obj.super:
if isinstance(sclass, pyclbr.Class):
G.add_edge(obj.name, sclass.name)
G.layout('dot')
G.draw(out_name)
开发者ID:xfire,项目名称:dotfiles,代码行数:35,代码来源:python_classdiagram.py
示例4: __init__
def __init__(self,fullname):
fn = fullname + '.py'
if not os.path.exists(fn):
raise ValueError,"Module source file %s does not exist" % fn
m = imp.load_source(fullname,fn)
d = pyclbr.readmodule_ex(fullname)
# remove external defs
d = dict([ (k,v) for k,v in d.items() if v.module == fullname ])
d = sortDict(d)
self.module = m
self.filename = fn
self.fullname = fullname
self.name = self.fullname.split('/')[-1]
self.shortdoc,self.longdoc = splitDocString(sanitize(m.__doc__))
# get classes and functions
self.classes,self.functions = splitDict(d)
for f in self.functions.keys()[:]:
if not hasattr(self.module,f):
# function was probably defined in __main__ section
del self.functions[f]
prt("Classes: %s" % ', '.join(self.classes.keys()))
prt("Functions: %s" % ', '.join(self.functions.keys()))
self.args = self.get_arg_linenrs()
self.set_class_method_args()
self.set_function_args()
开发者ID:BackupTheBerlios,项目名称:pyformex-svn,代码行数:28,代码来源:gendoc.py
示例5: find_functions_and_classes
def find_functions_and_classes(modulename, path):
"""Parse the file and return [('lineno', 'class name', 'function')]
>>> with open("test1.py", "w") as f:
... f.write(chr(10).join(["def hola():", " pass", "#", "def chau():", " pass", ""]))
... f.write(chr(10).join(["class Test:"," def __init__():",""," pass"]))
>>> results = find_functions_and_classes("test1", ".")
>>> results
[[1, None, 'hola', 0], [4, None, 'chau', 0], [7, 'Test', '__init__', 0]]
"""
# Assumptions: there is only one function/class per line (syntax)
# class attributes & decorators are ignored
# imported functions should be ignored
# inheritance clases from other modules is unhandled (super)doctest for results failed, exception NameError("name 'results' is not defined",)
result = []
module = pyclbr.readmodule_ex(modulename, path=path and [path])
for obj in module.values():
if isinstance(obj, pyclbr.Function) and obj.module == modulename:
# it is a top-level global function (no class)
result.append([obj.lineno, None, obj.name, 0])
elif isinstance(obj, pyclbr.Class) and obj.module == modulename:
# it is a class, look for the methods:
for method, lineno in obj.methods.items():
result.append([lineno, obj.name, method, 0])
# sort using lineno:
result.sort(key=lambda x: x[LINENO])
return result
开发者ID:Focus3D,项目名称:rad2py,代码行数:29,代码来源:locutil.py
示例6: profile_cputime
def profile_cputime(module, decorator_name, status):
try:
if status:
profile_cpu.add_module(module)
else:
profile_cpu.delete_module(module)
# import decorator function
decorator = importutils.import_class(decorator_name)
__import__(module)
# Retrieve module information using pyclbr
module_data = pyclbr.readmodule_ex(module)
for key in module_data.keys():
# set the decorator for the class methods
if isinstance(module_data[key], pyclbr.Class):
clz = importutils.import_class("%s.%s" % (module, key))
for method, func in inspect.getmembers(clz, inspect.ismethod):
if func.func_code.co_name == 'profile_cputime':
pass
else:
setattr(clz, method,
decorator("%s.%s.%s" % (module, key, method), func))
LOG.info(_('Decorated method ' + method))
# set the decorator for the function
if isinstance(module_data[key], pyclbr.Function):
func = importutils.import_class("%s.%s" % (module, key))
if func.func_code.co_name == 'profile_cputime':
pass
else:
setattr(sys.modules[module], key,
decorator("%s.%s" % (module, key), func))
LOG.info(_('Decorated method ' + key))
except:
LOG.error(_('Invalid module or decorator name '))
LOG.error(_('Exception occurred %s ') % traceback.format_exc())
开发者ID:emonty,项目名称:healthnmon,代码行数:35,代码来源:helper.py
示例7: listclasses
def listclasses(self):
dir, file = os.path.split(self.file)
name, ext = os.path.splitext(file)
if os.path.normcase(ext) != ".py":
return []
try:
dict = pyclbr.readmodule_ex(name, [dir] + sys.path)
except ImportError, msg:
return []
开发者ID:1310701102,项目名称:sl4a,代码行数:9,代码来源:ClassBrowser.py
示例8: pyclbrTest
def pyclbrTest( files ):
" Loop for the library standard parser "
count = 0
for item in files:
tempObj = pyclbr.readmodule_ex(
os.path.basename( item ).replace( ".py", "" ),
[os.path.dirname( item )] )
count += 1
print "pyclbr: processed " + str(count) + " files"
return
开发者ID:Alwnikrotikz,项目名称:codimension,代码行数:10,代码来源:speed_test.py
示例9: readpackage_at
def readpackage_at(self, path):
(modules, root) = self.projects.find_package(path)
for module in modules:
if not module:
continue
try:
for item in pyclbr.readmodule_ex(module, [root]).items():
yield item
except ImportError:
pass
开发者ID:tkf,项目名称:emacs-pyclbr,代码行数:10,代码来源:pyclbrepcserver.py
示例10: readModule
def readModule(filename, *paths):
try:
contents = readmodule_ex(filename, path=list(paths))
contents = contents.copy()
except (ImportError, ):
contents = {}
try:
del(contents['__path__'])
except (KeyError, ):
pass
return contents
开发者ID:InfiniteAlpha,项目名称:profitpy,代码行数:11,代码来源:syspathdialog.py
示例11: listchildren
def listchildren(self):
"Return sequenced classes and functions in the module."
dir, base = os.path.split(self.file)
name, ext = os.path.splitext(base)
if os.path.normcase(ext) != ".py":
return []
try:
tree = pyclbr.readmodule_ex(name, [dir] + sys.path)
except ImportError:
return []
return transform_children(tree, name)
开发者ID:hzp1245,项目名称:cpython,代码行数:11,代码来源:browser.py
示例12: listobjects
def listobjects(self):
dir, file = os.path.split(self.file)
name, ext = os.path.splitext(file)
if os.path.normcase(ext) != ".py":
return []
try:
dict = pyclbr.readmodule_ex(name, [dir] + sys.path)
except ImportError as msg:
return []
self.classes, items = collect_objects(dict, name)
items.sort()
return [s for item, s in items]
开发者ID:AprilArcus,项目名称:vpython-wx,代码行数:12,代码来源:ClassBrowser.py
示例13: monkey_patch
def monkey_patch():
"""Patch decorator.
If the Flags.monkey_patch set as True,
this function patches a decorator
for all functions in specified modules.
You can set decorators for each modules
using CONF.monkey_patch_modules.
The format is "Module path:Decorator function".
Example: 'manila.api.ec2.cloud:' \
manila.openstack.common.notifier.api.notify_decorator'
Parameters of the decorator is as follows.
(See manila.openstack.common.notifier.api.notify_decorator)
name - name of the function
function - object of the function
"""
# If CONF.monkey_patch is not True, this function do nothing.
if not CONF.monkey_patch:
return
# Get list of modules and decorators
for module_and_decorator in CONF.monkey_patch_modules:
module, decorator_name = module_and_decorator.split(':')
# import decorator function
decorator = importutils.import_class(decorator_name)
__import__(module)
# Retrieve module information using pyclbr
module_data = pyclbr.readmodule_ex(module)
for key in module_data.keys():
# set the decorator for the class methods
if isinstance(module_data[key], pyclbr.Class):
clz = importutils.import_class("%s.%s" % (module, key))
# NOTE(vponomaryov): we need to distinguish class methods types
# for py2 and py3, because the concept of 'unbound methods' has
# been removed from the python3.x
if six.PY3:
member_type = inspect.isfunction
else:
member_type = inspect.ismethod
for method, func in inspect.getmembers(clz, member_type):
setattr(
clz, method,
decorator("%s.%s.%s" % (module, key, method), func))
# set the decorator for the function
if isinstance(module_data[key], pyclbr.Function):
func = importutils.import_class("%s.%s" % (module, key))
setattr(sys.modules[module], key,
decorator("%s.%s" % (module, key), func))
开发者ID:JosonYuan,项目名称:manila,代码行数:49,代码来源:utils.py
示例14: checkModule
def checkModule(self, moduleName, module=None, ignore=()):
''' succeed iff pyclbr.readmodule_ex(modulename) corresponds
to the actual module object, module. Any identifiers in
ignore are ignored. If no module is provided, the appropriate
module is loaded with __import__.'''
if module == None:
module = __import__(moduleName, globals(), {}, [])
dict = pyclbr.readmodule_ex(moduleName)
# Make sure the toplevel functions and classes are the same.
for name, value in dict.items():
if name in ignore:
continue
self.assertHasattr(module, name, ignore)
py_item = getattr(module, name)
if isinstance(value, pyclbr.Function):
self.assertEquals(type(py_item), FunctionType)
else:
self.assertEquals(type(py_item), ClassType)
real_bases = [base.__name__ for base in py_item.__bases__]
pyclbr_bases = [ getattr(base, 'name', base)
for base in value.super ]
self.assertListEq(real_bases, pyclbr_bases, ignore)
actualMethods = []
for m in py_item.__dict__.keys():
if type(getattr(py_item, m)) == MethodType:
actualMethods.append(m)
foundMethods = []
for m in value.methods.keys():
if m[:2] == '__' and m[-2:] != '__':
foundMethods.append('_'+name+m)
else:
foundMethods.append(m)
self.assertListEq(foundMethods, actualMethods, ignore)
self.assertEquals(py_item.__module__, value.module)
self.assertEquals(py_item.__name__, value.name, ignore)
# can't check file or lineno
# Now check for missing stuff.
for name in dir(module):
item = getattr(module, name)
if type(item) in (ClassType, FunctionType):
self.assertHaskey(dict, name, ignore)
开发者ID:BackupTheBerlios,项目名称:etpe-svn,代码行数:49,代码来源:test_pyclbr.py
示例15: scanfuncs
def scanfuncs(filename, prefixes, cython=False):
""" Return list of function names from ``filename`` that begin with prefix.
This *does not* import the Python file, so this is safe to use, but
functionality is limited to retrieving names of basic functions defined
within global scope of the file.
This *does*, however, import Cython files (if applicable).
"""
# Used by: findarenas, findbenchmarks
path, name = os.path.split(filename)
name, ext = os.path.splitext(name)
# Should `cython` be a keyword argument, or should we just infer it?
cython = cython or ext == '.pyx'
if not cython:
funcs = pyclbr.readmodule_ex(name, [path])
funcnames = []
for key, val in funcs.items():
if (any(key.startswith(prefix) for prefix in prefixes) and
val.file == filename):
funcnames.append(key)
return funcnames
# Scan Cython file. We need to import it.
import pyximport
pyximport.install()
sys.dont_write_bytecode = True
# Make sure local imports work for the given file
sys.path.insert(0, path)
pyximport.build_module(name, filename)
try:
mod = pyximport.load_module(name, filename)
except ImportError:
# There is most likely a '*.py' file that shares the same
# base name as the '*.pyx' file we are trying to import.
# Removing the directory from sys.path should fix this,
# but will disable local importing.
sys.path.pop(0)
mod = pyximport.load_module(name, filename)
# Undo making local imports work
if sys.path[0] == path:
sys.path.pop(0)
funcnames = []
for funcname in mod.__dict__:
if any(funcname.startswith(prefix) for prefix in prefixes):
funcnames.append(funcname)
return funcnames
开发者ID:eriknw,项目名称:benchtoolz,代码行数:47,代码来源:benchutils.py
示例16: monkey_patch
def monkey_patch():
"""DEPRECATED: If the CONF.monkey_patch set as True,
this function patches a decorator
for all functions in specified modules.
You can set decorators for each modules
using CONF.monkey_patch_modules.
The format is "Module path:Decorator function".
Example:
'nova.api.ec2.cloud:nova.notifications.notify_decorator'
Parameters of the decorator is as follows.
(See nova.notifications.notify_decorator)
name - name of the function
function - object of the function
"""
# If CONF.monkey_patch is not True, this function do nothing.
if not CONF.monkey_patch:
return
LOG.warning('Monkey patching nova is deprecated for removal.')
if six.PY2:
is_method = inspect.ismethod
else:
def is_method(obj):
# Unbound methods became regular functions on Python 3
return inspect.ismethod(obj) or inspect.isfunction(obj)
# Get list of modules and decorators
for module_and_decorator in CONF.monkey_patch_modules:
module, decorator_name = module_and_decorator.split(':')
# import decorator function
decorator = importutils.import_class(decorator_name)
__import__(module)
# Retrieve module information using pyclbr
module_data = pyclbr.readmodule_ex(module)
for key, value in module_data.items():
# set the decorator for the class methods
if isinstance(value, pyclbr.Class):
clz = importutils.import_class("%s.%s" % (module, key))
for method, func in inspect.getmembers(clz, is_method):
setattr(clz, method,
decorator("%s.%s.%s" % (module, key, method), func))
# set the decorator for the function
if isinstance(value, pyclbr.Function):
func = importutils.import_class("%s.%s" % (module, key))
setattr(sys.modules[module], key,
decorator("%s.%s" % (module, key), func))
开发者ID:sapcc,项目名称:nova,代码行数:46,代码来源:utils.py
示例17: monkey_patch
def monkey_patch():
"""Patches decorators for all functions in a specified module.
If the CONF.monkey_patch set as True,
this function patches a decorator
for all functions in specified modules.
You can set decorators for each modules
using CONF.monkey_patch_modules.
The format is "Module path:Decorator function".
Example: 'cinder.api.ec2.cloud:' \
cinder.openstack.common.notifier.api.notify_decorator'
Parameters of the decorator is as follows.
(See cinder.openstack.common.notifier.api.notify_decorator)
:param name: name of the function
:param function: object of the function
"""
# If CONF.monkey_patch is not True, this function do nothing.
if not CONF.monkey_patch:
return
# Get list of modules and decorators
for module_and_decorator in CONF.monkey_patch_modules:
module, decorator_name = module_and_decorator.split(':')
# import decorator function
decorator = importutils.import_class(decorator_name)
__import__(module)
# Retrieve module information using pyclbr
module_data = pyclbr.readmodule_ex(module)
for key in module_data.keys():
# set the decorator for the class methods
if isinstance(module_data[key], pyclbr.Class):
clz = importutils.import_class("%s.%s" % (module, key))
# On Python 3, unbound methods are regular functions
predicate = inspect.isfunction if six.PY3 else inspect.ismethod
for method, func in inspect.getmembers(clz, predicate):
setattr(
clz, method,
decorator("%s.%s.%s" % (module, key, method), func))
# set the decorator for the function
elif isinstance(module_data[key], pyclbr.Function):
func = importutils.import_class("%s.%s" % (module, key))
setattr(sys.modules[module], key,
decorator("%s.%s" % (module, key), func))
开发者ID:muraliran,项目名称:cinder,代码行数:45,代码来源:utils.py
示例18: listclasses
def listclasses(self):
"""Return list of classes and functions in the module.
The dictionary output from pyclbr is re-written as a
list of tuples in the form (lineno, name) and
then sorted so that the classes and functions are
processed in line number order. The returned list only
contains the name and not the line number. An instance
variable self.classes contains the pyclbr dictionary values,
which are instances of Class and Function.
"""
dir, file = os.path.split(self.file)
name, ext = os.path.splitext(file)
if os.path.normcase(ext) != ".py":
return []
try:
dict = pyclbr.readmodule_ex(name, [dir] + sys.path)
except ImportError:
return []
items = []
self.classes = {}
for key, cl in dict.items():
if cl.module == name:
s = key
if hasattr(cl, 'super') and cl.super:
supers = []
for sup in cl.super:
if type(sup) is type(''):
sname = sup
else:
sname = sup.name
if sup.module != cl.module:
sname = "%s.%s" % (sup.module, sname)
supers.append(sname)
s = s + "(%s)" % ", ".join(supers)
items.append((cl.lineno, s))
self.classes[s] = cl
items.sort()
list = []
for item, s in items:
list.append(s)
return list
开发者ID:M31MOTH,项目名称:cpython,代码行数:42,代码来源:browser.py
示例19: __init__
def __init__(self, name="", path=None, file_name="<unknown>", code=None):
CKClass.__init__(self, name, None, None, None)
self.path = path
self.descriptor = pyclbr.readmodule_ex(self.name, path)
self.file_name = file_name
self.code = code
if self.code:
self.symbol_table = symtable.symtable(self.code, self.file_name, 'exec')
self.ast_node = ast.parse(self.code, self.file_name)
self.classes = {}
class_node_finder = ClassNodeFinder(self.ast_node)
for class_name in self.descriptor.keys():
class_descriptor = self.descriptor[class_name]
if isinstance(class_descriptor, pyclbr.Class):
if class_descriptor.module == self.name:
class_table = self.symbol_table.lookup(class_name).get_namespace()
class_node = class_node_finder.find(class_name)
ck_class = CKClass(class_name, class_descriptor, class_table, class_node)
ck_class.extract_references()
self.classes[self.name + "." + class_name] = ck_class
开发者ID:wolmir,项目名称:cristina,代码行数:20,代码来源:pyck.py
示例20: list_classes
def list_classes(self, buffer=None, fname=None):
model = gtk.TreeStore(str, str, int)
if not fname is None:
fname = fname
else:
return model
dir, file = os.path.split(fname)
name, ext = os.path.splitext(file)
dict = {}
try:
py_compile.compile(fname)
except:
# ~ print "isn't a valid file"
return model
if os.path.normcase(ext) != ".py":
return model
try:
pyclbr._modules = {}
dict = pyclbr.readmodule_ex(name, [dir] + sys.path)
except ImportError, msg:
return model
开发者ID:BackupTheBerlios,项目名称:culebra-svn,代码行数:21,代码来源:grad.py
注:本文中的pyclbr.readmodule_ex函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论