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


Python inspect.isframe方法代码示例

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


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

示例1: _format

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def _format(self, obj, descend=True):
        """Return a string representation of a single object."""
        if inspect.isframe(obj):
            filename, lineno, func, context, index = inspect.getframeinfo(obj)
            return "<frame of function '%s'>" % func

        if not descend:
            return self.peek(repr(obj))

        if isinstance(obj, dict):
            return '{' + ', '.join(['%s: %s' % (self._format(k, descend=False),
                                                self._format(v, descend=False))
                                    for k, v in obj.items()]) + '}'
        elif isinstance(obj, list):
            return '[' + ', '.join([self._format(item, descend=False)
                                    for item in obj]) + ']'
        elif isinstance(obj, tuple):
            return '(' + ', '.join([self._format(item, descend=False)
                                    for item in obj]) + ')'

        r = self.peek(repr(obj))
        if isinstance(obj, (str, int, float)):
            return r
        return '%s: %s' % (type(obj), r) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:26,代码来源:gctools.py

示例2: _getfile

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def _getfile(object):
    """
    Override inspect.getfile

    A common idiom within Obspy to get a file path of the current code
    (eg. to find a data file in the same package) is
    >>> inspect.getfile(inspect.currentframe())
    This doesn't work in PyInstaller for some reason.

    In every case I've tried, this returns the same thing as __file__,
    which does work in PyInstaller, so this hook tries to return that instead.
    """
    if inspect.isframe(object):
        try:
            file = object.f_globals['__file__']
            # print("inspect.getfile returning %s" % file)
            return file
        except:
            pass
    return _old_getfile(object) 
开发者ID:iris-edu,项目名称:pyweed,代码行数:22,代码来源:obspy.py

示例3: test_excluding_predicates

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def test_excluding_predicates(self):
        self.istest(inspect.isbuiltin, 'sys.exit')
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.func_code')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
        self.istest(inspect.isgenerator, '(x for x in xrange(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:25,代码来源:test_inspect.py

示例4: _format

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def _format(self, obj, descend=True):
        """Return a string representation of a single object."""
        if inspect.isframe(obj):
            filename, lineno, func, context, index = inspect.getframeinfo(obj)
            return "<frame of function '%s'>" % func

        if not descend:
            return self.peek(repr(obj))

        if isinstance(obj, dict):
            return "{" + ", ".join(["%s: %s" % (self._format(k, descend=False),
                                                self._format(v, descend=False))
                                    for k, v in obj.items()]) + "}"
        elif isinstance(obj, list):
            return "[" + ", ".join([self._format(item, descend=False)
                                    for item in obj]) + "]"
        elif isinstance(obj, tuple):
            return "(" + ", ".join([self._format(item, descend=False)
                                    for item in obj]) + ")"

        r = self.peek(repr(obj))
        if isinstance(obj, (str, int, float)):
            return r
        return "%s: %s" % (type(obj), r) 
开发者ID:naparuba,项目名称:opsbro,代码行数:26,代码来源:gctools.py

示例5: code

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def code(func):
    '''get the code object for the given function or method

    NOTE: use dill.source.getsource(CODEOBJ) to get the source code
    '''
    if PY3:
        im_func = '__func__'
        func_code = '__code__'
    else:
        im_func = 'im_func'
        func_code = 'func_code'
    if ismethod(func): func = getattr(func, im_func)
    if isfunction(func): func = getattr(func, func_code)
    if istraceback(func): func = func.tb_frame
    if isframe(func): func = func.f_code
    if iscode(func): return func
    return

#XXX: ugly: parse dis.dis for name after "<code object" in line and in globals? 
开发者ID:dagbldr,项目名称:dagbldr,代码行数:21,代码来源:detect.py

示例6: _isinstance

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def _isinstance(object):
    '''True if object is a class instance type (and is not a builtin)'''
    if _hascode(object) or isclass(object) or ismodule(object):
        return False
    if istraceback(object) or isframe(object) or iscode(object):
        return False
    # special handling (numpy arrays, ...)
    if not getmodule(object) and getmodule(type(object)).__name__ in ['numpy']:
        return True
#   # check if is instance of a builtin
#   if not getmodule(object) and getmodule(type(object)).__name__ in ['__builtin__','builtins']:
#       return False
    _types = ('<class ',"<type 'instance'>")
    if not repr(type(object)).startswith(_types): #FIXME: weak hack
        return False
    if not getmodule(object) or object.__module__ in ['builtins','__builtin__'] or getname(object, force=True) in ['array']:
        return False
    return True # by process of elimination... it's what we want 
开发者ID:dagbldr,项目名称:dagbldr,代码行数:20,代码来源:source.py

示例7: test_methods_garbage_collection

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def test_methods_garbage_collection(self):

        class Randomy(object):
            @memoize
            def randomy(self, do_random):
                if do_random:
                    return random.random()
                else:
                    return "constant"

        r = Randomy()
        rand1 = r.randomy(True)

        for gc_ref in gc.get_referrers(r):
            if inspect.isframe(gc_ref):
                continue
            else:
                raise AssertionError('Unexpected reference to `r` instance: {!r}\n'
                                     '@memoize probably made a reference to it and has created a circular reference loop'.format(gc_ref)) 
开发者ID:apache,项目名称:allura,代码行数:21,代码来源:test_decorators.py

示例8: test_excluding_predicates

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def test_excluding_predicates(self):
        #self.istest(inspect.isbuiltin, 'sys.exit')  # Not valid for Jython
        self.istest(inspect.isbuiltin, '[].append')
        self.istest(inspect.iscode, 'mod.spam.func_code')
        self.istest(inspect.isframe, 'tb.tb_frame')
        self.istest(inspect.isfunction, 'mod.spam')
        self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
        self.istest(inspect.ismethod, 'git.argue')
        self.istest(inspect.ismodule, 'mod')
        self.istest(inspect.istraceback, 'tb')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
        self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
        self.istest(inspect.isgenerator, '(x for x in xrange(2))')
        self.istest(inspect.isgeneratorfunction, 'generator_function_example')
        if hasattr(types, 'GetSetDescriptorType'):
            self.istest(inspect.isgetsetdescriptor,
                        'type(tb.tb_frame).f_locals')
        else:
            self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
        if hasattr(types, 'MemberDescriptorType'):
            # Not valid for Jython
            # self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
            pass
        else:
            self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days)) 
