當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。