Python sys._getframe() Examples

The following are 30 code examples of sys._getframe(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: versioning_test.py    From ssm-cache-python with MIT License 7 votes vote down vote up
def test_update_versions(self):
        """ Test version update """

        method_name = sys._getframe().f_code.co_name
        self._setUp(method_name)

        name = method_name
        self._create_or_update_param(name)

        param = SSMParameter(name)

        self.assertEqual(param.version, 1)
        self.assertEqual(param.value, self.PARAM_VALUE)

        # this will update the value and create version 2
        self._create_or_update_param(name, self.PARAM_VALUE_V2)

        param.refresh()

        # refreshing should give you version 2
        self.assertEqual(param.version, 2)
        self.assertEqual(param.value, self.PARAM_VALUE_V2)

        self._delete_param(name) 
Example #2
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def render_string(self, template_name, **kwargs):
        """使用给定的参数生成指定模板.

        我们返回生成的字节字符串(以utf8). 为了生成并写一个模板
        作为响应, 使用上面的render().
        """
        # If no template_path is specified, use the path of the calling file
        template_path = self.get_template_path()
        if not template_path:
            frame = sys._getframe(0)
            web_file = frame.f_code.co_filename
            while frame.f_code.co_filename == web_file:
                frame = frame.f_back
            template_path = os.path.dirname(frame.f_code.co_filename)
        with RequestHandler._template_loader_lock:
            if template_path not in RequestHandler._template_loaders:
                loader = self.create_template_loader(template_path)
                RequestHandler._template_loaders[template_path] = loader
            else:
                loader = RequestHandler._template_loaders[template_path]
        t = loader.load(template_name)
        namespace = self.get_template_namespace()
        namespace.update(kwargs)
        return t.generate(**namespace) 
Example #3
Source File: tools.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_trace():
    """Call pdb.set_trace in the caller's frame.

    First restore sys.stdout and sys.stderr.  Note that the streams are
    NOT reset to whatever they were before the call once pdb is done!
    """
    import pdb
    for stream in 'stdout', 'stderr':
        output = getattr(sys, stream)
        orig_output = getattr(sys, '__%s__' % stream)
        if output != orig_output:
            # Flush the output before entering pdb
            if hasattr(output, 'getvalue'):
                orig_output.write(output.getvalue())
                orig_output.flush()
            setattr(sys, stream, orig_output)
    exc, tb = sys.exc_info()[1:]
    if tb:
        if isinstance(exc, AssertionError) and exc.args:
            # The traceback is not printed yet
            print_exc()
        pdb.post_mortem(tb)
    else:
        pdb.Pdb().set_trace(sys._getframe().f_back) 
Example #4
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_trace():
    """Call pdb.set_trace in the caller's frame.

    First restore sys.stdout and sys.stderr.  Note that the streams are
    NOT reset to whatever they were before the call once pdb is done!
    """
    import pdb
    for stream in 'stdout', 'stderr':
        output = getattr(sys, stream)
        orig_output = getattr(sys, '__%s__' % stream)
        if output != orig_output:
            # Flush the output before entering pdb
            if hasattr(output, 'getvalue'):
                orig_output.write(output.getvalue())
                orig_output.flush()
            setattr(sys, stream, orig_output)
    exc, tb = sys.exc_info()[1:]
    if tb:
        if isinstance(exc, AssertionError) and exc.args:
            # The traceback is not printed yet
            print_exc()
        pdb.post_mortem(tb)
    else:
        pdb.Pdb().set_trace(sys._getframe().f_back) 
Example #5
Source File: _assertionold.py    From py with MIT License 6 votes vote down vote up
def check(s, frame=None):
    if frame is None:
        frame = sys._getframe(1)
        frame = py.code.Frame(frame)
    expr = parse(s, 'eval')
    assert isinstance(expr, ast.Expression)
    node = Interpretable(expr.node)
    try:
        node.eval(frame)
    except passthroughex:
        raise
    except Failure:
        e = sys.exc_info()[1]
        report_failure(e)
    else:
        if not frame.is_true(node.result):
            sys.stderr.write("assertion failed: %s\n" % node.nice_explanation())


###########################################################
# API / Entry points
# ######################################################### 
Example #6
Source File: support.py    From verge3d-blender-addon with GNU General Public License v3.0 6 votes vote down vote up
def requires(resource, msg=None):
    """Raise ResourceDenied if the specified resource is not available.

    If the caller's module is __main__ then automatically return True.  The
    possibility of False being returned occurs when regrtest.py is
    executing.
    """
    if resource == 'gui' and not _is_gui_available():
        raise unittest.SkipTest("Cannot use the 'gui' resource")
    # see if the caller's module is __main__ - if so, treat as if
    # the resource was set
    if sys._getframe(1).f_globals.get("__name__") == "__main__":
        return
    if not is_resource_enabled(resource):
        if msg is None:
            msg = "Use of the %r resource not enabled" % resource
        raise ResourceDenied(msg) 
Example #7
Source File: warning.py    From py with MIT License 6 votes vote down vote up
def _apiwarn(startversion, msg, stacklevel=2, function=None):
    # below is mostly COPIED from python2.4/warnings.py's def warn()
    # Get context information
    if isinstance(stacklevel, str):
        frame = sys._getframe(1)
        level = 1
        found = frame.f_code.co_filename.find(stacklevel) != -1
        while frame:
            co = frame.f_code
            if co.co_filename.find(stacklevel) == -1:
                if found:
                    stacklevel = level
                    break
            else:
                found = True
            level += 1
            frame = frame.f_back
        else:
            stacklevel = 1
    msg = "%s (since version %s)" %(msg, startversion)
    warn(msg, stacklevel=stacklevel+1, function=function) 
Example #8
Source File: decorator.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def update(self, func, **kw):
        "Update the signature of func with the data in self"
        func.__name__ = self.name
        func.__doc__ = getattr(self, 'doc', None)
        func.__dict__ = getattr(self, 'dict', {})
        func.__defaults__ = self.defaults
        func.__kwdefaults__ = self.kwonlydefaults or None
        func.__annotations__ = getattr(self, 'annotations', None)
        try:
            frame = sys._getframe(3)
        except AttributeError:  # for IronPython and similar implementations
            callermodule = '?'
        else:
            callermodule = frame.f_globals.get('__name__', '?')
        func.__module__ = getattr(self, 'module', callermodule)
        func.__dict__.update(kw) 
Example #9
Source File: __init__.py    From jawfish with MIT License 6 votes vote down vote up
def currentframe():
        """Return the frame object for the caller's stack frame."""
        try:
            raise Exception
        except:
            return sys.exc_info()[2].tb_frame.f_back

# _srcfile is only used in conjunction with sys._getframe().
# To provide compatibility with older versions of Python, set _srcfile
# to None if _getframe() is not available; this value will prevent
# findCaller() from being called.
#if not hasattr(sys, "_getframe"):
#    _srcfile = None

#
#_startTime is used as the base when calculating the relative time of events
# 
Example #10
Source File: test_code.py    From py with MIT License 6 votes vote down vote up
def test_frame_getargs():
    def f1(x):
        return sys._getframe(0)
    fr1 = py.code.Frame(f1('a'))
    assert fr1.getargs(var=True) == [('x', 'a')]

    def f2(x, *y):
        return sys._getframe(0)
    fr2 = py.code.Frame(f2('a', 'b', 'c'))
    assert fr2.getargs(var=True) == [('x', 'a'), ('y', ('b', 'c'))]

    def f3(x, **z):
        return sys._getframe(0)
    fr3 = py.code.Frame(f3('a', b='c'))
    assert fr3.getargs(var=True) == [('x', 'a'), ('z', {'b': 'c'})]

    def f4(x, *y, **z):
        return sys._getframe(0)
    fr4 = py.code.Frame(f4('a', 'b', c='d'))
    assert fr4.getargs(var=True) == [('x', 'a'), ('y', ('b',)),
                                     ('z', {'c': 'd'})] 
Example #11
Source File: __init__.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
def get_extended_info(error_message, prefix):
    # noinspection PyProtectedMember
    caller_stack_frame = sys._getframe(2)
    caller = caller_stack_frame.f_code.co_name
    line = caller_stack_frame.f_lineno
    module = inspect.getmodule(caller_stack_frame)
    error_code = get_error_constant_name(module.__dict__, error_message, prefix)
    if error_code is None:
        error_code = get_error_constant_name(caller_stack_frame.f_globals, error_message, prefix)

    result = {
        "Caller": caller,
        "Module": module.__name__,
        "Line": line
    }
    if error_code is not None:
        result["Code"] = error_code

    return result 
Example #12
Source File: didyoumean_internal_tests.py    From DidYouMean-Python with MIT License 6 votes vote down vote up
def name_corresponds_to(self, name, expected):
        """Helper functions to test get_objects_in_frame.

        Check that the name corresponds to the expected objects (and their
        scope) in the frame of calling function.
        None can be used to match any object as it can be hard to describe
        an object when it is hidden by something in a closer scope.
        Also, extra care is to be taken when calling the function because
        giving value by names might affect the result (adding in local
        scope).
        """
        frame = sys._getframe(1)  # frame of calling function
        lst = get_objects_in_frame(frame).get(name, [])
        self.assertEqual(len(lst), len(expected))
        for scopedobj, exp in zip(lst, expected):
            obj, scope = scopedobj
            expobj, expscope = exp
            self.assertEqual(scope, expscope, name)
            if expobj is not None:
                self.assertEqual(obj, expobj, name) 
Example #13
Source File: output.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def silentLogPrefix(stepsUp):
    '''
    logPrefix v2-- gets caller information silently (without caller intervention)
    The single parameter reflects how far up the stack to go to find the caller and
    depends how deep the direct caller to this method is wrt to the target caller

    NOTE: Some calls cannot be silently prefixed (getting into the twisted code is a
    great example)

    :param stepsUp: the number of steps to move up the stack for the caller
    :type steps: int.
    '''

    try:
        trace = sys._getframe(stepsUp).f_code.co_filename
        line = sys._getframe(stepsUp).f_lineno
        module, package = parseLogPrefix(trace)
    except:
        return 'unknown', 'unknown', '??'

    return package, module, line 
Example #14
Source File: decorator.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def update(self, func, **kw):
        "Update the signature of func with the data in self"
        func.__name__ = self.name
        func.__doc__ = getattr(self, 'doc', None)
        func.__dict__ = getattr(self, 'dict', {})
        func.__defaults__ = self.defaults
        func.__kwdefaults__ = self.kwonlydefaults or None
        func.__annotations__ = getattr(self, 'annotations', None)
        try:
            frame = sys._getframe(3)
        except AttributeError:  # for IronPython and similar implementations
            callermodule = '?'
        else:
            callermodule = frame.f_globals.get('__name__', '?')
        func.__module__ = getattr(self, 'module', callermodule)
        func.__dict__.update(kw) 
Example #15
Source File: versioning_test.py    From ssm-cache-python with MIT License 6 votes vote down vote up
def test_versions_group_select(self):
        """ Test version selection in a group """
        method_name = sys._getframe().f_code.co_name
        self._setUp(method_name)

        name = method_name
        self._create_or_update_param(name)

        # this will update the value and create version 2
        self._create_or_update_param(name, self.PARAM_VALUE_V2)

        group = SSMParameterGroup()
        param = group.parameter("%s:1" % name)

        self.assertEqual(param.version, 1)
        self.assertEqual(param.value, self.PARAM_VALUE)

        self._delete_param(name) 
Example #16
Source File: versioning_test.py    From ssm-cache-python with MIT License 6 votes vote down vote up
def test_versions_group(self):
        """ Test version update in a group """
        method_name = sys._getframe().f_code.co_name
        self._setUp(method_name)

        name = method_name
        self._create_or_update_param(name)

        group = SSMParameterGroup()
        param = group.parameter(name)

        self.assertEqual(param.version, 1)
        self.assertEqual(param.value, self.PARAM_VALUE)

        # this will update the value and create version 2
        self._create_or_update_param(name, self.PARAM_VALUE_V2)

        group.refresh()

        # refreshing should give you version 2
        self.assertEqual(param.version, 2)
        self.assertEqual(param.value, self.PARAM_VALUE_V2)

        self._delete_param(name) 
Example #17
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def render_string(self, template_name, **kwargs):
        """使用给定的参数生成指定模板.

        我们返回生成的字节字符串(以utf8). 为了生成并写一个模板
        作为响应, 使用上面的render().
        """
        # If no template_path is specified, use the path of the calling file
        template_path = self.get_template_path()
        if not template_path:
            frame = sys._getframe(0)
            web_file = frame.f_code.co_filename
            while frame.f_code.co_filename == web_file:
                frame = frame.f_back
            template_path = os.path.dirname(frame.f_code.co_filename)
        with RequestHandler._template_loader_lock:
            if template_path not in RequestHandler._template_loaders:
                loader = self.create_template_loader(template_path)
                RequestHandler._template_loaders[template_path] = loader
            else:
                loader = RequestHandler._template_loaders[template_path]
        t = loader.load(template_name)
        namespace = self.get_template_namespace()
        namespace.update(kwargs)
        return t.generate(**namespace) 
Example #18
Source File: versioning_test.py    From ssm-cache-python with MIT License 6 votes vote down vote up
def test_select_versions(self):
        """ Test version selection """

        method_name = sys._getframe().f_code.co_name
        self._setUp(method_name)

        name = method_name
        self._create_or_update_param(name)

        param = SSMParameter("%s:1" % name)

        self.assertEqual(param.value, self.PARAM_VALUE)
        self.assertEqual(param.version, 1)

        # this will update the value and create version 2
        self._create_or_update_param(name, self.PARAM_VALUE_V2)

        param.refresh()

        self.assertEqual(param.value, self.PARAM_VALUE)
        self.assertEqual(param.version, 1)

        self._delete_param(name) 
Example #19
Source File: lex.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_caller_module_dict(levels):
    f = sys._getframe(levels)
    ldict = f.f_globals.copy()
    if f.f_globals != f.f_locals:
        ldict.update(f.f_locals)
    return ldict

# -----------------------------------------------------------------------------
# _funcs_to_names()
#
# Given a list of regular expression functions, this converts it to a list
# suitable for output to a table file
# ----------------------------------------------------------------------------- 
Example #20
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def exec_(_code_, _globs_=None, _locs_=None):
        """Execute code in a namespace."""
        if _globs_ is None:
            frame = sys._getframe(1)
            _globs_ = frame.f_globals
            if _locs_ is None:
                _locs_ = frame.f_locals
            del frame
        elif _locs_ is None:
            _locs_ = _globs_
        exec("""exec _code_ in _globs_, _locs_""") 
Example #21
Source File: prepareable.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __new__(cls, name, bases, attributes):
            try:
                constructor = attributes["__new__"]
            except KeyError:
                return type.__new__(cls, name, bases, attributes)

            def preparing_constructor(cls, name, bases, attributes):
                try:
                    cls.__prepare__
                except AttributeError:
                    return constructor(cls, name, bases, attributes)
                namespace = cls.__prepare__(name, bases)
                defining_frame = sys._getframe(1)
                for constant in reversed(defining_frame.f_code.co_consts):
                    if inspect.iscode(constant) and constant.co_name == name:
                        def get_index(attribute_name, _names=constant.co_names):
                            try:
                                return _names.index(attribute_name)
                            except ValueError:
                                return 0
                        break
                else:
                    return constructor(cls, name, bases, attributes)

                by_appearance = sorted(
                    attributes.items(), key=lambda item: get_index(item[0])
                )
                for key, value in by_appearance:
                    namespace[key] = value
                return constructor(cls, name, bases, namespace)
            attributes["__new__"] = wraps(constructor)(preparing_constructor)
            return type.__new__(cls, name, bases, attributes) 
Example #22
Source File: test_code.py    From py with MIT License 5 votes vote down vote up
def test_frame_getsourcelineno_myself():
    def func():
        return sys._getframe(0)
    f = func()
    f = py.code.Frame(f)
    source, lineno = f.code.fullsource, f.lineno
    assert source[lineno].startswith("        return sys._getframe(0)") 
Example #23
Source File: newsuper.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def superm(*args, **kwds):
    f = sys._getframe(1)
    nm = f.f_code.co_name
    return getattr(newsuper(framedepth=2),nm)(*args, **kwds) 
Example #24
Source File: __init__.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def exec_(code, globs=None, locs=None):
        """Execute code in a namespace."""
        if globs is None:
            frame = sys._getframe(1)
            globs = frame.f_globals
            if locs is None:
                locs = frame.f_locals
            del frame
        elif locs is None:
            locs = globs
        exec("""exec code in globs, locs""")


# Defined here for backward compatibility: 
Example #25
Source File: yacc.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_caller_module_dict(levels):
    f = sys._getframe(levels)
    ldict = f.f_globals.copy()
    if f.f_globals != f.f_locals:
        ldict.update(f.f_locals)
    return ldict

# -----------------------------------------------------------------------------
# parse_grammar()
#
# This takes a raw grammar rule string and parses it into production data
# ----------------------------------------------------------------------------- 
Example #26
Source File: newsuper.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def superm(*args, **kwds):
    f = sys._getframe(1)
    nm = f.f_code.co_name
    return getattr(newsuper(framedepth=2),nm)(*args, **kwds) 
Example #27
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def exec_(_code_, _globs_=None, _locs_=None):
        """Execute code in a namespace."""
        if _globs_ is None:
            frame = sys._getframe(1)
            _globs_ = frame.f_globals
            if _locs_ is None:
                _locs_ = frame.f_locals
            del frame
        elif _locs_ is None:
            _locs_ = _globs_
        exec("""exec _code_ in _globs_, _locs_""") 
Example #28
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def exec_(_code_, _globs_=None, _locs_=None):
        """Execute code in a namespace."""
        if _globs_ is None:
            frame = sys._getframe(1)
            _globs_ = frame.f_globals
            if _locs_ is None:
                _locs_ = frame.f_locals
            del frame
        elif _locs_ is None:
            _locs_ = _globs_
        exec("""exec _code_ in _globs_, _locs_""") 
Example #29
Source File: prepareable.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __new__(cls, name, bases, attributes):
            try:
                constructor = attributes["__new__"]
            except KeyError:
                return type.__new__(cls, name, bases, attributes)

            def preparing_constructor(cls, name, bases, attributes):
                try:
                    cls.__prepare__
                except AttributeError:
                    return constructor(cls, name, bases, attributes)
                namespace = cls.__prepare__(name, bases)
                defining_frame = sys._getframe(1)
                for constant in reversed(defining_frame.f_code.co_consts):
                    if inspect.iscode(constant) and constant.co_name == name:
                        def get_index(attribute_name, _names=constant.co_names):
                            try:
                                return _names.index(attribute_name)
                            except ValueError:
                                return 0
                        break
                else:
                    return constructor(cls, name, bases, attributes)

                by_appearance = sorted(
                    attributes.items(), key=lambda item: get_index(item[0])
                )
                for key, value in by_appearance:
                    namespace[key] = value
                return constructor(cls, name, bases, namespace)
            attributes["__new__"] = wraps(constructor)(preparing_constructor)
            return type.__new__(cls, name, bases, attributes) 
Example #30
Source File: six.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def exec_(_code_, _globs_=None, _locs_=None):
        """Execute code in a namespace."""
        if _globs_ is None:
            frame = sys._getframe(1)
            _globs_ = frame.f_globals
            if _locs_ is None:
                _locs_ = frame.f_locals
            del frame
        elif _locs_ is None:
            _locs_ = _globs_
        exec("""exec _code_ in _globs_, _locs_""")