我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pdb.post_mortem()。
def boto_except_hook(debugger_flag, debug_flag): def excepthook(typ, value, tb): if typ is bdb.BdbQuit: sys.exit(1) sys.excepthook = sys.__excepthook__ if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty(): if debugger.__name__ == 'epdb': debugger.post_mortem(tb, typ, value) else: debugger.post_mortem(tb) elif debug_flag: print(traceback.print_tb(tb)) sys.exit(1) else: print(value) sys.exit(1) return excepthook
def testUpDown(self): try: x_np = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8).reshape([2, 3, 1]) y_np = np.array([[4, 5, 6], [1, 2, 3]], dtype=np.uint8).reshape([2, 3, 1]) for use_gpu in [False, True]: with self.test_session(use_gpu=use_gpu): x_tf = constant_op.constant(x_np, shape=x_np.shape) y = image_ops.flip_up_down(x_tf) y_tf = y.eval() self.assertAllEqual(y_tf, y_np) except: import sys, pdb, traceback type, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
def temp_testCropping(self): x_shape = [4, 8, 1] x_np = np.array([[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8]], dtype=np.int32).reshape(x_shape) y_np = np.array([[3, 4, 5, 6], [3, 4, 5, 6]]).reshape([2, 4, 1]) with self.test_session(): x = constant_op.constant(x_np, shape=x_shape) try: y = image_ops.central_crop(x, 0.5) except: import pdb pdb.post_mortem() y_tf = y.eval() self.assertAllEqual(y_tf, y_np)
def testRounding(self): try: x = [0.49, 0.7, -0.3, -0.8] for dtype in [np.float32, np.double]: x_np = np.array(x, dtype=dtype) for use_gpu in [True, False]: with self.test_session(use_gpu=use_gpu): x_tf = constant_op.constant(x_np, shape=x_np.shape) y_tf = math_ops.round(x_tf) y_tf_np = y_tf.eval() y_np = np.round(x_np) self.assertAllClose(y_tf_np, y_np, atol=1e-2) except: import sys, pdb, traceback type, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
def boto_except_hook(debugger_flag, debug_flag): def excepthook(typ, value, tb): if typ is bdb.BdbQuit: sys.exit(1) sys.excepthook = sys.__excepthook__ if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty(): if debugger.__name__ == 'epdb': debugger.post_mortem(tb, typ, value) else: debugger.post_mortem(tb) elif debug_flag: print traceback.print_tb(tb) sys.exit(1) else: print value sys.exit(1) return excepthook
def __init__(self, reporter, kw="", post_mortem=False, seed=None, fast_threshold=None, slow_threshold=None): self._post_mortem = post_mortem self._kw = kw self._count = 0 self._root_dir = sympy_dir self._reporter = reporter self._reporter.root_dir(self._root_dir) self._testfiles = [] self._seed = seed if seed is not None else random.random() # Defaults in seconds, from human / UX design limits # http://www.nngroup.com/articles/response-times-3-important-limits/ # # These defaults are *NOT* set in stone as we are measuring different # things, so others feel free to come up with a better yardstick :) if fast_threshold: self._fast_threshold = float(fast_threshold) else: self._fast_threshold = 0.1 if slow_threshold: self._slow_threshold = float(slow_threshold) else: self._slow_threshold = 10
def _hook(type_, value, tback): """Exception hook callback.""" if hasattr(sys, 'ps1') or not sys.stderr.isatty(): # we are in interactive mode or we don't have a tty-like # device, so we call the default hook sys.__excepthook__(type_, value, tback) else: import traceback import pdb # we are NOT in interactive mode, print the exception... traceback.print_exception(type_, value, tback) # Dirty hack because Py27 doesn't chain exceptions if value.args: tb2 = value.args[-1] if isinstance(tb2, type(tback)): ex = value.args[-2] print >>sys.stderr, '{}Caused by{} '.format( ansi('1;35m'), ansi('0m')), traceback.print_exception(type_(ex), ex, tb2) print # ...then start the debugger in post-mortem mode. # pdb.pm() # deprecated pdb.post_mortem(tback) # more "modern"
def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None, captureVars=False, Failure__init__=Failure.__init__): """ Initialize failure object, possibly spawning pdb. """ if (exc_value, exc_type, exc_tb) == (None, None, None): exc = sys.exc_info() if not exc[0] == self.__class__ and DO_POST_MORTEM: try: strrepr = str(exc[1]) except: strrepr = "broken str" print("Jumping into debugger for post-mortem of exception '%s':" % (strrepr,)) import pdb pdb.post_mortem(exc[2]) Failure__init__(self, exc_value, exc_type, exc_tb, captureVars)
def setUp(self): """ Override pdb.post_mortem so we can make sure it's called. """ # Make sure any changes we make are reversed: post_mortem = pdb.post_mortem if _shouldEnableNewStyle: origInit = failure.Failure.__init__ else: origInit = failure.Failure.__dict__['__init__'] def restore(): pdb.post_mortem = post_mortem if _shouldEnableNewStyle: failure.Failure.__init__ = origInit else: failure.Failure.__dict__['__init__'] = origInit self.addCleanup(restore) self.result = [] pdb.post_mortem = self.result.append failure.startDebugMode()
def warn(exc, nav, repl_pairs, local_opt, node): """ Failure_callback for NavigatorOptimizer: print traceback. """ if config.on_opt_error != 'ignore': _logger.error("Optimization failure due to: %s" % str(local_opt)) _logger.error("node: %s" % str(node)) _logger.error("TRACEBACK:") _logger.error(traceback.format_exc()) if config.on_opt_error == 'pdb': pdb.post_mortem(sys.exc_info()[2]) elif isinstance(exc, AssertionError) or config.on_opt_error == 'raise': # We always crash on AssertionError because something may be # seriously wrong if such an exception is raised. raise exc
def _HandleRunPluginException(self, ui_renderer, e): """Handle all exceptions thrown by logging to the console.""" if isinstance(e, plugin.InvalidArgs): self.logging.fatal("Invalid Args: %s" % e) elif isinstance(e, plugin.PluginError): self.logging.fatal(str(e)) elif isinstance(e, KeyboardInterrupt) or isinstance(e, plugin.Abort): logging.error("Aborted\r\n") else: error_status = traceback.format_exc() # Report the error to the renderer. self.logging.fatal(error_status) # If anything goes wrong, we break into a debugger here. if self.GetParameter("debug"): pdb.post_mortem(sys.exc_info()[2]) # This method is called from the exception handler - this bare raise # will preserve backtraces. raise # pylint: disable=misplaced-bare-raise
def main(): try: root_logger = logging.getLogger() root_logger.setLevel(logging.INFO) root_logger.handlers[0].setFormatter( logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') ) _parser_obj = _get_parser() _args = _parser_obj.parse_args() if _args.verbose: root_logger.setLevel(logging.DEBUG) _args.action(_args) except (Exception, KeyboardInterrupt): import pdb pdb.post_mortem() raise
def setup_exceptionhook(ipython=False): """Overloads default sys.excepthook with our exceptionhook handler. If interactive, our exceptionhook handler will invoke pdb.post_mortem; if not interactive, then invokes default handler. """ def _niceman_pdb_excepthook(type, value, tb): import traceback traceback.print_exception(type, value, tb) print() if is_interactive(): import pdb pdb.post_mortem(tb) if ipython: from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB(mode='Verbose', # color_scheme='Linux', call_pdb=is_interactive()) else: sys.excepthook = _niceman_pdb_excepthook
def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb # Note that tempfile.NameTemporaryFile() cannot be used. As the # docs say, a file so created cannot be opened by name a second time # on modern Windows boxes, and execfile() needs to open it. srcfilename = tempfile.mktemp(".py", "doctestdebug") f = open(srcfilename, 'w') f.write(src) f.close() try: if globs: globs = globs.copy() else: globs = {} if pm: try: execfile(srcfilename, globs, globs) except: print sys.exc_info()[1] pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause # backslashes to get treated as metacharacters on Windows. pdb.run("execfile(%r)" % srcfilename, globs, globs) finally: os.remove(srcfilename)
def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb # Note that tempfile.NameTemporaryFile() cannot be used. As the # docs say, a file so created cannot be opened by name a second time # on modern Windows boxes, and execfile() needs to open it. srcfilename = tempfile.mktemp(".py", "doctestdebug") f = open(srcfilename, 'w') f.write(src) f.close() try: if globs: globs = globs.copy() else: globs = {} if pm: try: execfile(srcfilename, globs, globs) except: print(sys.exc_info()[1]) pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause # backslashes to get treated as metacharacters on Windows. pdb.run("execfile(%r)" % srcfilename, globs, globs) finally: os.remove(srcfilename)
def post_mortem(): pdb.post_mortem(sys.exc_info()[2]) logger.debug('Graceful exit from debugger.')
def main(): debug = os.environ.get('DEBUG', '').lower() in ('1', 'y') verbose = os.environ.get('VERBOSE', '').lower() in ('1', 'y') config = Configuration() config['debug'] = debug config['verbose'] = debug or verbose config['color'] = sys.stderr.isatty() dictConfig(config.logging_dict()) logger.debug("Debug mode enabled.") try: exit(wrapped_main(config)) except pdb.bdb.BdbQuit: logger.info("Graceful exit from debugger.") except UserError as e: logger.critical("%s", e) exit(e.exit_code) except Exception: logger.exception('Unhandled error:') if debug and sys.stdout.isatty(): logger.debug("Dropping in debugger.") pdb.post_mortem(sys.exc_info()[2]) else: logger.error( "Please file an issue at " "https://github.com/dalibo/ldap2pg/issues with full log.", ) exit(os.EX_SOFTWARE)
def _debuginit(self, exc_value=None, exc_type=None, exc_tb=None, Failure__init__=Failure.__init__.im_func): if (exc_value, exc_type, exc_tb) == (None, None, None): exc = sys.exc_info() if not exc[0] == self.__class__ and DO_POST_MORTEM: print "Jumping into debugger for post-mortem of exception '%s':" % exc[1] import pdb pdb.post_mortem(exc[2]) Failure__init__(self, exc_value, exc_type, exc_tb)
def debug(self, err): import sys # FIXME why is this import here? ec, ev, tb = err stdout = sys.stdout sys.stdout = sys.__stdout__ try: pdb.post_mortem(tb) finally: sys.stdout = stdout
def _start_linter(): """ This is a pre-alpha API. You're not supposed to use it at all, except for testing. It will very likely change. """ import jedi if '--debug' in sys.argv: jedi.set_debug_function() for path in sys.argv[2:]: if path.startswith('--'): continue if isdir(path): import fnmatch import os paths = [] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, '*.py'): paths.append(os.path.join(root, filename)) else: paths = [path] try: for path in paths: for error in jedi.Script(path=path)._analysis(): print(error) except Exception: if '--pdb' in sys.argv: import traceback traceback.print_exc() import pdb pdb.post_mortem() else: raise
def _main(): """Entry point""" 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)
def run_smoketests(raiden_service, test_config, debug=False): """ Test that the assembled raiden_service correctly reflects the configuration from the smoketest_genesis. """ try: chain = raiden_service.chain assert ( raiden_service.default_registry.address == test_config['contracts']['registry_address'].decode('hex') ) assert ( raiden_service.default_registry.token_addresses() == [test_config['contracts']['token_address'].decode('hex')] ) assert len(chain.address_to_discovery.keys()) == 1 assert ( chain.address_to_discovery.keys()[0] == test_config['contracts']['discovery_address'].decode('hex') ) discovery = chain.address_to_discovery.values()[0] assert discovery.endpoint_by_address(raiden_service.address) != TEST_ENDPOINT assert len(raiden_service.token_to_channelgraph.values()) == 1 graph = raiden_service.token_to_channelgraph.values()[0] channel = graph.partneraddress_to_channel[TEST_PARTNER_ADDRESS.decode('hex')] assert channel.can_transfer assert channel.contract_balance == channel.distributable == TEST_DEPOSIT_AMOUNT assert channel.state == CHANNEL_STATE_OPENED run_restapi_smoketests(raiden_service, test_config) except Exception: error = traceback.format_exc() if debug: pdb.post_mortem() return error
def pdb_hook(exctype, value, traceback): pdb.post_mortem(traceback)
def test_postmortem_noargs(): def fn(): try: a = 1 1/0 except ZeroDivisionError: pdb.post_mortem(Pdb=PdbTest) check(fn, """ [NUM] > .*fn() -> 1/0 # c """)
def test_postmortem_needs_exceptioncontext(): try: # py.test bug - doesnt clear the index error from finding the next item sys.exc_clear() except AttributeError: # Python 3 doesn't have sys.exc_clear pass py.test.raises(AssertionError, pdb.post_mortem, Pdb=PdbTest)
def _debug_on_error(context, step): if 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 main(args=None): p = make_parser() ns = p.parse_args(args=args) try: save_sparse(**vars(ns)) except Exception: import sys import pdb import traceback type, value, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb)
def cli(main): # A decorator to add consistent CLI bootstrap # # Decorated function must accept argv and environ arguments and return an # exit code. # # The decorator adds basic logging setup and error management. The # decorated function can just raise exception and log using logging module # as usual. def cli_wrapper(argv=sys.argv[1:], environ=os.environ): debug = strtobool(environ.get('DEBUG', '0')) if debug: os.environ['TEMBOARD_LOGGING_LEVEL'] = b'DEBUG' retcode = 1 try: setup_logging(level='DEBUG' if debug else 'ERROR') logger.debug("Starting temBoard agent.") retcode = main(argv, environ) or 1 except KeyboardInterrupt: logger.info('Terminated.') except pdb.bdb.BdbQuit: logger.info("Graceful exit from debugger.") except UserError as e: retcode = e.retcode logger.critical("%s", e) except Exception: logger.exception('Unhandled error:') if debug: pdb.post_mortem(sys.exc_info()[2]) else: logger.error("This is a bug!") logger.error( "Please report traceback to " "https://github.com/dalibo/temboard-agent/issues! Thanks!" ) exit(retcode) return cli_wrapper
def __init__(self, reporter, kw="", post_mortem=False, seed=None): self._post_mortem = post_mortem self._kw = kw self._count = 0 self._root_dir = sympy_dir self._reporter = reporter self._reporter.root_dir(self._root_dir) self._testfiles = [] self._seed = seed if seed is not None else random.random()
def post_mortem(level = 1): """Provides a command line interface to python after an exception's occurred""" if config.DEBUG >= level: pdb.post_mortem()
def debugger(): """If called in the context of an exception, calls post_mortem; otherwise set_trace. ``ipdb`` is preferred over ``pdb`` if installed. """ e, m, tb = sys.exc_info() if tb is not None: _debugger.post_mortem(tb) else: _debugger.set_trace()