def handle(self, *args, **options): global good_regex global bad_regex args = list(args) command = args.pop(0) global_options['include_builtins'] = options['include_builtins'] global_options['include_stdlib'] = options['include_stdlib'] global_options['module_only'] = options['module_only'] global_options['calls_only'] = options['calls_only'] global_options['good'] = options['good'] global_options['bad'] = options['bad'] global_options['good_regex'] = options['good_regex'] global_options['bad_regex'] = options['bad_regex'] global_options['good_preset'] = options['good_preset'] global_options['bad_preset'] = options['bad_preset'] good_regex = re.compile(global_options['good_regex']) bad_regex = re.compile(global_options['bad_regex']) sys.settrace(traceit) options = dict( use_reloader=False, ) management.call_command(command, *args, **options)
def setBreakpoint(self, breakpoint): import sys debugInstance = self._getDebugger() debugInstance.do_break(debugInstance.precmd(breakpoint)) debugInstance.quitting = True sys.settrace(debugInstance.trace_dispatch) debugInstance.quitting = False
def execute (self, cmd): """ Execute a given command """ sys.stdout, self.stdout = self.stdout, sys.stdout sys.stderr, self.stderr = self.stderr, sys.stderr sys.stdin, self.stdin = self.stdin, sys.stdin sys.settrace (self.idle) try: try: r = eval (cmd, self.namespace, self.namespace) if r is not None: print(r) except SyntaxError: exec cmd in self.namespace except: if hasattr (sys, 'last_type') and sys.last_type == SystemExit: self.quit_handler() else: try: info = sys.exc_info() tb = info[2] if tb: tb = tb.tb_next traceback.print_exception (info[0], info[1], tb) except: sys.stderr, self.stderr = self.stderr, sys.stderr traceback.print_exc() sys.settrace (None) sys.stdout, self.stdout = self.stdout, sys.stdout sys.stderr, self.stderr = self.stderr, sys.stderr sys.stdin, self.stdin = self.stdin, sys.stdin
def __init__(self, *args, **kwargs): global tracer global q self._response_headers = [] # print DEBUG_ENABLED # self.http_version = "1.1" DBG("START") # STDERR("START: debug_enable=%s"%DEBUG_ENABLED) if DEBUG_ENABLED: # STDERR("bps: %s" % tracer.get_all_breaks()) if tracer.get_all_breaks(): q.put("set_continue") tracer.set_trace() tracer.process_pending_commands() # STDERR("bps: %s" % tracer.get_all_breaks()) # STDERR("%d" % q.unfinished_tasks) else: # Debug is not enable and there are no breakpoints # continue without debugger overhead # STDERR(repr(tracer.get_all_breaks())) sys.settrace(None) WSGIRequestHandler.__init__(self, *args, **kwargs) # STDOUT("aqui") # print self.requestline # print self.headers try: WSOUT("REQUEST_HEADERS", "%s\n%s\n%s" % ("-" * 20, self.requestline, self.headers)) except AttributeError: pass DBG("STOP")
def trace_process (**kwargs): """Literally log every line of python code as it runs. Keyword arguments: log -- file (name) to log to (default stderr) scope -- base scope to log to (default Cobalt)""" file_name = kwargs.get("log", None) if file_name is not None: log_file = open(file_name, "w") else: log_file = sys.stderr scope = kwargs.get("scope", "Cobalt") def traceit (frame, event, arg): if event == "line": lineno = frame.f_lineno filename = frame.f_globals["__file__"] if (filename.endswith(".pyc") or filename.endswith(".pyo")): filename = filename[:-1] name = frame.f_globals["__name__"] line = linecache.getline(filename, lineno) print >> log_file, "%s:%s: %s" % (name, lineno, line.rstrip()) return traceit sys.settrace(traceit)
def run_test(self, func): tracer = JumpTracer(func) sys.settrace(tracer.trace) output = [] func(output) sys.settrace(None) self.compare_jump_output(func.output, output)
def run(self): # Note: this is important: we have to set the tracing function # when the thread is started (we could set threading.settrace # before starting this thread to do this externally) try: global call_finished sys.settrace(do_nothing_trace_function) exec self._Thread__kwargs['call_string'] in self._Thread__kwargs['kw'] print "exec call finished!" call_finished = True except TypeError as t: call_finished = True self._Thread__kwargs['Exception'] = t except AttributeError as a: call_finished = True self._Thread__kwargs['Exception'] = a except SyntaxError as s1: call_finished = True self._Thread__kwargs['Exception'] = s1 except SigFinish as sf1: call_finished = True self._Thread__kwargs['Exception'] = sf1 except Exception as e1: call_finished = True self._Thread__kwargs['Exception'] = e1
def opt_spew(self): """ Print an insanely verbose log of everything that happens. Useful when debugging freezes or locks in complex code. """ from twisted.python.util import spewer sys.settrace(spewer)
def run_and_compare(self, func, events): tracer = Tracer() sys.settrace(tracer.trace) func() sys.settrace(None) self.compare_events(func.func_code.co_firstlineno, tracer.events, events)
def start(self, parallel_mode=False): self.get_ready() if self.nesting == 0: #pragma: no cover sys.settrace(self.t) if hasattr(threading, 'settrace'): threading.settrace(self.t) self.nesting += 1
def wrap(*args, **kwargs): frames = [] def tracer(frame, event, arg): frames.append(frame) sys.settrace(old_tracer) if old_tracer is not None: return old_tracer(frame, event, arg) old_tracer = sys.gettrace() # tracer is activated on next call, return or exception sys.settrace(tracer) try: func(*args, **kwargs) finally: sys.settrace(old_tracer) assert len(frames) == 1 argspec = inspect.getargspec(func) argnames = list(argspec.args) if argspec.varargs is not None: argnames.append(argspec.varargs) if argspec.keywords is not None: argnames.append(argspec.keywords) return {name: value for name, value in frames.pop(0).f_locals.items() if name not in argnames}
def trace_stop(): global _tracing, _indent assert _tracing > 0 _tracing -= 1 if not _tracing: sys.settrace(None) _indent = ''
def run(): if len(sys.argv) == 1: sys.argv.append("--help") config = Options() try: config.parseOptions() except usage.error as ue: raise SystemExit("%s: %s" % (sys.argv[0], ue)) _initialDebugSetup(config) try: trialRunner = _makeRunner(config) except _DebuggerNotFound as e: raise SystemExit('%s: %s' % (sys.argv[0], str(e))) suite = _getSuite(config) if config['until-failure']: test_result = trialRunner.runUntilFailure(suite) else: test_result = trialRunner.run(suite) if config.tracer: sys.settrace(None) results = config.tracer.results() results.write_results(show_missing=1, summary=False, coverdir=config.coverdir().path) sys.exit(not test_result.wasSuccessful())
def detach(): """ Finish execution tracing, print the results and reset internal state """ global _gls global current_gl global _states global _curr_states global _attach_expiration global _trace_began_at # do we have a current trace? if not _trace_began_at: return duration = time.time() - _trace_began_at _attach_expiration = None sys.settrace(None) _maybe_flush(_trace_output_file) _print_output(duration) _gls = {} _curr_gl = None _states = {} _curr_states = {} _trace_began_at = None curr_state = None
def main(): usage = "mactrace.py [-o output_file_path] scriptfile [arg] ..." parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option('-o', '--outfile', dest="outfile", help="Save trace to <outfile>", default=None) if not sys.argv[1:]: parser.print_usage() sys.exit(2) (options, args) = parser.parse_args() sys.argv[:] = args if options.outfile: twriter = TraceWriter(open(options.outfile, "w")) else: twriter = TraceWriter() sys.settrace(twriter.trace) if len(args) > 0: progname = args[0] sys.path.insert(0, os.path.dirname(progname)) with open(progname, 'rb') as fp: code = compile(fp.read(), progname, 'exec') globs = { '__file__': progname, '__name__': '__main__', '__package__': None, } eval(code, globs) else: parser.print_usage() return parser
def __bootstrap(self): try: self._set_ident() self._Thread__started.set() threading._active_limbo_lock.acquire() threading._active[self._Thread__ident] = self del threading._limbo[self] threading._active_limbo_lock.release() if threading._trace_hook: sys.settrace(threading._trace_hook) if threading._profile_hook: sys.setprofile(threading._profile_hook) try: self.run() finally: self._Thread__exc_clear() finally: with threading._active_limbo_lock: self._Thread__stop() try: del threading._active[threading._get_ident()] except: pass
def test_trace_try_finally(self): import sys l = [] def trace(frame, event, arg): if event == 'exception': l.append(arg) return trace def g(): try: raise Exception finally: pass def f(): try: g() except: pass sys.settrace(trace) f() sys.settrace(None) assert len(l) == 2 assert issubclass(l[0][0], Exception) assert issubclass(l[1][0], Exception)
def __init__(self, func=None, unpack=None, **kwargs): self.__defs__ = [] self.__sizes__ = [] self.__attrs__ = [] self.__values__ = {} self.__next__ = True self.__baked__ = False if func == None: self.__format__() else: sys.settrace(self.__trace__) func() for name in func.func_code.co_varnames: value = self.__frame__.f_locals[name] self.__setattr__(name, value) self.__baked__ = True if unpack != None: if isinstance(unpack, tuple): self.unpack(*unpack) else: self.unpack(unpack) if len(kwargs): for name in kwargs: self.__values__[name] = kwargs[name]
def test_trace_hidden_prints(self): import sys l = [] def trace(a,b,c): l.append((a,b,c)) return trace outputf = open(self.tempfile1, 'w') def f(): print >> outputf, 1 print >> outputf, 2 print >> outputf, 3 return "that's the return value" sys.settrace(trace) f() sys.settrace(None) outputf.close() # should get 1 "call", 3 "line" and 1 "return" events, and no call # or return for the internal app-level implementation of 'print' assert len(l) == 6 assert [what for (frame, what, arg) in l] == [ 'call', 'line', 'line', 'line', 'line', 'return'] assert l[-1][2] == "that's the return value"
def test_trace_return_exc(self): import sys l = [] def trace(a,b,c): if b in ('exception', 'return'): l.append((b, c)) return trace def g(): raise Exception def f(): try: g() except: pass sys.settrace(trace) f() sys.settrace(None) assert len(l) == 4 assert l[0][0] == 'exception' assert isinstance(l[0][1][1], Exception) assert l[1] == ('return', None) assert l[2][0] == 'exception' assert isinstance(l[2][1][1], Exception) assert l[3] == ('return', None)
def start(self): self.get_ready() if self.nesting == 0: # pragma: no cover sys.settrace(self.t) if hasattr(threading, "settrace"): threading.settrace(self.t) self.nesting += 1
def trace_lines(do_trace): """Turn on/off printing each executed line. Args: do_trace: Whether to start tracing (True) or stop it (False). """ def trace(frame, event, arg): """Trace function passed to sys.settrace. Return: Itself, so tracing continues. """ if sys is not None: loc = '{}:{}'.format(frame.f_code.co_filename, frame.f_lineno) if arg is not None: arg = utils.compact_text(str(arg), 200) else: arg = '' print("{:11} {:80} {}".format(event, loc, arg), file=sys.stderr) return trace else: # When tracing while shutting down, it seems sys can be None # sometimes... if that's the case, we stop tracing. return None if do_trace: sys.settrace(trace) else: sys.settrace(None)
def TraceFunc(self, frame, event, arg): if event == 'call' and frame.f_code.co_name in ('schedule_cb', ): sys.settrace(self.NullTraceFunc) return self.ResumeTracingTraceFunc tasklet = stackless.current # print " TraceFunc: %s %s in %s, line %s" % \ # (id(tasklet), event, frame.f_code.co_name, frame.f_lineno) ok = True if event in ('call', 'line', 'return'): key = (id(tasklet), frame.f_lineno) try: count = self.seen[key] except KeyError: ok = False else: self.seen[key] = count + 1 else: ok = False if not ok: self.unexpected_trace_events.append((tasklet, event, frame.f_code.co_name, frame.f_lineno)) if event in ('call', 'line', 'exception'): return self.TraceFunc return None
def __exit__(self, type_=None, value=None, traceback=None): reset_Breakpoint() sys.settrace(self._original_tracer) not_empty = '' if self.tracer.set_list: not_empty += 'All paired tuples have not been processed, ' not_empty += ('the last one was number %d' % self.tracer.expect_set_no) # Make a BdbNotExpectedError a unittest failure. if type_ is not None and issubclass(BdbNotExpectedError, type_): if isinstance(value, BaseException) and value.args: err_msg = value.args[0] if not_empty: err_msg += '\n' + not_empty if self.dry_run: print(err_msg) return True else: self.test_case.fail(err_msg) else: assert False, 'BdbNotExpectedError with empty args' if not_empty: if self.dry_run: print(not_empty) else: self.test_case.fail(not_empty)
def test_trace_raise_three_arg(self): import sys l = [] def trace(frame, event, arg): if event == 'exception': l.append(arg) return trace def g(): try: raise Exception except Exception as e: import sys raise Exception, e, sys.exc_info()[2] def f(): try: g() except: pass sys.settrace(trace) f() sys.settrace(None) assert len(l) == 2 assert issubclass(l[0][0], Exception) assert issubclass(l[1][0], Exception)
def run(self): if _settrace_func: _sys.settrace(_settrace_func) if _setprofile_func: _sys.setprofile(_setprofile_func) self.__target(*self.__args, **self.__kwargs)
def test_set_unset_f_trace(self): import sys seen = [] def trace1(frame, what, arg): seen.append((1, frame, frame.f_lineno, what, arg)) return trace1 def trace2(frame, what, arg): seen.append((2, frame, frame.f_lineno, what, arg)) return trace2 def set_the_trace(f): f.f_trace = trace1 sys.settrace(trace2) len(seen) # take one line: should not be traced f = sys._getframe() set_the_trace(f) len(seen) # take one line: should not be traced len(seen) # take one line: should not be traced sys.settrace(None) # and this line should be the last line traced len(seen) # take one line del f.f_trace len(seen) # take one line firstline = set_the_trace.func_code.co_firstlineno assert seen == [(1, f, firstline + 6, 'line', None), (1, f, firstline + 7, 'line', None), (1, f, firstline + 8, 'line', None)]
def probe_func( frame, event, arg ): if event=='return': l = frame.f_locals for key in keys: dictionary[key] = l.get( key ) sys.settrace( None ) return probe_func
def unsettrace(self, irc, msg, args): """takes no arguments Stops tracing function calls on stdout. """ sys.settrace(None) irc.replySuccess()
def trace_dispatch(self, frame, event, arg): """ Public method wrapping the trace_dispatch of bdb.py. It wraps the call to dispatch tracing into bdb to make sure we have locked the client to prevent multiple threads from entering the client event loop. @param frame The current stack frame. @param event The trace event (string) @param arg The arguments @return local trace function """ try: self._dbgClient.lockClient() # if this thread came out of a lock, and we are quitting # and we are still running, then get rid of tracing for this thread if self.quitting and self._threadRunning: sys.settrace(None) sys.setprofile(None) import threading self.__name = threading.currentThread().getName() retval = DebugBase.trace_dispatch(self, frame, event, arg) finally: self._dbgClient.unlockClient() return retval
oldprint = print def newprint(text): global _summary_text_ oldprint(text) if _summary_text_ != "": _summary_text_ += "\n" _summary_text_ += text print = newprint import sys sys.settrace(None) outstructs = [] outstrings = [] class Logger(object): def __init__(self): self.terminal = sys.stdout self.log = open("Summary.txt", "w") def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self):
def __exit__(self, exc_type, exc_val, exc_tbf): """Disables events tracker.""" sys.settrace(self._original_trace_function)
def set_quit(self): sys.settrace(None)
def __run(self): """Hacked run function, which installs the trace.""" sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup
def __run(self): sys.settrace(self.globaltrace) self.__run_backup() self.run = self.__run_backup
def teardown(self): sys.setprofile(None) sys.settrace(None)
def __enter__(self): """Enables events tracker.""" sys.settrace(self._trace_memory_usage) return self
def run(args): global verbosity preffile = os.path.join(os.environ['HOME'], '.openipmigui.startup') histfile = os.path.join(os.environ['HOME'], '.openipmigui.history') debug_msg = False debug_rawmsg = False debug_mem = False do_trace = False read_preffile = True log_file = None # Skip program name. carg = 1 while (carg < len(args)): arg = args[carg] carg += 1 if (arg == "--dmsg"): debug_msg = True elif (arg == "--drawmsg"): debug_msg = True elif (arg == "--dmem"): debug_mem = True elif (arg == "--verbose"): verbosity += 1 elif (arg == "--trace"): do_trace = True elif (arg == "--logstderr"): log_file = sys.stderr elif (arg == "--logstdout"): log_file = sys.stdout elif (arg == "-n"): read_preffile = False elif (arg == '-p'): if (len(args) == 0): print "No argument given for -p" return preffile = args[carg] carg += 1 else: print "Unknown argument: " + arg return pass if (debug_mem): OpenIPMI.enable_debug_malloc() pass top = TopHandler(preffile, log_file, histfile) # Detect if we need a separate OpenIPMI driver thread. See the # openipmi_driver function above for the reason. try: import thread try: top.tk.getvar("tcl_platform", "threaded") # Tcl is threaded, no need for another thread. need_separate_openipmi_thread = False except: # Python is threaded, but Tcl is not. Need to run the # OpenIPMI event loop in another thread. need_separate_openipmi_thread = True pass pass except: # No thread support, can't use another thread. need_separate_openipmi_thread = False pass if (need_separate_openipmi_thread): if (verbosity >= 1): print "Creating separate OpenIPMI event driver thread" pass rv = OpenIPMI.init() if (rv != 0): print "Unable to initialize OpenIPMI" return thread.start_new_thread(openipmi_driver, ()) pass else: if (verbosity >= 1): print "Using TCL event loop, no threads" pass rv = OpenIPMI.init_tcl() if (rv != 0): print "Unable to initialize OpenIPMI, probably no TCL support" return pass if (debug_rawmsg): OpenIPMI.enable_debug_rawmsg() pass if (debug_msg): OpenIPMI.enable_debug_msg() pass if (do_trace): sys.settrace(trace) pass if (read_preffile): _saveprefs.restore(preffile) gui_cmdwin._HistoryRestore(histfile) mainhandler = top OpenIPMI.add_domain_change_handler(_domain.DomainWatcher(mainhandler)) mainhandler.debug_mem = debug_mem top.title('OpenIPMI GUI') ui = gui.IPMIGUI(top, mainhandler) mainhandler.SetUI(ui) OpenIPMI.add_domain_change_handler(mainhandler) OpenIPMI.set_log_handler(mainhandler) _domain.RestoreDomains(mainhandler) OpenIPMI.set_cmdlang_event_handler(CmdlangEventHandler(mainhandler)) top.mainloop() mainhandler.quit()
co = frame.f_code func_name = co.co_name line_no = frame.f_lineno filename = co.co_filename print ' %s line %s -- %d' % (func_name, line_no, int(round(time.time() * 1000)) - lastTime) global lastTime lastTime = int(round(time.time() * 1000)) def trace_calls(frame, event, arg): if event != 'call': return co = frame.f_code func_name = co.co_name line_no = frame.f_lineno filename = co.co_filename print 'Call to %s on line %s of %s' % (func_name, line_no, filename) return trace_lines #return def g(): print "here" time.sleep(4) time.sleep(3) sys.settrace(trace_calls) g()
def test_debug(main, mocker): # store the tracing function trace_function = sys.gettrace() class event_loop(object): '''Used to mock the QEventLoop for the debugger component ''' def __init__(self, callbacks): self.callbacks = callbacks self.i = 0 def exec_(self): if self.i < len(self.callbacks): self.callbacks[self.i]() self.i += 1 def exit(self, *args): pass def assert_func(x): '''Neddedd to perform asserts in lambdas ''' assert (x) def patch_debugger(debugger, event_loop_mock): debugger.inner_event_loop.exec_ = event_loop_mock.exec_ debugger.inner_event_loop.exit = event_loop_mock.exit 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)
def probeFunc(frame, event, arg): if event == 'return': locals = frame.f_locals func_locals.update(dict((k,locals.get(k)) for k in keys)) sys.settrace(None) return probeFunc