Here are the examples of the python api sys._getframe.f_back taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
67 Examples
3
Example 1
@property
def db(self):
import sys
dbg = _get_debugger()
set_interrupt_handler()
dbg.set_trace(sys._getframe().f_back)
3
Example 2
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: inline_tools.py
def inline_function_code(code,arg_names,local_dict=None,
global_dict=None,auto_downcast=1,
type_converters=None,compiler=''):
call_frame = sys._getframe().f_back
if local_dict is None:
local_dict = call_frame.f_locals
if global_dict is None:
global_dict = call_frame.f_globals
ext_func = inline_ext_function('compiled_func',code,arg_names,
local_dict,global_dict,auto_downcast,
type_converters=type_converters)
from . import build_tools
compiler = build_tools.choose_compiler(compiler)
ext_func.set_compiler(compiler)
return ext_func.function_code()
3
Example 3
def set_trace():
from .debugger import BugBuzz
api_url = os.getenv('BUGBUZZ_API', 'https://bugbuzz-api.herokuapp.com')
db_url = os.getenv(
'BUGBUZZ_DASHBOARD',
'http://dashboard.bugbuzz.io/'
)
BugBuzz(api_url, db_url).set_trace(sys._getframe().f_back)
3
Example 4
Project: feat Source File: fiber.py
def _get_base_frame(depth):
# Go up the frame stack to the base frame given it's deepness.
# Go up one level more to account for this function own frame.
if depth < 0:
return None
base_frame = sys._getframe().f_back
while base_frame and depth >= 0:
depth -= 1
base_frame = base_frame.f_back
return base_frame
3
Example 5
Project: trtools Source File: trace.py
def set_trace(self, frame=None):
"""
"""
update_stdout()
wrap_sys_excepthook()
if frame is None:
frame = sys._getframe().f_back
#pdb = Tdb(def_colors)
self.reset()
self.set_step()
sys.settrace(self.trace_dispatch)
3
Example 6
def no_jump_without_trace_function():
try:
previous_frame = sys._getframe().f_back
previous_frame.f_lineno = previous_frame.f_lineno
except ValueError as e:
# This is the exception we wanted; make sure the error message
# talks about trace functions.
if 'trace' not in str(e):
raise
else:
# Something's wrong - the expected exception wasn't raised.
raise RuntimeError("Trace-function-less jump failed to fail")
3
Example 7
Project: gauge-python Source File: python.py
def step(step_text):
def _step(func):
f_back = sys._getframe().f_back
registry.add_step(step_text, func, f_back.f_code.co_filename, inspect.getsourcelines(func)[1])
return func
return _step
3
Example 8
def set_trace():
import sys
dbg = _get_debugger()
set_interrupt_handler()
dbg.set_trace(sys._getframe().f_back)
3
Example 9
def __init__(self,name,code_block, args, local_dict=None, global_dict=None,
auto_downcast=1, type_converters=None):
call_frame = sys._getframe().f_back
if local_dict is None:
local_dict = call_frame.f_locals
if global_dict is None:
global_dict = call_frame.f_globals
if type_converters is None:
type_converters = converters.default
arg_specs = assign_variable_types(args,local_dict, global_dict,
auto_downcast, type_converters)
ext_function_from_specs.__init__(self,name,code_block,arg_specs)
3
Example 10
Project: pytest Source File: debugging.py
def set_trace(self):
""" invoke PDB set_trace debugging, dropping any IO capturing. """
import _pytest.config
frame = sys._getframe().f_back
if self._pluginmanager is not None:
capman = self._pluginmanager.getplugin("capturemanager")
if capman:
capman.suspendcapture(in_=True)
tw = _pytest.config.create_terminal_writer(self._config)
tw.line()
tw.sep(">", "PDB set_trace (IO-capturing turned off)")
self._pluginmanager.hook.pytest_enter_pdb(config=self._config)
self._pdb_cls().set_trace(frame)
3
Example 11
def set_trace():
"""
can be called like pdb.set_trace()
"""
instance = make_instance()
instance.set_trace(sys._getframe().f_back)
3
Example 12
Project: mikidown Source File: utils.py
def debugTrace():
from PyQt5.QtCore import pyqtRemoveInputHook, pyqtRestoreInputHook
import pdb
import sys
pyqtRemoveInputHook()
try:
debugger = pdb.Pdb()
debugger.reset()
debugger.do_next(None)
user_frame = sys._getframe().f_back
debugger.interaction(user_frame, None)
finally:
pyqtRestoreInputHook()
3
Example 13
Project: EventGhost Source File: Log.py
def PrintStack(self, skip=0):
strs = [
'Stack trace (most recent call last) (%s):\n' % eg.Version.string
]
strs += format_stack(sys._getframe().f_back)[skip:]
error = "".join(strs)
self.Write(error.rstrip() + "\n", ERROR_ICON)
if eg.debugLevel:
sys.stderr.write(error)
3
Example 14
def set_trace(frame=None, context=3):
wrap_sys_excepthook()
if frame is None:
frame = sys._getframe().f_back
p = _init_pdb(context).set_trace(frame)
if p and hasattr(p, 'shell'):
p.shell.restore_sys_module_state()
3
Example 15
def no_jump_without_trace_function():
try:
previous_frame = sys._getframe().f_back
previous_frame.f_lineno = previous_frame.f_lineno
except ValueError, e:
# This is the exception we wanted; make sure the error message
# talks about trace functions.
if 'trace' not in str(e):
raise
else:
# Something's wrong - the expected exception wasn't raised.
raise RuntimeError, "Trace-function-less jump failed to fail"
3
Example 16
def set_trace(self, frame=None):
if frame is None:
frame = sys._getframe().f_back
try:
Pdb.set_trace(self, frame)
except IOError as exc:
if exc.errno != errno.ECONNRESET:
raise
3
Example 17
def set_trace(self, frame=None):
# start debugger interaction immediatelly
if frame is None:
frame = sys._getframe().f_back
self._wait_for_mainpyfile = frame.f_code.co_filename
self._wait_for_breakpoint = 0
bdb.Bdb.set_trace(self, frame)
3
Example 18
def set_continue(self):
# Don't stop except at breakpoints or when finished
self._set_stopinfo(self.botframe, None)
if not self.breaks:
# no breakpoints; run without debugger overhead
frame = sys._getframe().f_back
while frame and frame is not self.botframe:
del frame.f_trace
frame = frame.f_back
3
Example 19
Project: pyp2rpm Source File: pdb.py
def set_trace(self):
""" invoke PDB set_trace debugging, dropping any IO capturing. """
frame = sys._getframe().f_back
item = self.item or self.collector
if item is not None:
capman = item.config.pluginmanager.getplugin("capturemanager")
out, err = capman.suspendcapture()
if hasattr(item, 'outerr'):
item.outerr = (item.outerr[0] + out, item.outerr[1] + err)
tw = py.io.TerminalWriter()
tw.line()
tw.sep(">", "PDB set_trace (IO-capturing turned off)")
py.std.pdb.Pdb().set_trace(frame)
3
Example 20
def set_trace(self, frame=None):
# start debugger interaction immediatelly
if frame is None:
frame = sys._getframe().f_back
self._wait_for_mainpyfile = frame.f_code.co_filename
self._wait_for_breakpoint = 0
# reinitialize debugger internal settings
self.fast_continue = False
bdb.Bdb.set_trace(self, frame)
3
Example 21
def set_trace(self, frame=None, start=0):
"""Start debugging from `frame`, or `start` frames back from
caller's frame.
If frame is not specified, debugging starts from caller's frame.
"""
if frame is None:
frame = sys._getframe().f_back
self.reset()
if start:
start = int(start)
while start > 0 and frame:
frame = frame.f_back
start -= 1
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_step()
sys.settrace(self.trace_dispatch)
3
Example 22
def _set_trace(self, skip=0):
"""Start debugging from here."""
frame = sys._getframe().f_back
# go up the specified number of frames
for i in range(0,skip):
frame = frame.f_back
self.reset()
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_step()
sys.settrace(self.trace_dispatch)
3
Example 23
def do_debug(self, mainpyfile=None, wait_breakpoint=1):
self.reset()
if not wait_breakpoint or mainpyfile:
self._wait_for_mainpyfile = 1
if not mainpyfile:
frame = sys._getframe().f_back
mainpyfile = frame.f_code.co_filename
self.mainpyfile = self.canonic(mainpyfile)
self._wait_for_breakpoint = wait_breakpoint
sys.settrace(self.trace_dispatch)
3
Example 24
def inline(n=5, m=10000):
if n:
return inline(n - 1, m)
for i in range(m):
f = sys._getframe().f_back
code_list = []
while f:
code_list.append(f.f_code)
code_list.append(f.f_lineno)
f = f.f_back
3
Example 25
Project: support Source File: exceptions.py
def current_code_list():
'Returns a code-list that can be formatted by code_list2trace_list'
f = sys._getframe().f_back
code_list = []
while f:
code_list.append(f.f_code)
code_list.append(f.f_lineno)
f = f.f_back
return code_list
3
Example 26
def set_trace(stop=True, **kwargs):
"""
Begins tracing from this point.
All arguments except for stackframe are passed to the constructor of the
internal Qdb object.
This function will continue to act on the same Qdb object until disable()
is called.
"""
Qdb(**kwargs).set_trace(sys._getframe().f_back, stop=stop)
3
Example 27
def set_trace(self, stackframe=None, stop=True):
"""
Starts debugging in stackframe or in the callers frame.
If stop is True, begin stepping from here, otherwise, wait for
the first breakpoint or exception.
"""
# We need to look back 1 frame to get our caller.
stackframe = stackframe or sys._getframe().f_back
self.reset()
while stackframe:
stackframe.f_trace = self.trace_dispatch
self.botframe = stackframe
stackframe = stackframe.f_back
if stop:
self.set_step()
else:
self.set_continue()
sys.settrace(self.trace_dispatch)
3
Example 28
def set_trace(host='127.0.0.1', port=0, patch_stdstreams=False):
"""
Opens a remote PDB on first available port.
"""
rdb = RemotePdb(host=host, port=port, patch_stdstreams=patch_stdstreams)
rdb.set_trace(frame=sys._getframe().f_back)
3
Example 29
def __init__( self, name, *alternates ):
"""Initialize set of alternative implementations of the same function"""
self.__name__ = name
self._alternatives = alternates
if root.MODULE_ANNOTATIONS:
frame = sys._getframe().f_back
if frame and frame.f_back and '__name__' in frame.f_back.f_globals:
self.__module__ = frame.f_back.f_globals['__name__']
3
Example 30
def set_trace(self, frame=None):
"""Start debugging from `frame`.
If frame is not specified, debugging starts from caller's frame.
"""
if frame is None:
frame = sys._getframe().f_back
self.reset()
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_step()
sys.settrace(self.trace_dispatch)
3
Example 31
def contexts(self):
frame = sys._getframe().f_back
while frame:
ls = frame.f_locals.get('__ctx__', None)
if ls:
for ctx in ls:
yield ctx
frame = sys._getframe().f_back
0
Example 32
Project: owasp-pysec Source File: intern.py
def get_frame_type(frame=None, get_module=None):
"""Return information about a frame: (frame_type, module)
*type* could be: FRAME_EXEC, FRAME_MODULE, FRAME_CLASS,
FRAME_FUNCTION, FRAME_UNKNOWN
If *frame* is None, the caller frame will be used.
If *get_module* is None, the module will be searched in sys.path.
If *get_module* don't find the module, it must return None.
"""
if frame is None:
frame = sys._getframe().f_back
f_locals = frame.f_locals
f_globals = frame.f_globals
same_namespace = f_locals is f_globals
loc_module = f_locals.get('__module__', None)
glb_name = f_globals.get('__name__', None)
same_name = loc_module and glb_name and loc_module == glb_name
if get_module is None:
get_module = lambda mod: sys.modules.get(mod, None)
module = get_module(glb_name)
if not (module and module.__dict__ is f_globals):
ftype = FRAME_EXEC
elif same_namespace and not loc_module:
ftype = FRAME_MODULE
elif same_name and not same_namespace:
ftype = FRAME_CLASS
elif not same_namespace:
ftype = FRAME_FUNCTION
else:
ftype = FRAME_UNKNOWN
return ftype
0
Example 33
def set_trace(self):
self.__debugger_used = True
_orp.set_trace(self, sys._getframe().f_back)
0
Example 34
def getvar(name, frame=None):
"""Search a name in local scope, global scope, and in builtins"""
if frame is None:
frame = sys._getframe().f_back
val = frame.f_locals.get(name, NORESULT)
if val is not NORESULT:
return SCOPE_LOCAL, val
val = frame.f_globals.get(name, NORESULT)
if val is not NORESULT:
return SCOPE_GLOBAL, val
builtins = frame.f_globals.get('__builtins__', NORESULT)
if builtins is not NORESULT:
if type(builtins) is type({}):
val = builtins.get(name, NORESULT)
if val is not NORESULT:
return SCOPE_BUILTIN, val
else:
val = getattr(builtins, name, NORESULT)
if val is not NORESULT:
return SCOPE_BUILTIN, val
return None, None
0
Example 35
Project: qdb Source File: utils.py
def progn(src, eval_fn=None, stackframe=None):
"""
Evaluate all expressions and statments in src, returns the result of the
last expression or raises a QdbPrognEndsInStatement if the last thing is a
statement.
eval_fn is the function to evaluate the src with and should conform to the
same standards as the Qdb class's eval_fn param.
stackframe is the context to evaluate src in, if None, it will be the
calling stackframe.
"""
eval_fn = eval_fn or default_eval_fn
register_name = isolate_namespace('register')
code = register_last_expr(ast.parse(src), register_name)
stackframe = stackframe or sys._getframe().f_back
store = {}
def register(expr):
"""
Store the last expression's result.
"""
store['expr'] = expr
return expr
# Add the register function to the namespace.
stackframe.f_globals[register_name] = register
try:
eval_fn(code, stackframe, 'exec', original=src)
finally:
# Always remove the register function from the namespace.
# This is to not fill the namespace after multiple calls to progn.
del stackframe.f_globals[register_name]
try:
# Attempt to retrieve the last expression.
return store['expr']
except KeyError:
# There was no final expression.
raise QdbPrognEndsInStatement(src)
0
Example 36
Project: ayrton Source File: remote.py
def __exit__ (self, *args):
logger.debug (args)
data= b''
partial= self.result_channel.recv (8196)
while len(partial)>0:
data+= partial
partial= self.result_channel.recv (8196)
logger.debug ('recieved %d bytes', len (data))
(l, result, e)= pickle.loads (data)
logger.debug ('result from remote: %r', result)
logger.debug3 ('locals returned from remote: %s', ayrton.utils.dump_dict (l))
logger.debug ('closing %s', self.result_channel)
self.result_channel.close ()
logger.debug ('closing %s', self.result_listen)
self.result_listen.close ()
logger.debug ('closing %s', self.remote)
self.remote.close ()
# update locals
callers_frame= sys._getframe().f_back
logger.debug3 ('caller name: %s', callers_frame.f_code.co_name)
callers_frame.f_locals.update (l)
# see https://mail.python.org/pipermail/python-dev/2005-January/051018.html
ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(callers_frame), 0)
if self._debug:
# this makes sure that remote locals were properly store in the fast locals
ctypes.pythonapi.PyFrame_FastToLocals(ctypes.py_object(callers_frame))
# TODO: (and globals?)
logger.debug3 ('globals after remote: %s', ayrton.utils.dump_dict (ayrton.runner.globals))
logger.debug3 ('locals after remote: %s', ayrton.utils.dump_dict (callers_frame.f_locals))
logger.debug3 ('co_varnames: %s', callers_frame.f_code.co_varnames)
if e is not None:
logger.debug ('raised from remote: %r', e)
# TODO: this makes the exception be as if raised from here
raise e
0
Example 37
def gdb():
"""Enter pdb in Google App Engine. """
pdb.Pdb(stdin=getattr(sys, '__stdin__'),
stdout=getattr(sys, '__stderr__')).set_trace(sys._getframe().f_back)
0
Example 38
def set_trace():
Pdb().set_trace(sys._getframe().f_back)
0
Example 39
def set_trace():
"breakpoint shortcut (like pdb)"
logger.info("DEBUG: set_trace!")
debugger.set_trace(sys._getframe().f_back)
0
Example 40
def _stop():
import pdb
pdb.Pdb().set_trace(sys._getframe().f_back)
0
Example 41
Project: viewfinder Source File: operation.py
@classmethod
@gen.coroutine
def TriggerFailpoint(cls, client):
"""Raises a non-abortable exception in order to cause the operation to restart. Only raises
the exception if this failpoint has not yet been triggered for this operation.
This facility is useful for testing operation idempotency in failure situations.
"""
# Check whether failpoint support is enabled.
if not Operation.FAILPOINTS_ENABLED:
return
op = Operation.GetCurrent()
assert op.operation_id is not None, \
'TriggerFailpoint can only be called in scope of executing operation'
# Get list of previously triggered failpoints for this operation.
triggered_failpoints = op.triggered_failpoints or []
# Check whether this failpoint has already been triggered for this operation.
frame = sys._getframe().f_back
trigger_point = [frame.f_code.co_filename, frame.f_lineno]
if trigger_point in triggered_failpoints:
return
# This is first time the failpoint has been triggered, so trigger it now and save it to the op.
triggered_failpoints.append(trigger_point)
op = Operation.CreateFromKeywords(user_id=op.user_id,
operation_id=op.operation_id,
triggered_failpoints=list(triggered_failpoints))
yield gen.Task(op.Update, client)
raise FailpointError(*trigger_point)
0
Example 42
def set_trace(host='', port=5555, patch_stdstreams=False):
"""
Start the debugger
This method suspends execution of the current script
and starts a PDB debugging session. The web-interface is opened
on the specified port (default: ``5555``).
Example::
import web_pdb;web_pdb.set_trace()
Subsequent :func:`set_trace` calls can be used as hardcoded breakpoints.
:param host: web-UI hostname or IP-address
:type host: str
:param port: web-UI port. If ``port=-1``, choose a random port value
between 32768 and 65536.
:type port: int
:param patch_stdstreams: redirect all standard input and output
streams to the web-UI.
:type patch_stdstreams: bool
"""
pdb = WebPdb.active_instance
if pdb is None:
pdb = WebPdb(host, port, patch_stdstreams)
else:
# If the debugger is still attached reset trace to a new location
pdb.remove_trace()
pdb.set_trace(sys._getframe().f_back)
0
Example 43
Project: canvas Source File: sql.py
def execute(self, sql, params=()):
start = datetime.now()
try:
return self.cursor.execute(sql, params)
finally:
stop = datetime.now()
duration = ms_from_timedelta(stop - start)
stacktrace = tidy_stacktrace(traceback.extract_stack())
_params = ''
try:
_params = simplejson.dumps([force_unicode(x, strings_only=True) for x in params])
except TypeError:
pass # object not JSON serializable
template_info = None
cur_frame = sys._getframe().f_back
try:
while cur_frame is not None:
if cur_frame.f_code.co_name == 'render':
node = cur_frame.f_locals['self']
if isinstance(node, Node):
template_info = get_template_info(node.source)
break
cur_frame = cur_frame.f_back
except:
pass
del cur_frame
# We keep `sql` to maintain backwards compatibility
self.db.queries.append({
'sql': self.db.ops.last_executed_query(self.cursor, sql, params),
'duration': duration,
'raw_sql': sql,
'params': _params,
'hash': sha_constructor(settings.SECRET_KEY + sql + _params).hexdigest(),
'stacktrace': stacktrace,
'start_time': start,
'stop_time': stop,
'is_slow': (duration > SQL_WARNING_THRESHOLD),
'is_select': sql.lower().strip().startswith('select'),
'template_info': template_info,
})
0
Example 44
def __enter__(self):
self.set_trace(sys._getframe().f_back, stop=False)
return self
0
Example 45
def set_trace(*args, **kwargs):
"""Wrapper function to keep the same import x; x.set_trace() interface.
We catch all the possible exceptions from pdb and cleanup.
"""
if not args and 'DEFAULT_IRCPDB_URI' in os.environ:
args = (
os.environ['DEFAULT_IRCPDB_URI'],
)
debugger = Ircpdb(*args, **kwargs)
try:
irc_feeder = Thread(
target=debugger.bot.process_forever,
args=(debugger.b_B_pipe, debugger.b_A_pipe, ),
)
irc_feeder.daemon = True
irc_feeder.start()
debugger.set_trace(sys._getframe().f_back)
except Exception:
debugger.shutdown()
traceback.print_exc()
0
Example 46
def set_trace():
Ripdb().set_trace(sys._getframe().f_back)
0
Example 47
Project: drawquest-web Source File: sql.py
def execute(self, sql, params=()):
start = datetime.now()
try:
return self.cursor.execute(sql, params)
finally:
stop = datetime.now()
duration = ms_from_timedelta(stop - start)
stacktrace = tidy_stacktrace(traceback.extract_stack())
_params = ''
try:
_params = simplejson.dumps([force_unicode(x, strings_only=True) for x in params])
except TypeError:
pass # object not JSON serializable
template_info = None
cur_frame = sys._getframe().f_back
try:
while cur_frame is not None:
if cur_frame.f_code.co_name == 'render':
node = cur_frame.f_locals['self']
if isinstance(node, Node):
template_info = get_template_info(node.source)
break
cur_frame = cur_frame.f_back
except:
pass
del cur_frame
# We keep `sql` to maintain backwards compatibility
self.db.queries.append({
'sql': self.db.ops.last_executed_query(self.cursor, sql, params),
'duration': duration,
'raw_sql': sql,
'params': _params,
'hash': sha1(settings.SECRET_KEY + sql + _params).hexdigest(),
'stacktrace': stacktrace,
'start_time': start,
'stop_time': stop,
'is_slow': (duration > SQL_WARNING_THRESHOLD),
'is_select': sql.lower().strip().startswith('select'),
'template_info': template_info,
})
0
Example 48
Project: autotest Source File: logging_manager.py
def _logging_manager_aware_logger__find_caller(unused):
"""
Find the stack frame of the caller so that we can note the source
file name, line number and function name.
"""
f = sys._getframe(2).f_back
rv = "(unknown file)", 0, "(unknown function)"
while hasattr(f, "f_code"):
co = f.f_code
filename = os.path.normcase(co.co_filename)
if filename == logging._srcfile:
f = f.f_back
continue
# START additional code.
if co in _caller_code_to_skip_in_logging_stack:
f = f.f_back
continue
# END additional code.
rv = (filename, f.f_lineno, co.co_name)
break
return rv
0
Example 49
Project: sherpa Source File: data.py
def __init__(self):
"""
Initialize a data object. This method can only be called from
a derived class constructor. Attempts to create a BaseData
instance will raise NotImplementedErr.
Derived class constructors must call this method directly (and
not indirectly through a superclass constructor). When thus
invoked, this method will extract the argument names and
values from the derived class constructor invocation and set
corresponding attributes on the instance (thereby eliminating
the need for the derived class constructor to do its own
attribute setting). If the name of an argument matches the
name of a DataProperty of the derived class, then the
corresponding attribute name will have an underscore prepended
(meaning the property will use the value directly instead of
relying on _get_*/_set_* methods).
"""
if type(self) is BaseData:
raise NotImplementedErr('noinstanceallowed', 'BaseData')
frame = sys._getframe().f_back
cond = (frame.f_code is self.__init__.__func__.__code__)
assert cond, (('%s constructor must call BaseData constructor ' +
'directly') % type(self).__name__)
args = inspect.getargvalues(frame)
self._fields = tuple(args[0][1:])
for f in self._fields:
cond = (f not in vars(self))
assert cond, (("'%s' object already has attribute '%s'") %
(type(self).__name__, f))
setattr(self, f, args[3][f])
self.filter = None
self.mask = True
NoNewAttributesAfterInit.__init__(self)
0
Example 50
def __enter__(self):
frame = sys._getframe().f_back
contexts = frame.f_locals.setdefault('__ctx__', [])
contexts.append(self)