开发者ID:Acmesec,项目名称:CTFCrackTools-V2,代码行数:27,代码来源:test_inspect.py

示例9: ascend

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def ascend(self, obj, depth=1):
        """Return a nested list containing referrers of the given object."""
        depth += 1
        parents = []

        # Gather all referrers in one step to minimize
        # cascading references due to repr() logic.
        refs = gc.get_referrers(obj)
        self.ignore.append(refs)
        if len(refs) > self.maxparents:
            return [('[%s referrers]' % len(refs), [])]

        try:
            ascendcode = self.ascend.__code__
        except AttributeError:
            ascendcode = self.ascend.im_func.func_code
        for parent in refs:
            if inspect.isframe(parent) and parent.f_code is ascendcode:
                continue
            if parent in self.ignore:
                continue
            if depth <= self.maxdepth:
                parents.append((parent, self.ascend(parent, depth)))
            else:
                parents.append((parent, []))

        return parents 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:29,代码来源:gctools.py

示例10: isdata

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def isdata(object):
    """Check if an object is of a type that probably means it's data."""
    return not (inspect.ismodule(object) or inspect.isclass(object) or
                inspect.isroutine(object) or inspect.isframe(object) or
                inspect.istraceback(object) or inspect.iscode(object)) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:7,代码来源:pydoc.py

示例11: from_built_in_frame

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def from_built_in_frame(cls, frame):
    """Create a new instance from built-in frame object."""
    assert inspect.isframe(frame), 'Expect FrameType; Got %s' % type(frame)
    return cls(
      file=os.path.abspath(frame.f_code.co_filename),
      line=int(frame.f_lineno),
    ) 
开发者ID:luci,项目名称:recipes-py,代码行数:9,代码来源:cause.py

示例12: getArgValues

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def getArgValues(frame):
    """Provides information about arguments passed into a particular frame"""
    if not isframe(frame):
        raise TypeError('{0!r} is not a frame object'.format(frame))

    args, varargs, kwonlyargs, varkw = _getfullargs(frame.f_code)
    return ArgInfo(args + kwonlyargs, varargs, varkw, frame.f_locals) 
开发者ID:SergeySatskiy,项目名称:codimension,代码行数:9,代码来源:cdm_dbg_utils.py

示例13: _process_in_memory_objects

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def _process_in_memory_objects(objects):
    """Processes objects tracked by GC.

    Processing is done in separate function to avoid generating overhead.
    """
    return _remove_duplicates(obj for obj in objects
                              if not inspect.isframe(obj)) 
开发者ID:nvdv,项目名称:vprof,代码行数:9,代码来源:memory_profiler.py

示例14: test_abuse_done

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def test_abuse_done(self):
        self.istest(inspect.istraceback, 'git.ex[2]')
        self.istest(inspect.isframe, 'mod.fr') 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:5,代码来源:test_inspect.py

示例15: list_referrers

# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import isframe [as 别名]
def list_referrers(self, exclude=[], depth=0):
        """List all the referrers of the tracked objects.

        Can exlude some objects and go to deeper levels (referrers of the
        referrers) in which case reference to the first object are filtered.
        References held by frames are also filtered

        This function is mostly useful when tracking why an object that is
        expected to be released is not.

        """
        gc.collect()

        def find_referrers(ref_dict, obj, depth=0, exclude=[]):
            """Find the object referring the specified object.

            """
            referrers = [ref for ref in gc.get_referrers(obj)
                         if not (inspect.isframe(ref) or
                         ref in exclude)]
            if depth == 0:
                ref_dict[obj] = referrers
            else:
                deeper = {}
                for r in referrers:
                    find_referrers(deeper, r, depth-1,
                                   exclude + [obj, referrers])
                ref_dict[obj] = deeper

        tracked = {}
        objs = [r for r in self._refs if r not in exclude]
        for r in objs:
            find_referrers(tracked, r, depth, [objs])

        return tracked 
开发者ID:Exopy,项目名称:exopy,代码行数:37,代码来源:util.py


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