Here are the examples of the python api sys.gettrace taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
86 Examples
5
Source : Console.py
with MIT License
from 3fon3fonov
with MIT License
from 3fon3fonov
def updateSysTrace(self):
## Install or uninstall sys.settrace handler
if not self.ui.catchNextExceptionBtn.isChecked() and not self.ui.catchAllExceptionsBtn.isChecked():
if sys.gettrace() == self.systrace:
sys.settrace(None)
return
if self.ui.onlyUncaughtCheck.isChecked():
if sys.gettrace() == self.systrace:
sys.settrace(None)
else:
if sys.gettrace() is not None and sys.gettrace() != self.systrace:
self.ui.onlyUncaughtCheck.setChecked(False)
raise Exception("sys.settrace is in use; cannot monitor for caught exceptions.")
else:
sys.settrace(self.systrace)
def exceptionHandler(self, excType, exc, tb, systrace=False, frame=None):
5
Source : Console.py
with MIT License
from octaviaguo
with MIT License
from octaviaguo
def updateSysTrace(self):
## Install or uninstall sys.settrace handler
if not self.ui.catchNextExceptionBtn.isChecked() and not self.ui.catchAllExceptionsBtn.isChecked():
if sys.gettrace() == self.systrace:
sys.settrace(None)
return
if self.ui.onlyUncaughtCheck.isChecked():
if sys.gettrace() == self.systrace:
sys.settrace(None)
else:
if sys.gettrace() is not None and sys.gettrace() != self.systrace:
self.ui.onlyUncaughtCheck.setChecked(False)
raise Exception("sys.settrace is in use; cannot monitor for caught exceptions.")
else:
sys.settrace(self.systrace)
def exceptionHandler(self, excType, exc, tb, systrace=False):
3
Source : pickletester.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def no_tracing(func):
"""Decorator to temporarily turn off tracing for the duration of a test."""
if not hasattr(sys, 'gettrace'):
return func
else:
def wrapper(*args, **kwargs):
original_trace = sys.gettrace()
try:
sys.settrace(None)
return func(*args, **kwargs)
finally:
sys.settrace(original_trace)
wrapper.__name__ = func.__name__
return wrapper
# Return True if opcode code appears in the pickle, else False.
def opcode_in_pickle(code, pickle):
3
Source : support.py
with Apache License 2.0
from almeidaw
with Apache License 2.0
from almeidaw
def no_tracing(func):
"""Decorator to temporarily turn off tracing for the duration of a test."""
if not hasattr(sys, 'gettrace'):
return func
else:
@functools.wraps(func)
def wrapper(*args, **kwargs):
original_trace = sys.gettrace()
try:
sys.settrace(None)
return func(*args, **kwargs)
finally:
sys.settrace(original_trace)
return wrapper
def refcount_test(test):
3
Source : test_script.py
with MIT License
from autofelix
with MIT License
from autofelix
def test_tracerInstalled(self):
"""
L{trial.Options} handles C{"--coverage"} by installing a trace
hook to record coverage information.
"""
options = trial.Options()
options.parseOptions(["--coverage"])
self.assertEqual(sys.gettrace(), options.tracer.globaltrace)
def test_coverdirDefault(self):
3
Source : test_bdb.py
with MIT License
from bkerler
with MIT License
from bkerler
def __enter__(self):
# test_pdb does not reset Breakpoint class attributes on exit :-(
reset_Breakpoint()
self._original_tracer = sys.gettrace()
return self.tracer
def __exit__(self, type_=None, value=None, traceback=None):
3
Source : trace.py
with GNU General Public License v3.0
from CherryKodi
with GNU General Public License v3.0
from CherryKodi
def start(self):
"""Start traceing."""
#xbmc.log('[XXX] Starting! ' + str(self.__details), xbmc.LOGNOTICE)
if not self.__runing:
if self.__details == TRACE_CALL:
self.__old_trace = sys.gettrace()
sys.settrace(self.log_trace)
elif self.__details == TRACE_CALL:
self.__old_trace = sys.getprofile()
sys.setprofile(self.log_trace)
else:
assert False, 'Incorect details level ({})'.format(self.__details)
return
self.__runing = True
def stop(self):
3
Source : tracer.py
with MIT License
from cool-RR
with MIT License
from cool-RR
def __enter__(self):
if DISABLED:
return
thread_global.__dict__.setdefault('depth', -1)
calling_frame = inspect.currentframe().f_back
if not self._is_internal_frame(calling_frame):
calling_frame.f_trace = self.trace
self.target_frames.add(calling_frame)
stack = self.thread_local.__dict__.setdefault(
'original_trace_functions', []
)
stack.append(sys.gettrace())
self.start_times[calling_frame] = datetime_module.datetime.now()
sys.settrace(self.trace)
def __exit__(self, exc_type, exc_value, exc_traceback):
3
Source : utils.py
with Apache License 2.0
from dashanji
with Apache License 2.0
from dashanji
def _no_tracing(func):
"""
Decorator to temporarily turn off tracing for the duration of a test.
Needed in tests that check refcounting, otherwise the tracing itself
influences the refcounts
"""
if not hasattr(sys, 'gettrace'):
return func
else:
@wraps(func)
def wrapper(*args, **kwargs):
original_trace = sys.gettrace()
try:
sys.settrace(None)
return func(*args, **kwargs)
finally:
sys.settrace(original_trace)
return wrapper
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def set_trace(trace_func):
"""Registers a call trace function which will be called for every
function call, and keeps a reference to any previously set trace function
in order to be able to restore it.
"""
global thread_locals
thread_locals.original_trace_func = sys.gettrace()
sys.settrace(trace_func)
def remove_trace():
3
Source : train.py
with MIT License
from eugenevinitsky
with MIT License
from eugenevinitsky
def get_experiment_name(args):
"""
Build an experiment name based on environment, model and algorithm.
:param args: The parsed arguments.
:return: The experiment name.
"""
if sys.gettrace() is not None:
exp_name = "debug_experiment"
elif args.exp_name is None:
exp_name = args.env + "_" + args.model + "_" + args.algorithm
else:
exp_name = args.exp_name
return exp_name
def build_experiment_dict(args, experiment_name, trainer, config):
3
Source : utils.py
with MIT License
from facebookresearch
with MIT License
from facebookresearch
def is_under_debugger() -> bool:
"""
Attempts to detect if running under a debugger
"""
frames = inspect.stack()
if len(frames) >= 3:
filename = frames[-3].filename
if filename.endswith("/pdb.py"):
return True
elif filename.endswith("/pydevd.py"):
return True
# unknown debugging will sometimes set sys.trace
return sys.gettrace() is not None
def create_automatic_config_search_path(
3
Source : test_lazyobject.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_trace(self):
# See ticket #19456
old_trace_func = sys.gettrace()
try:
def trace_func(frame, event, arg):
frame.f_locals['self'].__class__
if old_trace_func is not None:
old_trace_func(frame, event, arg)
sys.settrace(trace_func)
self.lazy_wrap(None)
finally:
sys.settrace(old_trace_func)
def test_none(self):
3
Source : conftest.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def restore_tracing():
"""Restore tracing function (when run with Coverage.py).
https://bugs.python.org/issue37011
"""
orig_trace = sys.gettrace()
yield
if sys.gettrace() != orig_trace:
sys.settrace(orig_trace)
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
3
Source : test_simplelazyobject.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_trace(self):
# See ticket #19456
old_trace_func = sys.gettrace()
try:
def trace_func(frame, event, arg):
frame.f_locals['self'].__class__
if old_trace_func is not None:
old_trace_func(frame, event, arg)
sys.settrace(trace_func)
SimpleLazyObject(None)
finally:
sys.settrace(old_trace_func)
def test_not_equal(self):
3
Source : withhacks.py
with MIT License
from MegaIng
with MIT License
from MegaIng
def _enable_tracing():
"""Enable system-wide tracing, if it wasn't already."""
global _orig_sys_trace
try:
_orig_sys_trace = sys.gettrace()
except AttributeError:
_orig_sys_trace = None
if _orig_sys_trace is None:
sys.settrace(_dummy_sys_trace)
def _disable_tracing():
3
Source : threads.py
with Mozilla Public License 2.0
from mozilla
with Mozilla Public License 2.0
from mozilla
def __init__(self, ident, name=None):
self.id = ident
self.name = name
if ident != -1:
self.name = "Unknown Thread " + text(ident)
self.child_locker = allocate_lock()
self.children = []
self.cprofiler = None
self.trace_func = sys.gettrace()
def add_child(self, child):
3
Source : _utils.py
with BSD 3-Clause "New" or "Revised" License
from omry
with BSD 3-Clause "New" or "Revised" License
from omry
def _raise(ex: Exception, cause: Exception) -> None:
# Set the environment variable OC_CAUSE=1 to get a stacktrace that includes the
# causing exception.
env_var = os.environ["OC_CAUSE"] if "OC_CAUSE" in os.environ else None
debugging = sys.gettrace() is not None
full_backtrace = (debugging and not env_var == "0") or (env_var == "1")
if full_backtrace:
ex.__cause__ = cause
else:
ex.__cause__ = None
raise ex.with_traceback(sys.exc_info()[2]) # set env var OC_CAUSE=1 for full trace
def format_and_raise(
3
Source : torch.py
with MIT License
from overlappredator
with MIT License
from overlappredator
def __exit__(self, type, value, trace):
super().__exit__()
if isinstance(value, RuntimeError):
traceback.print_tb(trace)
print(value)
if sys.gettrace() is None:
pdb.set_trace()
3
Source : tracer.py
with MIT License
from pedal-edu
with MIT License
from pedal-edu
def __enter__(self):
self.reset()
self._old_trace = sys.gettrace()
sys.settrace(self.trace_dispatch)
def __exit__(self, exc_type, exc_val, traceback):
3
Source : instrumentation_tracing.py
with MIT License
from react-native-skia
with MIT License
from react-native-skia
def no_tracing(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
trace_func = sys.gettrace()
try:
sys.settrace(None)
threading.settrace(None)
return f(*args, **kwargs)
finally:
sys.settrace(trace_func)
threading.settrace(trace_func)
return wrapper
def start_instrumenting(output_file, to_include=(), to_exclude=()):
3
Source : profilehooks.py
with GNU General Public License v3.0
from Soft8Soft
with GNU General Public License v3.0
from Soft8Soft
def __call__(self, *args, **kw):
"""Profile a singe call to the function."""
self.ncalls += 1
old_trace = sys.gettrace()
try:
return self.profiler.runcall(self.fn, args, kw)
finally: # pragma: nocover
sys.settrace(old_trace)
def atexit(self):
3
Source : profilehooks.py
with GNU General Public License v3.0
from Soft8Soft
with GNU General Public License v3.0
from Soft8Soft
def __call__(self, *args, **kw):
"""Profile a singe call to the function."""
self.ncalls += 1
if TraceFuncCoverage.tracing: # pragma: nocover
return self.fn(*args, **kw)
old_trace = sys.gettrace()
try:
TraceFuncCoverage.tracing = True
return self.tracer.runfunc(self.fn, *args, **kw)
finally: # pragma: nocover
sys.settrace(old_trace)
TraceFuncCoverage.tracing = False
def atexit(self):
3
Source : ftrace.py
with GNU General Public License v3.0
from vrthra
with GNU General Public License v3.0
from vrthra
def __enter__(self) -> None:
""" set hook """
self.out({'event': 'start', '$input': self.in_data})
self.oldtrace = sys.gettrace()
sys.settrace(self.method)
return self
def __exit__(self, typ: str, value: str, backtrace: Any) -> None:
3
Source : tracer.py
with Apache License 2.0
from ydf0509
with Apache License 2.0
from ydf0509
def __enter__(self):
if DISABLED:
return
calling_frame = inspect.currentframe().f_back
if not self._is_internal_frame(calling_frame):
calling_frame.f_trace = self.trace
self.target_frames.add(calling_frame)
stack = self.thread_local.__dict__.setdefault(
'original_trace_functions', []
)
stack.append(sys.gettrace())
sys.settrace(self.trace)
def __exit__(self, exc_type, exc_value, exc_traceback):
3
Source : test_snoop.py
with MIT License
from zasdfgbnm
with MIT License
from zasdfgbnm
def assert_output(verbose, expect):
torchsnooper.register_snoop(verbose=verbose)
with sys_tools.OutputCapturer(stdout=False, stderr=True) as output_capturer:
assert sys.gettrace() is None
snoop(func)()
assert sys.gettrace() is None
output = output_capturer.string_io.getvalue()
output = ansi_escape.sub('', output)
assert clean_output(output) == clean_output(expect)
snoop.config = default_config
def test_verbose():
0
Source : test_threading.py
with GNU General Public License v3.0
from adityaprakash-bobby
with GNU General Public License v3.0
from adityaprakash-bobby
def test_frame_tstate_tracing(self):
# Issue #14432: Crash when a generator is created in a C thread that is
# destroyed while the generator is still used. The issue was that a
# generator contains a frame, and the frame kept a reference to the
# Python state of the destroyed C thread. The crash occurs when a trace
# function is setup.
def noop_trace(frame, event, arg):
# no operation
return noop_trace
def generator():
while 1:
yield "generator"
def callback():
if callback.gen is None:
callback.gen = generator()
return next(callback.gen)
callback.gen = None
old_trace = sys.gettrace()
sys.settrace(noop_trace)
try:
# Install a trace function
threading.settrace(noop_trace)
# Create a generator in a C thread which exits after the call
_testcapi.call_in_temporary_c_thread(callback)
# Call the generator in a different Python thread, check that the
# generator didn't keep a reference to the destroyed thread state
for test in range(3):
# The trace function is still called here
callback()
finally:
sys.settrace(old_trace)
class ThreadingExceptionTests(BaseTestCase):
0
Source : mp.py
with Apache License 2.0
from allegroai
with Apache License 2.0
from allegroai
def _background_process_start(cls, task_obj_id, event_start=None, parent_pid=None):
# type: (int, Optional[SafeEvent], Optional[int]) -> None
is_debugger_running = bool(getattr(sys, 'gettrace', None) and sys.gettrace())
# make sure we update the pid to our own
cls._main_process = os.getpid()
cls._main_process_proc_obj = psutil.Process(cls._main_process)
# restore original signal, this will prevent any deadlocks
# Do not change the exception we need to catch base exception as well
# noinspection PyBroadException
try:
from ... import Task
# make sure we do not call Task.current_task() it will create a Task object for us on a subprocess!
# noinspection PyProtectedMember
if Task._has_current_task_obj():
# noinspection PyProtectedMember
Task.current_task()._remove_at_exit_callbacks()
except: # noqa
pass
# if a debugger is running, wait for it to attach to the subprocess
if is_debugger_running:
sleep(3)
instances = BackgroundMonitor._instances.get(task_obj_id, [])
# launch all the threads
for d in instances:
d._start()
if cls._sub_process_started:
cls._sub_process_started.set()
if event_start:
event_start.set()
# wait until we are signaled
for i in instances:
# DO NOT CHANGE, we need to catch base exception, if the process gte's killed
try:
while i._thread is None or (i._thread and i._thread.is_alive()):
# thread is still not up
if i._thread is None:
sleep(0.1)
continue
# noinspection PyBroadException
try:
p = psutil.Process(parent_pid)
parent_alive = p.is_running() and p.status() != psutil.STATUS_ZOMBIE
except Exception:
parent_alive = False
# if parent process is not here we should just leave!
if not parent_alive:
return
# DO NOT CHANGE, we need to catch base exception, if the process gte's killed
try:
# timeout so we can detect if the parent process got killed.
i._thread.join(timeout=30.)
except: # noqa
break
except: # noqa
pass
# we are done, leave process
return
def is_alive(self):
0
Source : state.py
with GNU General Public License v3.0
from autogram
with GNU General Public License v3.0
from autogram
async def _call_and_jump(func, target, coro_locals, *args, kwargs):
def _trace_global(frame, event, arg):
# print(frame, event, arg)
if event == "call" and frame.f_code is func.__code__:
return _trace_local
def _trace_local(frame, event, arg):
# print(frame, event, arg)
if event == "line" and frame.f_code is func.__code__:
if getattr(_trace_state, "first", True):
frame.f_lineno = frame.f_lineno + target - 1
_trace_state.first = False
return None
else:
_trace_state.first = True
return _trace_local
oldtrace = sys.gettrace()
sys.settrace(_trace_global)
inspect.currentframe().f_trace = _trace_global
try:
ret = func(*args, **kwargs)
try:
fut = ret.send(None)
except StopIteration:
fut = None
finally:
sys.settrace(oldtrace)
inspect.currentframe().f_trace = oldtrace
return ret, fut
0
Source : save_env.py
with MIT License
from bkerler
with MIT License
from bkerler
def get_sys_gettrace(self):
return sys.gettrace()
def restore_sys_gettrace(self, trace_fxn):
0
Source : pdb_patch.py
with MIT License
from bogdanvuk
with MIT License
from bogdanvuk
def patch_pdb():
tr = sys.gettrace();
if tr:
if not hasattr(tr, '__self__'):
return
p = tr.__self__
if p is not None:
p.stop_here = stop_here.__get__(p, pdb.Pdb)
p.do_up = do_up.__get__(p, pdb.Pdb)
p.do_down = do_down.__get__(p, pdb.Pdb)
p.do_u = do_up.__get__(p, pdb.Pdb)
p.do_d = do_down.__get__(p, pdb.Pdb)
p.print_stack_trace = print_stack_trace.__get__(p, pdb.Pdb)
pdb.Pdb.stop_here = stop_here
pdb.Pdb.do_up = do_up
pdb.Pdb.do_down = do_down
pdb.Pdb.do_u = do_up
pdb.Pdb.do_d = do_down
pdb.Pdb.print_stack_trace = print_stack_trace
def unpatch_pdb():
0
Source : pdb_patch.py
with MIT License
from bogdanvuk
with MIT License
from bogdanvuk
def unpatch_pdb():
importlib.reload(pdb)
tr = sys.gettrace();
if tr:
if not hasattr(tr, '__self__'):
return
p = tr.__self__
if p is None:
return
if inspect.getfile(p.stop_here) == __file__:
p.stop_here = pdb.Pdb.stop_here.__get__(p, pdb.Pdb)
p.do_up = pdb.Pdb.do_up.__get__(p, pdb.Pdb)
p.do_down = pdb.Pdb.do_down.__get__(p, pdb.Pdb)
p.do_u = pdb.Pdb.do_up.__get__(p, pdb.Pdb)
p.do_d = pdb.Pdb.do_down.__get__(p, pdb.Pdb)
p.print_stack_trace = pdb.Pdb.print_stack_trace.__get__(p, pdb.Pdb)
0
Source : debugger.py
with Apache License 2.0
from CadQuery
with Apache License 2.0
from CadQuery
def debug(self,value):
previous_trace = sys.gettrace()
if value:
self.sigDebugging.emit(True)
self.state = DbgState.STEP
self.script = self.get_current_script()
code,module = self.compile_code(self.script)
if code is None:
self.sigDebugging.emit(False)
self._actions['Run'][1].setChecked(False)
return
cq_objects,injected_names = self._inject_locals(module)
#clear possible traceback
self.sigTraceback.emit(None,
self.script)
try:
sys.settrace(self.trace_callback)
exec(code,module.__dict__,module.__dict__)
except Exception:
exc_info = sys.exc_info()
sys.last_traceback = exc_info[-1]
self.sigTraceback.emit(exc_info,
self.script)
finally:
sys.settrace(previous_trace)
self.sigDebugging.emit(False)
self._actions['Run'][1].setChecked(False)
if len(cq_objects) == 0:
cq_objects = find_cq_objects(module.__dict__)
self.sigRendered.emit(cq_objects)
self._cleanup_locals(module,injected_names)
self.sigLocals.emit(module.__dict__)
self._frames = []
else:
sys.settrace(previous_trace)
self.inner_event_loop.exit(0)
def debug_cmd(self,state=DbgState.STEP):
0
Source : test_app.py
with Apache License 2.0
from CadQuery
with Apache License 2.0
from CadQuery
def test_debug(main,mocker):
# store the tracing function
trace_function = sys.gettrace()
def assert_func(x):
'''Neddedd to perform asserts in lambdas
'''
assert(x)
qtbot, win = main
#clear all
obj_tree = win.components['object_tree']
obj_tree.toolbarActions()[0].triggered.emit()
editor = win.components['editor']
editor.set_text(code)
debugger = win.components['debugger']
actions = debugger._actions['Run']
run,debug,step,step_in,cont = actions
variables = win.components['variables_viewer']
viewer = win.components['viewer']
assert(number_visible_items(viewer) == 3)
#check breakpoints
assert(debugger.breakpoints == [])
#check _frames
assert(debugger._frames == [])
#test step through
ev = event_loop([lambda: (assert_func(variables.model().rowCount() == 4),
assert_func(number_visible_items(viewer) == 3),
step.triggered.emit()),
lambda: (assert_func(variables.model().rowCount() == 4),
assert_func(number_visible_items(viewer) == 3),
step.triggered.emit()),
lambda: (assert_func(variables.model().rowCount() == 5),
assert_func(number_visible_items(viewer) == 3),
step.triggered.emit()),
lambda: (assert_func(variables.model().rowCount() == 5),
assert_func(number_visible_items(viewer) == 4),
cont.triggered.emit())])
patch_debugger(debugger,ev)
debug.triggered.emit(True)
assert(variables.model().rowCount() == 2)
assert(number_visible_items(viewer) == 4)
#test exit debug
ev = event_loop([lambda: (step.triggered.emit(),),
lambda: (assert_func(variables.model().rowCount() == 1),
assert_func(number_visible_items(viewer) == 3),
debug.triggered.emit(False),)])
patch_debugger(debugger,ev)
debug.triggered.emit(True)
assert(variables.model().rowCount() == 1)
assert(number_visible_items(viewer) == 3)
#test breakpoint
ev = event_loop([lambda: (cont.triggered.emit(),),
lambda: (assert_func(variables.model().rowCount() == 5),
assert_func(number_visible_items(viewer) == 4),
cont.triggered.emit(),)])
patch_debugger(debugger,ev)
editor.debugger.set_breakpoints([(4,None)])
debug.triggered.emit(True)
assert(variables.model().rowCount() == 2)
assert(number_visible_items(viewer) == 4)
#test breakpoint without using singals
ev = event_loop([lambda: (cont.triggered.emit(),),
lambda: (assert_func(variables.model().rowCount() == 5),
assert_func(number_visible_items(viewer) == 4),
cont.triggered.emit(),)])
patch_debugger(debugger,ev)
editor.debugger.set_breakpoints([(4,None)])
debugger.debug(True)
assert(variables.model().rowCount() == 2)
assert(number_visible_items(viewer) == 4)
#test debug() without using singals
ev = event_loop([lambda: (cont.triggered.emit(),),
lambda: (assert_func(variables.model().rowCount() == 5),
assert_func(number_visible_items(viewer) == 4),
cont.triggered.emit(),)])
patch_debugger(debugger,ev)
editor.set_text(code_debug_Workplane)
editor.debugger.set_breakpoints([(4,None)])
debugger.debug(True)
CQ = obj_tree.CQ
# object 1 (defualt color)
r,g,b,a = get_rgba(CQ.child(0).ais)
assert( a == pytest.approx(0.2) )
assert( r == 1.0 )
assert(variables.model().rowCount() == 2)
assert(number_visible_items(viewer) == 4)
# restore the tracing function
sys.settrace(trace_function)
code_err1 = \
0
Source : test_app.py
with Apache License 2.0
from CadQuery
with Apache License 2.0
from CadQuery
def test_traceback(main):
# store the tracing function
trace_function = sys.gettrace()
qtbot, win = main
editor = win.components['editor']
debugger = win.components['debugger']
traceback_view = win.components['traceback_viewer']
actions = debugger._actions['Run']
run,debug,step,step_in,cont = actions
editor.set_text(code_err1)
run.triggered.emit()
assert('SyntaxError' in traceback_view.current_exception.text())
debug.triggered.emit()
assert('SyntaxError' in traceback_view.current_exception.text())
assert(debug.isChecked() == False)
editor.set_text(code_err2)
run.triggered.emit()
assert('NameError' in traceback_view.current_exception.text())
assert(hasattr(sys, 'last_traceback'))
del sys.last_traceback
assert(not hasattr(sys, 'last_traceback'))
#test last_traceback with debug
ev = event_loop([lambda: (cont.triggered.emit(),)])
patch_debugger(debugger,ev)
debugger.debug(True)
assert('NameError' in traceback_view.current_exception.text())
assert(hasattr(sys, 'last_traceback'))
# restore the tracing function
sys.settrace(trace_function)
@pytest.fixture
0
Source : test_pysnooper.py
with MIT License
from cool-RR
with MIT License
from cool-RR
def test_generator():
string_io = io.StringIO()
original_tracer = sys.gettrace()
original_tracer_active = lambda: (sys.gettrace() is original_tracer)
@pysnooper.snoop(string_io, color=False)
def f(x1):
assert not original_tracer_active()
x2 = (yield x1)
assert not original_tracer_active()
x3 = 'foo'
assert not original_tracer_active()
x4 = (yield 2)
assert not original_tracer_active()
return
assert original_tracer_active()
generator = f(0)
assert original_tracer_active()
first_item = next(generator)
assert original_tracer_active()
assert first_item == 0
second_item = generator.send('blabla')
assert original_tracer_active()
assert second_item == 2
with pytest.raises(StopIteration) as exc_info:
generator.send('looloo')
assert original_tracer_active()
output = string_io.getvalue()
assert_output(
output,
(
SourcePathEntry(),
VariableEntry('x1', '0'),
VariableEntry(),
CallEntry(),
LineEntry(),
VariableEntry(),
VariableEntry(),
LineEntry(),
ReturnEntry(),
ReturnValueEntry('0'),
ElapsedTimeEntry(),
# Pause and resume:
VariableEntry('x1', '0'),
VariableEntry(),
VariableEntry(),
VariableEntry(),
CallEntry(),
VariableEntry('x2', "'blabla'"),
LineEntry(),
LineEntry(),
VariableEntry('x3', "'foo'"),
LineEntry(),
LineEntry(),
ReturnEntry(),
ReturnValueEntry('2'),
ElapsedTimeEntry(),
# Pause and resume:
VariableEntry('x1', '0'),
VariableEntry(),
VariableEntry(),
VariableEntry(),
VariableEntry(),
VariableEntry(),
CallEntry(),
VariableEntry('x4', "'looloo'"),
LineEntry(),
LineEntry(),
ReturnEntry(),
ReturnValueEntry(None),
ElapsedTimeEntry(),
)
)
@pytest.mark.parametrize("normalize", (True, False))
0
Source : plugin.py
with BSD 2-Clause "Simplified" License
from dry-python
with BSD 2-Clause "Simplified" License
from dry-python
def assert_trace( # noqa: WPS602
trace_type: _ReturnsResultType,
function_to_search: _FunctionType,
) -> Iterator[None]:
"""
Ensures that a given function was called during execution.
Use it to determine where the failure happened.
"""
old_tracer = sys.gettrace()
sys.settrace(partial(_trace_function, trace_type, function_to_search))
try:
yield
except _DesiredFunctionFound:
pass # noqa: WPS420
else:
pytest.fail(
'No container {0} was created'.format(
trace_type.__class__.__name__,
),
)
finally:
sys.settrace(old_tracer)
def _trace_function(
0
Source : collector.py
with MIT License
from EtienneMD
with MIT License
from EtienneMD
def start(self):
"""Start collecting trace information."""
if self._collectors:
self._collectors[-1].pause()
self.tracers = []
# Check to see whether we had a fullcoverage tracer installed. If so,
# get the stack frames it stashed away for us.
traces0 = []
fn0 = sys.gettrace()
if fn0:
tracer0 = getattr(fn0, '__self__', None)
if tracer0:
traces0 = getattr(tracer0, 'traces', [])
try:
# Install the tracer on this thread.
fn = self._start_tracer()
except:
if self._collectors:
self._collectors[-1].resume()
raise
# If _start_tracer succeeded, then we add ourselves to the global
# stack of collectors.
self._collectors.append(self)
# Replay all the events from fullcoverage into the new trace function.
for args in traces0:
(frame, event, arg), lineno = args
try:
fn(frame, event, arg, lineno=lineno)
except TypeError:
raise Exception("fullcoverage must be run with the C trace function.")
# Install our installation tracer in threading, to jump-start other
# threads.
if self.threading:
self.threading.settrace(self._installation_trace)
def stop(self):
0
Source : pytracer.py
with MIT License
from EtienneMD
with MIT License
from EtienneMD
def _trace(self, frame, event, arg_unused):
"""The trace function passed to sys.settrace."""
#self.log(":", frame.f_code.co_filename, frame.f_lineno, event)
if (self.stopped and sys.gettrace() == self._trace):
# The PyTrace.stop() method has been called, possibly by another
# thread, let's deactivate ourselves now.
#self.log("X", frame.f_code.co_filename, frame.f_lineno)
sys.settrace(None)
return None
if self.last_exc_back:
if frame == self.last_exc_back:
# Someone forgot a return event.
if self.trace_arcs and self.cur_file_dict:
pair = (self.last_line, -self.last_exc_firstlineno)
self.cur_file_dict[pair] = None
self.cur_file_dict, self.cur_file_name, self.last_line = self.data_stack.pop()
self.last_exc_back = None
if event == 'call':
# Entering a new function context. Decide if we should trace
# in this file.
self._activity = True
self.data_stack.append((self.cur_file_dict, self.cur_file_name, self.last_line))
filename = frame.f_code.co_filename
self.cur_file_name = filename
disp = self.should_trace_cache.get(filename)
if disp is None:
disp = self.should_trace(filename, frame)
self.should_trace_cache[filename] = disp
self.cur_file_dict = None
if disp.trace:
tracename = disp.source_filename
if tracename not in self.data:
self.data[tracename] = {}
self.cur_file_dict = self.data[tracename]
# The call event is really a "start frame" event, and happens for
# function calls and re-entering generators. The f_lasti field is
# -1 for calls, and a real offset for generators. Use < 0 as the
# line number for calls, and the real line number for generators.
if getattr(frame, 'f_lasti', -1) < 0:
self.last_line = -frame.f_code.co_firstlineno
else:
self.last_line = frame.f_lineno
elif event == 'line':
# Record an executed line.
if self.cur_file_dict is not None:
lineno = frame.f_lineno
#if frame.f_code.co_filename != self.cur_file_name:
# self.log("*", frame.f_code.co_filename, self.cur_file_name, lineno)
if self.trace_arcs:
self.cur_file_dict[(self.last_line, lineno)] = None
else:
self.cur_file_dict[lineno] = None
self.last_line = lineno
elif event == 'return':
if self.trace_arcs and self.cur_file_dict:
# Record an arc leaving the function, but beware that a
# "return" event might just mean yielding from a generator.
# Jython seems to have an empty co_code, so just assume return.
code = frame.f_code.co_code
if (not code) or code[frame.f_lasti] != YIELD_VALUE:
first = frame.f_code.co_firstlineno
self.cur_file_dict[(self.last_line, -first)] = None
# Leaving this function, pop the filename stack.
self.cur_file_dict, self.cur_file_name, self.last_line = self.data_stack.pop()
elif event == 'exception':
self.last_exc_back = frame.f_back
self.last_exc_firstlineno = frame.f_code.co_firstlineno
return self._trace
def start(self):
0
Source : pytracer.py
with MIT License
from EtienneMD
with MIT License
from EtienneMD
def stop(self):
"""Stop this Tracer."""
# Get the activate tracer callback before setting the stop flag to be
# able to detect if the tracer was changed prior to stopping it.
tf = sys.gettrace()
# Set the stop flag. The actual call to sys.settrace(None) will happen
# in the self._trace callback itself to make sure to call it from the
# right thread.
self.stopped = True
if self.threading and self.thread.ident != self.threading.currentThread().ident:
# Called on a different thread than started us: we can't unhook
# ourselves, but we've set the flag that we should stop, so we
# won't do any more tracing.
#self.log("~", "stopping on different threads")
return
if self.warn:
# PyPy clears the trace function before running atexit functions,
# so don't warn if we are in atexit on PyPy and the trace function
# has changed to None.
dont_warn = (env.PYPY and env.PYPYVERSION >= (5, 4) and self.in_atexit and tf is None)
if (not dont_warn) and tf != self._trace:
self.warn(
"Trace function changed, measurement is likely wrong: %r" % (tf,),
slug="trace-changed",
)
def activity(self):
0
Source : train.py
with MIT License
from eugenevinitsky
with MIT License
from eugenevinitsky
def initialize_ray(args):
"""
Initialize ray and automatically turn on local mode when debugging.
:param args: The parsed arguments.
"""
if sys.gettrace() is not None:
print(
"Debug mode detected through sys.gettrace(), turning on ray local mode. Saving"
" experiment under ray_results/debug_experiment"
)
args.local_mode = True
if args.multi_node and args.local_mode:
sys.exit("You cannot have both local mode and multi node on at the same time")
ray.init(
address=args.address,
local_mode=args.local_mode,
memory=args.memory,
object_store_memory=args.object_store_memory,
redis_max_memory=args.redis_max_memory,
include_webui=False,
)
def get_experiment_name(args):
0
Source : peep.py
with MIT License
from gergelyk
with MIT License
from gergelyk
def stop(try_exit):
def test_exit():
try:
exit_func = exit
return True
except NameError:
# e.g. in ipython exit() is not available
return False
cancel_stop = False
if try_exit:
if sys.gettrace():
print_error('Underlying debugger cannot be terminated.')
# in fact it can be, but in case of pdb/ipdb it results in an ugly exception
print_help("You can use 'Continue' command to close peepshow.")
cancel_stop = True
elif test_exit():
clean_up()
exit(0)
else:
print_error('Underlying Python interpreter cannot be terminated.')
print_help("You can use 'Continue' command to close peepshow.")
cancel_stop = True
else:
clean_up()
return cancel_stop
def peep(target, env):
0
Source : test_replay.py
with GNU General Public License v2.0
from gluap
with GNU General Public License v2.0
from gluap
async def test_init_against_mocked_stick(event_loop, replayfile):
def bla(*args,**kwargs):
pass
proto = DuofernStickAsync(event_loop, system_code="ffff", config_file_json=tempfile.mktemp(), recording=False, changes_callback=bla)
proto.transport = TransportMock(proto, replayfile)
proto._ready = asyncio.Event()
init_ = asyncio.ensure_future(proto.handshake())
proto._ready.set()
await init_
assert ["OK"] * len(
proto.transport.finished_actions) == proto.transport.finished_actions, "some sends did not match" \
"the recording"
await asyncio.wait_for(proto.available, 1)
# if proto.transport.next_is_sent():
# proto.transport.write(bytearray.fromhex(proto.transport.replay[-1][1].strip()))
start_time = time.time()
async def feedback_loop():
while proto.transport.replay:
await asyncio.sleep(0)
if time.time() - start_time > 3 and sys.gettrace() is None:
raise TimeoutError("Mock test should not take longer than 3 seconds, asynchronous loop must be stuck"
"Be aware this is not raised in debug mode.")
if proto.transport.next_is_action():
asyncio.ensure_future(proto.transport.actions())
print("bla")
await feedback_loop()
proto.transport.receiveloop.cancel()
proto.send_loop.cancel()
0
Source : config_dict_test.py
with Apache License 2.0
from google
with Apache License 2.0
from google
def testEquals(self):
"""Tests __eq__ and __ne__ methods."""
some_dict = {
'float': 1.23,
'integer': 3,
'list': [1, 2],
'dict': {
'a': {},
'b': 'string'
}
}
cfg = ml_collections.ConfigDict(some_dict)
cfg_other = ml_collections.ConfigDict(some_dict)
self.assertEqual(cfg, cfg_other)
self.assertEqual(ml_collections.ConfigDict(cfg), cfg_other)
cfg_other.float = 3
self.assertNotEqual(cfg, cfg_other)
cfg_other.float = cfg.float
cfg_other.list = ['a', 'b']
self.assertNotEqual(cfg, cfg_other)
cfg_other.list = cfg.list
cfg_other.lock()
self.assertNotEqual(cfg, cfg_other)
cfg_other.unlock()
cfg_other = ml_collections.ConfigDict(some_dict, type_safe=False)
self.assertNotEqual(cfg, cfg_other)
cfg = ml_collections.ConfigDict(some_dict)
# References that have the same id should be equal (even if self-references)
cfg_other = ml_collections.ConfigDict(some_dict)
cfg_other.me = cfg
cfg.me = cfg
self.assertEqual(cfg, cfg_other)
cfg = ml_collections.ConfigDict(some_dict)
cfg.me = cfg
self.assertEqual(cfg, cfg)
# Self-references that do not have the same id loop infinitely
cfg_other = ml_collections.ConfigDict(some_dict)
cfg_other.me = cfg_other
# Temporarily disable coverage trace while testing runtime is exceeded
trace_func = sys.gettrace()
sys.settrace(None)
with self.assertRaises(RuntimeError):
cfg == cfg_other # pylint:disable=pointless-statement
sys.settrace(trace_func)
def testEqAsConfigDict(self):
0
Source : test__threading_vs_settrace.py
with GNU General Public License v3.0
from gtkfi
with GNU General Public License v3.0
from gtkfi
def test_untraceable_lock(self):
# Untraceable locks were part of the solution to https://bugs.python.org/issue1733757
# which details a deadlock that could happen if a trace function invoked
# threading.currentThread at shutdown time---the cleanup lock would be held
# by the VM, and calling currentThread would try to acquire it again. The interpreter
# changed in 2.6 to use the `with` statement (https://hg.python.org/cpython/rev/76f577a9ec03/),
# which apparently doesn't trace in quite the same way.
if hasattr(sys, 'gettrace'):
old = sys.gettrace()
else:
old = None
lst = []
try:
def trace(frame, ev, _arg):
lst.append((frame.f_code.co_filename, frame.f_lineno, ev))
print("TRACE: %s:%s %s" % lst[-1])
return trace
with allocate_lock():
sys.settrace(trace)
finally:
sys.settrace(old)
self.assertEqual(lst, [], "trace not empty")
@greentest.skipOnPurePython("Locks can be traced in Pure Python")
0
Source : test__threading_vs_settrace.py
with GNU General Public License v3.0
from gtkfi
with GNU General Public License v3.0
from gtkfi
def test_untraceable_lock_uses_different_lock(self):
if hasattr(sys, 'gettrace'):
old = sys.gettrace()
else:
old = None
PY3 = sys.version_info[0] > 2
lst = []
# we should be able to use unrelated locks from within the trace function
l = allocate_lock()
try:
def trace(frame, ev, _arg):
with l:
lst.append((frame.f_code.co_filename, frame.f_lineno, ev))
print("TRACE: %s:%s %s" % lst[-1])
return trace
l2 = allocate_lock()
sys.settrace(trace)
# Separate functions, not the C-implemented `with` so the trace
# function gets a crack at them
l2.acquire()
l2.release()
finally:
sys.settrace(old)
if not PY3:
# Py3 overrides acquire in Python to do argument checking
self.assertEqual(lst, [], "trace not empty")
else:
# Have an assert so that we know if we miscompile
self.assertTrue(lst, "should not compile on pypy")
@greentest.skipOnPurePython("Locks can be traced in Pure Python")
0
Source : test__threading_vs_settrace.py
with GNU General Public License v3.0
from gtkfi
with GNU General Public License v3.0
from gtkfi
def test_untraceable_lock_uses_same_lock(self):
from gevent.hub import LoopExit
if hasattr(sys, 'gettrace'):
old = sys.gettrace()
else:
old = None
PY3 = sys.version_info[0] > 2
lst = []
e = None
# we should not be able to use the same lock from within the trace function
# because it's over acquired but instead of deadlocking it raises an exception
l = allocate_lock()
try:
def trace(frame, ev, _arg):
with l:
lst.append((frame.f_code.co_filename, frame.f_lineno, ev))
return trace
sys.settrace(trace)
# Separate functions, not the C-implemented `with` so the trace
# function gets a crack at them
l.acquire()
except LoopExit as ex:
e = ex
finally:
sys.settrace(old)
if not PY3:
# Py3 overrides acquire in Python to do argument checking
self.assertEqual(lst, [], "trace not empty")
else:
# Have an assert so that we know if we miscompile
self.assertTrue(lst, "should not compile on pypy")
self.assertTrue(isinstance(e, LoopExit))
def run_script(self, more_args=()):
0
Source : build.py
with GNU Affero General Public License v3.0
from gwendal-lv
with GNU Affero General Public License v3.0
from gwendal-lv
def get_split_dataloaders(train_config, full_dataset, persistent_workers=True):
""" Returns a dict of train/validation/test DataLoader instances, and a dict which contains the
length of each sub-dataset. """
# Num workers might be zero (no multiprocessing)
_debugger = False
if train_config.profiler_args['enabled'] and train_config.profiler_args['use_cuda']:
num_workers = 0 # CUDA PyTorch profiler does not work with a multiprocess-dataloader
elif sys.gettrace() is not None:
_debugger = True
print("[data/build.py] Debugger detected - num_workers=0 for all DataLoaders")
num_workers = 0 # PyCharm debug behaves badly with multiprocessing...
else: # We should use an higher CPU count for real-time audio rendering
# 4*GPU count: optimal w/ light dataloader (e.g. (mel-)spectrogram computation)
num_workers = min(train_config.minibatch_size, torch.cuda.device_count() * 4)
# Dataloader easily build from samplers
subset_samplers = data.sampler.build_subset_samplers(full_dataset, k_fold=train_config.current_k_fold,
k_folds_count=train_config.k_folds,
test_holdout_proportion=train_config.test_holdout_proportion)
dataloaders = dict()
sub_datasets_lengths = dict()
for k, sampler in subset_samplers.items():
# Last train minibatch must be dropped to help prevent training instability. Worst case example, last minibatch
# contains only 8 elements, mostly sfx: these hard to learn (or generate) item would have a much higher
# equivalent learning rate because all losses are minibatch-size normalized. No issue for eval though
drop_last = (k.lower() == 'train')
# Dataloaders based on previously built samplers
dataloaders[k] = torch.utils.data.DataLoader(full_dataset, batch_size=train_config.minibatch_size,
sampler=sampler, num_workers=num_workers, pin_memory=False,
persistent_workers=((num_workers > 0) and persistent_workers),
drop_last=drop_last)
sub_datasets_lengths[k] = len(sampler.indices)
if train_config.verbosity >= 1:
print("[data/build.py] Dataset '{}' contains {}/{} samples ({:.1f}%). num_workers={}"
.format(k, sub_datasets_lengths[k], len(full_dataset),
100.0 * sub_datasets_lengths[k]/len(full_dataset), num_workers))
return dataloaders, sub_datasets_lengths
0
Source : _stack.py
with MIT License
from hhoeflin
with MIT License
from hhoeflin
def start(self, omit_levels=0):
"""Activate the tracking."""
if self.ctx_active:
raise TrackerActiveError("Context manager is already active")
frame = self._get_callee_frame(omit_levels=omit_levels + 1)
# save the tree for storing the information
self.tree = FrameInfo.from_frame(frame)
# include the current file in the directories to accept
self.active_dirs = copy(self.dirs)
self.active_dirs.append(str(Path(self.tree.filename).parent) + "/")
self.active_dirs = list(set(self.active_dirs))
# here we actually want the next command
self.cur_node = self.tree
stmt_tree = parser.get_stmt_ranges(Path(frame.f_code.co_filename))
stmt_after = parser.closest_after(stmt_tree, frame.f_lineno)
if stmt_after is None:
self.entry_lineno = frame.f_lineno
else:
self.entry_lineno = stmt_after.begin
self.ctx_active = True
# we get the directory of the callee
if sys.gettrace() is None:
sys.settrace(self.trace)
# sys.settrace(None)
else:
logger.warning(f"Logger already set to {sys.gettrace()}")
return self
def stop(self, omit_levels=0):
0
Source : debugger.py
with BSD 3-Clause "New" or "Revised" License
from holzschu
with BSD 3-Clause "New" or "Revised" License
from holzschu
def do_debug(self, arg):
"""debug code
Enter a recursive debugger that steps through the code
argument (which is an arbitrary expression or statement to be
executed in the current environment).
"""
trace_function = sys.gettrace()
sys.settrace(None)
globals = self.curframe.f_globals
locals = self.curframe_locals
p = self.__class__(completekey=self.completekey,
stdin=self.stdin, stdout=self.stdout)
p.use_rawinput = self.use_rawinput
p.prompt = "(%s) " % self.prompt.strip()
self.message("ENTERING RECURSIVE DEBUGGER")
sys.call_tracing(p.run, (arg, globals, locals))
self.message("LEAVING RECURSIVE DEBUGGER")
sys.settrace(trace_function)
self.lastcmd = p.lastcmd
def do_pdef(self, arg):
See More Examples