def after_step(context, step): if BEHAVE_DEBUG_ON_ERROR and step.status == "failed": context.browser.screenshot_error() # -- ENTER DEBUGGER: Zoom in on failure location. # NOTE: Use IPython debugger, same for pdb (basic python debugger). import ipdb ipdb.post_mortem(step.exc_traceback)
def process_exception(exception): qlog.critical('EXCEPTION while processing HTTP request: "{}"\n{}'.format( type(exception).__name__, str(traceback.format_exc()) )) if not global_arguments['-g']: return render_template('exception.html') # Try to launch a postmortem debugger. # The order of preference is: pudb, ipdb, pdb # pudb will not work on Windows machines, so it can be suppressed with the -p option. # ipdb may not be installed on all machines, so it falls back to pdb if not installed e_traceback = sys.exc_info()[2] debugger_launched = False if global_arguments['-p']: try: # Use pudb debugger if available import pudb pudb.post_mortem(e_traceback) debugger_launched = True except: print('Could not launch pudb. Falling back to ipdb/pdb.') pass if not debugger_launched: try: # Use iPython debugger if available import ipdb ipdb.post_mortem(e_traceback) except: # Fall back to pdb import pdb pdb.post_mortem(e_traceback)
def __exit__(self, type_, value, traceback_): host = socket.gethostname() caffeine.__exit__(type_, value, traceback_) if isinstance(value, Exception): error = type_.__name__ temp = '{host} encountered {error}: {value} in {task}' event = temp.format(host=host, error=error, value=value, task=self.name) info = [] # traceback tb_items = traceback.format_tb(traceback_) error_message = "%s: %s\n" % (error, value) tb_items.append(error_message) tb_str = '\n'.join(tb_items) info.append(tb_str) # object info if self.crash_info_func: info.extend(self.crash_info_func()) self.send(event, info) # drop into pdb if self.debug: traceback.print_exc() print('') try: import ipdb as pdb except ImportError: import pdb pdb.post_mortem(traceback_) else: event = '{host} finished {task}'.format(host=host, task=self.name) self.send(event)
def main(argv=sys.argv, out=sys.stdout): setup_log_ = functools.partial(setup_log, str_formatter='%(asctime)s [%(levelname)s] %(message)s') try: return pbparser_runner( argv=argv[1:], parser=get_parser(), args_runner_func=args_runner, contract_runner_func=resolved_tool_contract_runner, alog=logging.getLogger(__name__), setup_log_func=setup_log_) # FIXME is there a more central place to deal with this? except Exception as e: type, value, tb = sys.exc_info() traceback.print_exc(file=sys.stderr) # Note: if kt.args.usePdb # This won't work. If an exception is raised in parseArgs, # then kt.args is not defined yet. if '--pdb' in argv: try: # this has better integration with ipython and is nicer # pip install ipdb import ipdb ipdb.post_mortem(tb) except ImportError: import pdb pdb.post_mortem(tb) else: # exit non-zero raise
def handle_packet_in(self, concrete_pkt): pyretic_pkt = self.concrete2pyretic(concrete_pkt) if self.debug_packet_in: debugger.set_trace() if USE_IPDB: with debugger.launch_ipdb_on_exception(): if self.mode == 'interpreted': output = self.policy.eval(pyretic_pkt) else: (output,traversed) = self.policy.track_eval(pyretic_pkt) self.reactive0(pyretic_pkt,output,traversed) else: try: if self.mode == 'interpreted': output = self.policy.eval(pyretic_pkt) else: (output,traversed) = self.policy.track_eval(pyretic_pkt) self.reactive0(pyretic_pkt,output,traversed) except : type, value, tb = sys.exc_info() traceback.print_exc() debugger.post_mortem(tb) if self.show_traces: print "<<<<<<<<< RECV <<<<<<<<<<<<<<<<<<<<<<<<<<" print util.repr_plus([pyretic_pkt], sep="\n\n") print print ">>>>>>>>> SEND >>>>>>>>>>>>>>>>>>>>>>>>>>" print util.repr_plus(output, sep="\n\n") print map(self.send_packet,output)
def _main(): """Entry point""" initLogging() try: args, _, config = parseCommandLine() eyed3.utils.console.AnsiCodes.init(not args.no_color) mainFunc = main if args.debug_profile is False else profileMain retval = mainFunc(args, config) except KeyboardInterrupt: retval = 0 except (StopIteration, IOError) as ex: eyed3.utils.console.printError(str(ex)) retval = 1 except Exception as ex: eyed3.utils.console.printError("Uncaught exception: %s\n" % str(ex)) eyed3.log.exception(ex) retval = 1 if args.debug_pdb: try: with warnings.catch_warnings(): warnings.simplefilter("ignore", PendingDeprecationWarning) # Must delay the import of ipdb as say as possible because # of https://github.com/gotcha/ipdb/issues/48 import ipdb as pdb except ImportError: import pdb e, m, tb = sys.exc_info() pdb.post_mortem(tb) sys.exit(retval)
def __exit__(self, type_, value, traceback_): host = socket.gethostname() user_activity.__exit__(type_, value, traceback_) if isinstance(value, Exception): error = type_.__name__ temp = '{host} encountered {error}: {value} in {task}' event = temp.format(host=host, error=error, value=value, task=self.name) info = [] # traceback tb_items = traceback.format_tb(traceback_) error_message = "%s: %s\n" % (error, value) tb_items.append(error_message) tb_str = '\n'.join(tb_items) info.append(tb_str) # object info if self.crash_info_func: info.extend(self.crash_info_func()) self.send(event, info) # drop into pdb if self.debug: traceback.print_exc() print('') try: import ipdb as pdb except ImportError: import pdb pdb.post_mortem(traceback_) else: event = '{host} finished {task}'.format(host=host, task=self.name) self.send(event)
def _handle_map_err(self, mapper, args): msg = "map %r failed for %r"%(mapper,args) logging.exception(msg) print(msg) traceback.print_exc() import ipdb ipdb.post_mortem(sys.exc_info()[2])
def validate_bboxes(self): import traceback import sys from tqdm import tqdm try: # For each image in the data set... for idx in tqdm(range(len(self.image_ids))): img_file = os.path.join(self.root, self.impaths[idx]) width, height = PIL.Image.open(img_file).size # For each bounding box on this image... for iBox, bbox in enumerate(self.bboxes[idx]): # Clip everything to be >= 0 bbox = [0 if i < 0 else i for i in bbox] # Clip coordinates to be inside the image bbox[1] = min(bbox[1], width) bbox[3] = min(bbox[3], width) bbox[0] = min(bbox[0], height) bbox[2] = min(bbox[2], height) # Make sure bounding boxes are non-zero area assert bbox[3] > bbox[1] assert bbox[2] > bbox[0] self.bboxes[idx][iBox] = bbox except: extype, value, tb = sys.exc_info() traceback.print_exc() import ipdb ipdb.post_mortem(tb)
def _main(): """Entry point""" initLogging() try: args, _, config = parseCommandLine() eyed3.utils.console.AnsiCodes.init(not args.no_color) mainFunc = main if args.debug_profile is False else profileMain retval = mainFunc(args, config) except KeyboardInterrupt: retval = 0 except (StopIteration, IOError) as ex: eyed3.utils.console.printError(UnicodeType(ex)) retval = 1 except Exception as ex: eyed3.utils.console.printError("Uncaught exception: %s\n" % str(ex)) eyed3.log.exception(ex) retval = 1 if args.debug_pdb: try: with warnings.catch_warnings(): warnings.simplefilter("ignore", PendingDeprecationWarning) # Must delay the import of ipdb as say as possible because # of https://github.com/gotcha/ipdb/issues/48 import ipdb as pdb except ImportError: import pdb e, m, tb = sys.exc_info() pdb.post_mortem(tb) sys.exit(retval)
async def transaction(self, name): old_transaction_name = self._transaction_name old_transaction_id = self._transaction_id self._transaction_id = next(self._trans_id_gen) self._transaction_name = name start_time = time.time() error = False try: yield None except Exception as e: error = True if isinstance(e, MiteError): self._send_mite_error(e) else: self._send_exception(e) if self._debug: # pragma: no cover import ipdb ipdb.post_mortem() sys.exit(1) finally: self.send('txn', start_time=start_time, end_time=time.time(), had_error=error) self._transaction_name = old_transaction_name self._transaction_id = old_transaction_id
def post_mortem(exc_info): err = exc_info[1] if isinstance(err, (doctest.UnexpectedException, doctest.DocTestFailure)): if isinstance(err, doctest.UnexpectedException): exc_info = err.exc_info # Print out location info if the error was in a doctest if exc_info[2].tb_frame.f_code.co_filename == '<string>': print_doctest_location(err) else: print_doctest_location(err) # Hm, we have a DocTestFailure exception. We need to # generate our own traceback try: exec(('raise ValueError' '("Expected and actual output are different")' ), err.test.globs) except: exc_info = sys.exc_info() print(''.join(traceback.format_exception_only(exc_info[0], exc_info[1]))) if _use_ipdb(): ipdb.post_mortem(exc_info[2]) else: pdb.post_mortem(exc_info[2]) raise zope.testrunner.interfaces.EndRun()
def __call__(self, *args, **kwargs): try: return self.main(*args, **kwargs) except Exception as error: print(traceback.format_exc(), file=sys.stderr) import ipdb ipdb.post_mortem()
def d(): try: yield except: type, value, tb = sys.exc_info() tb = traceback.print_exc() ipdb.post_mortem(tb)
async def slack_listen(): async for message in _listen( conversations=conversations, types=types ): def fixup_message(message): if "channel" in message: message["mucroom"] = config.slack.get_conversation( message["channel"] ).name if "user" in message: message["username"] = config.slack.get_user( message["user"] ).name message["body"] = message.get("text", "") try: fixup_message(message) except: import sys import ipdb ipdb.post_mortem(sys.exc_info()[2]) LOGGER.debug("Got message: {}".format(message)) mess = mess_encode(message) await redis_connection.send(mess)
def after_step(context, step): print('Status') if BEHAVE_DEBUG_ON_ERROR and step.status == "failed": # # -- ENTER DEBUGGER: Zoom in on failure location. # # NOTE: Use IPython debugger, same for pdb (basic python debugger). import ipdb ipdb.post_mortem(step.exc_traceback)
def handle_exception(self, e): print("\nException:", e) traceback.print_exc(file=sys.stdout) answer = questionary.select('Now what?', choices=[ 'Restart browser', 'Debug with ipdb', 'Debug with pdb', 'Exit', ]).ask() if answer == 'Debug with ipdb': try: import ipdb except ImportError: print('Please run "pip install ipdb" to install ipdb') sys.exit(1) ipdb.post_mortem() elif answer == 'Debug with pdb': import pdb pdb.post_mortem() elif answer == 'Restart browser': self.worker.restart() return self.worker.close() sys.exit()
def info(type, value, tb): if hasattr(sys, 'ps1') or not sys.stderr.isatty(): sys.__excepthook__(type, value, tb) else: import ipdb traceback.print_exception(type, value, tb) ipdb.post_mortem(tb)
def after_step(context, step): ''' behave hook called after running test step ''' if context.options.debug_on_error: import ipdb ipdb.post_mortem(step.exc_traceback)
def handle_packet_in(self, concrete_pkt): pyretic_pkt = self.concrete2pyretic(concrete_pkt) if self.debug_packet_in: debugger.set_trace() if USE_IPDB: with debugger.launch_ipdb_on_exception(): if self.mode == 'interpreted': output = self.policy.eval(pyretic_pkt) else: (output, eval_trace) = self.policy.track_eval(pyretic_pkt, dry=False) self.reactive0(pyretic_pkt, output, eval_trace) else: try: if self.mode == 'interpreted': output = self.policy.eval(pyretic_pkt) else: (output, eval_trace) = self.policy.track_eval(pyretic_pkt, dry=False) self.reactive0(pyretic_pkt, output, eval_trace) except: type, value, tb = sys.exc_info() traceback.print_exc() debugger.post_mortem(tb) if self.show_traces: print "<<<<<<<<< RECV <<<<<<<<<<<<<<<<<<<<<<<<<<" print util.repr_plus([pyretic_pkt], sep="\n\n") print print ">>>>>>>>> SEND >>>>>>>>>>>>>>>>>>>>>>>>>>" print util.repr_plus(output, sep="\n\n") print map(self.send_packet, output)
def drop_to_debugger(traceback): try: import ipdb as pdb except ImportError: warnings.warn('ipdb not available, falling back to pdb') import pdb pdb.post_mortem(traceback)
def _loop(self): while self.running: try: if self.updated: self.updated = False n = 100 while n > 0: n -= 1 try: self._do_update() self._do_update( ) # Yes we do this twice. Don't ask. break except SyntaxError: pass if self.restarted: self.restarted = False self.looper.__init__() if (not self.paused) and self.looper.loop_body(): self.running = False except Exception: traceback.print_exc() if self.debug_on_exception: try: pygame.event.set_grab(False) pygame.mouse.set_visible(True) except: pass ipdb.post_mortem(sys.exc_info()[2]) else: time.sleep(5)
def _loop(self): while self.running: try: if self.updated: self.updated = False n = 100 while n > 0: n -= 1 try: self._do_update() self._do_update() # Yes we do this twice. Don't ask. break except SyntaxError: pass if self.restarted: self.restarted = False self.looper.__init__() if (not self.paused) and self.looper.loop_body(): self.running = False except Exception: traceback.print_exc() if self.debug_on_exception: try: pygame.event.set_grab(False) pygame.mouse.set_visible(True) except: pass ipdb.post_mortem(sys.exc_info()[2]) else: time.sleep(5)
def debug(self): try: import ipdb ipdb.post_mortem(self.traceback) except ImportError: import pdb pdb.post_mortem(self.traceback)
def exception_handler(tag=None, pdb=False): """Context manager to handle exception with option to open a debugger. Parameter --------- tag: str Name to display before outputing error in red. pdb: bool If set to True, open a debugger if an error is raised. """ try: yield except KeyboardInterrupt: status = colorify("interrupted", YELLOW) print(f"\r{tag} {status}".ljust(LINE_LENGTH)) raise SystemExit(1) except BaseException: status = colorify("error", RED) print(f"{tag} {status}".ljust(LINE_LENGTH)) if pdb: # Use ipdb if it is available and default to pdb otherwise. try: from ipdb import post_mortem except ImportError: from pdb import post_mortem post_mortem() if DEBUG: raise else: import traceback traceback.print_exc()
def main(self): import pickle try: args = self.parse_args() the_data = self.load_data(args) results = self.do_work(args, the_data) except Exception: if not args.pdb_on_error: raise import traceback traceback.print_exc() try: import ipdb as pdb except ImportError: import pdb print() pdb.post_mortem(sys.exc_info()[2]) sys.exit(1) # save the results file if args.save_results: print("\nsaving results in '{}'".format(args.save_results)) results['_args'] = args with open(args.save_results, 'wb') as f: pickle.dump(results, f, protocol=2)
def post_mortem(exc_info): err = exc_info[1] if isinstance(err, (doctest.UnexpectedException, doctest.DocTestFailure)): if isinstance(err, doctest.UnexpectedException): exc_info = err.exc_info # Print out location info if the error was in a doctest if exc_info[2].tb_frame.f_code.co_filename == '<string>': print_doctest_location(err) else: print_doctest_location(err) # Hm, we have a DocTestFailure exception. We need to # generate our own traceback try: exec(('raise ValueError' '("Expected and actual output are different")'), err.test.globs) except: exc_info = sys.exc_info() print(''.join(traceback.format_exception_only(exc_info[0], exc_info[1]))) if _use_ipdb(): ipdb.post_mortem(exc_info[2]) else: pdb.post_mortem(exc_info[2]) raise zope.testrunner.interfaces.EndRun()
def _wrapExecution(self, seleniumParser, sd): """Wrap execution of selenium tests in setUp and tearDown functions if available""" if self.setUpFunc: logger.info("Calling setUp()") self.setUpFunc(sd) logger.info("setUp() finished") # remove all verification errors possibly generated during setUpFunc() sd.clean_verification_errors() try: return self._executeSelenium(seleniumParser, sd) except BaseException as e: if self.error_screenshot_dir: path = os.path.join(self.error_screenshot_dir, time.strftime('%Y%m%d.%H%M%S.png')) sd.save_screenshot(path) logger.error('Screenshot saved to %s' % path) if self.pmd: try: import ipdb as pdb except ImportError: import pdb pdb.post_mortem(e) else: raise finally: if self.tearDownFunc: logging.info("Calling tearDown()") self.tearDownFunc(sd) logger.info("tearDown() finished")
def main_wrapper(module, args): """This wraps the main method of an action so that: - backtrace is not printed by default - backtrace is printed is --backtrace was given - a pdb session is run if --pdb was given """ try: module.do(args) except Exception as e: if args.pdb: traceback = sys.exc_info()[2] print "" print "### Exception:", e print "### Starting a debugger" try: import ipdb ipdb.post_mortem(traceback) sys.exit(0) except ImportError: import pdb pdb.post_mortem(traceback) sys.exit(0) if args.backtrace: raise logger = logging.getLogger("\n") # small hack logger.error(str(e)) sys.exit(2)
def yield_values(extract, *args, **kw): """ Yields ``Value`` objects extracted using ``extract``. """ exc_info = () try: returned = extract(*args, **kw) for walker in walk(returned, should_iter_unless_list): for value in walker: yield Value(value) except BdbQuit: raise except Exception as exc: exc_info = sys.exc_info() yield Value(exc) if any(exc_info) and (Value.exit_on_exc or Value.debug_on_exc): if Value.debug_on_exc: import traceback try: import ipdb as pdb except ImportError: import pdb assert pdb traceback.print_tb(exc_info[2]) pdb.post_mortem(exc_info[2]) else: reraise(exc_info[0], exc_info[1], exc_info[2])
def new_fn(*args, **kwargs): try: return orig_fn(*args, **kwargs) except Exception as e: print(traceback.format_exc()) print(e) ipdb.post_mortem()
def main_wrapper(module, args): """This wraps the main method of an action so that: - backtrace is not printed by default - backtrace is printed is --backtrace was given - a pdb session is run if --pdb was given """ try: module.do(args) except Exception as e: if args.pdb: traceback = sys.exc_info()[2] print "" print "### Exception:", e print "### Starting a debugger" try: #pylint: disable-msg=F0401 import ipdb ipdb.post_mortem(traceback) sys.exit(0) except ImportError: import pdb pdb.post_mortem(traceback) sys.exit(0) if args.backtrace: raise ui.error(e.__class__.__name__, e) sys.exit(2)
def handle_packet_in(self, concrete_pkt): pyretic_pkt = self.concrete2pyretic(concrete_pkt) if self.debug_packet_in: debugger.set_trace() if USE_IPDB: with debugger.launch_ipdb_on_exception(): if self.mode == 'interpreted': output = self.policy.eval(pyretic_pkt) else: (output,eval_trace) = self.policy.track_eval(pyretic_pkt,dry=False) self.reactive0(pyretic_pkt,output,eval_trace) else: try: if self.mode == 'interpreted': output = self.policy.eval(pyretic_pkt) else: (output,eval_trace) = self.policy.track_eval(pyretic_pkt,dry=False) self.reactive0(pyretic_pkt,output,eval_trace) except : type, value, tb = sys.exc_info() traceback.print_exc() debugger.post_mortem(tb) if self.show_traces or True: self.trace("<<<<<<<<< RECV <<<<<<<<<<<<<<<<<<<<<<<<<<", timeStamped=True) self.trace(util.repr_plus([pyretic_pkt], sep="\n\n")) self.trace("") self.trace(">>>>>>>>> SEND >>>>>>>>>>>>>>>>>>>>>>>>>>", timeStamped=True) self.trace(util.repr_plus(output, sep="\n\n")) self.trace("") map(self.send_packet,output)
def main(argv=sys.argv, out=sys.stdout): setup_log_ = functools.partial( setup_log, str_formatter='%(asctime)s [%(levelname)s] %(message)s') try: return pacbio_args_runner(argv=argv[1:], parser=get_parser(), args_runner_func=args_runner, alog=logging.getLogger(__name__), setup_log_func=setup_log) # FIXME is there a more central place to deal with this? except Exception as e: type, value, tb = sys.exc_info() traceback.print_exc(file=sys.stderr) # Note: if kt.args.usePdb # This won't work. If an exception is raised in parseArgs, # then kt.args is not defined yet. if '--pdb' in argv: try: # this has better integration with ipython and is nicer # pip install ipdb import ipdb ipdb.post_mortem(tb) except ImportError: import pdb pdb.post_mortem(tb) else: # exit non-zero raise
def yield_values(extract, *args, **kw): """ Yields ``Value`` objects extracted using ``extract``. """ exc_info = () try: returned = extract(*args, **kw) for walker in walk(returned, should_iter_unless_list): for value in walker: yield Value(value) except Exception as exc: exc_info = sys.exc_info() yield Value(exc) if any(exc_info) and (Value.exit_on_exc or Value.debug_on_exc): if Value.debug_on_exc: import traceback try: import ipdb as pdb except ImportError: import pdb assert pdb traceback.print_tb(exc_info[2]) pdb.post_mortem(exc_info[2]) else: reraise(exc_info[0], exc_info[1], exc_info[2])
def _run(self): try: self.run() except Exception: e, m, tb = sys.exc_info() ipdb.post_mortem(tb) self.running = False
def on_command_loading_error(): LOGGER.develop(traceback.format_exc()) if config.debug_on_command_load_error_callback: import sys import ipdb ipdb.post_mortem(sys.exc_info()[2])
def main_wrapper(module, args): """This wraps the main method of an action so that: - backtrace is not printed by default - backtrace is printed is --backtrace was given - a pdb session is run if --pdb was given """ try: module.do(args) except Exception as e: if args.pdb: traceback = sys.exc_info()[2] print "" print "### Exception:", e print "### Starting a debugger" try: #pylint: disable-msg=F0401 import ipdb ipdb.post_mortem(traceback) sys.exit(0) except ImportError: import pdb pdb.post_mortem(traceback) sys.exit(0) if args.backtrace: raise message = str(e) if message.endswith("\n"): message = message[:-1] ui.error(e.__class__.__name__, message) sys.exit(2)
def main_wrapper(module, args): """ This wraps the main method of an action so that: - backtrace is not printed by default - backtrace is printed is --backtrace was given - a pdb session is run if --pdb was given """ try: module.do(args) except Exception as e: if args.pdb: traceback = sys.exc_info()[2] print("") print("### Exception:", e) print("### Starting a debugger") try: import ipdb ipdb.post_mortem(traceback) sys.exit(0) except ImportError: import pdb pdb.post_mortem(traceback) sys.exit(0) if args.backtrace: raise if six.PY3: message = str(e) else: message = str(e).decode("utf-8", errors="ignore") if message.endswith("\n"): message = message[:-1] ui.error(e.__class__.__name__, message) sys.exit(2)
def after_step(context, step): # "Given" triggers execution if step.step_type == 'given': context.interpreter.execute() # "When" triggers monitored execution if step.step_type == 'when': macrosteps = context.interpreter.execute() if not context._monitoring: context._monitoring = True context.monitored_trace = [] context.monitored_trace.extend(macrosteps) # Hook to enable debugging if step.step_type == 'then' and step.status == 'failed' and context.config.userdata.get( 'debug_on_error'): try: import ipdb as pdb except ImportError: import pdb print('--------------------------------------------------------------') print('Dropping into (i)pdb.', end='\n\n') print('Variable context holds the current execution context of Behave') print('You can access the interpreter using context.interpreter, the') print('trace using context.trace and the monitored trace using') print('context.monitored_trace.') print('--------------------------------------------------------------') pdb.post_mortem(step.exc_traceback)
def _debug_on_error(context, step): if step.status == 'failed' and context.config.userdata.getbool("debug"): try: import ipdb ipdb.post_mortem(step.exc_traceback) except ImportError: import pdb pdb.post_mortem(step.exc_traceback)
def write_error(self, status_code, **kwargs): super().write_error(status_code, **kwargs) if self.settings.get("serve_traceback") and "exc_info" in kwargs: try: import ipdb as pdb except: import pdb pdb.post_mortem(kwargs['exc_info'][2])
def _excepthook(self, etype, evalue, etb): from IPython.core import ultratb ultratb.FormattedTB()(etype, evalue, etb) for exc in [KeyboardInterrupt, FileNotFoundError]: if issubclass(etype, exc): sys.exit(-1) import ipdb ipdb.post_mortem(etb)
def _launch_debugger_on_exception(environ, start_response): try: return app(environ, start_response) except Exception as exc: log.exception(exc) e, m, tb = sys.exc_info() ipdb.post_mortem(tb) raise
def interceptor(*args, **kw): try: result = olde_debug_call(*args, **kw) except: type, value, tb = sys.exc_info() pdb.post_mortem(tb) raise return result
def launch_debugger_on_exception(req, app): try: return req.get_response(app) except Exception as exc: log.exception(exc) e, m, tb = sys.exc_info() ipdb.post_mortem(tb) raise
def debug(self): if self.debugger: try: from ipdb import post_mortem except ImportError: from pdb import post_mortem tb = self.exc_info[2] post_mortem(tb)
def wrapper(*args, **kwds): try: return func(*args, **kwds) except Exception: e, m, tb = sys.exc_info() print(m.__repr__(), file=sys.stderr) ipdb.post_mortem(tb) raise
def pdberror(): import sys try: import ipdb as pdb except ImportError: import pdb pdb.post_mortem(sys.exc_info()[2]) return web.debugerror()
def after_step(context, step): # from https://github.com/behave/behave/blob/master/docs/tutorial.rst# # debug-on-error-in-case-of-step-failures # and https://stackoverflow.com/a/22344473/399726 if BEHAVE_DEBUG_ON_ERROR and step.status == "failed": # -- ENTER DEBUGGER: Zoom in on failure location. # NOTE: Use IPython debugger, same for pdb (basic python debugger). import ipdb ipdb.post_mortem(step.exc_traceback)
def launch_ipdb_on_exception(): try: yield except Exception: e, m, tb = sys.exc_info() print(m.__repr__(), file=sys.stderr) post_mortem(tb) finally: pass
def run_with_try(func): """ Call `func()` with fallback in pdb on error. """ try: return func() except Exception, e: print '%s: %s' % (e.__class__, e) ipdb.post_mortem(sys.exc_info()[2]) raise
def after_step(context, step): """ Define actions to take after the completion of a step. Note: `behave` must be run with `-D BEHAVE_DEBUG_ON_ERROR` in order for the enter debugger "after step" failure to work. """ if BEHAVE_DEBUG_ON_ERROR and step.status == "failed": import ipdb ipdb.post_mortem(step.exc_traceback)
def set_debug_if_allowed(config): if config.PDB: _, _, tb = sys.exc_info() try: import ipdb as pdb except ImportError: import pdb pdb.post_mortem(tb)