我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用bdb.BdbQuit()。
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 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 test_entrypoint_bdb_quit(mocker): mocker.patch('jenkins_epo.script.logging') from jenkins_epo.script import entrypoint from bdb import BdbQuit main = mocker.patch('jenkins_epo.main.main') CACHE = mocker.patch('jenkins_epo.cache.CACHE') main.side_effect = BdbQuit() with pytest.raises(SystemExit): entrypoint() assert CACHE.close.mock_calls
def entrypoint(argv=None): argv = argv or sys.argv[1:] logging.config.dictConfig(setup_logging()) distribution = pkg_resources.get_distribution('jenkins-epo') logger.info("Starting jenkins-epo %s.", distribution.version) logger.debug("Debug mode enabled") # Import modules after logging is setup from .cache import CACHE from .main import main from .settings import SETTINGS try: logger.debug("Executing %s.", ' '.join(argv)) main(argv) logger.info("Done.") except bdb.BdbQuit: logger.info('Graceful exit from debugger.') except Exception as e: if SETTINGS.DEBUG: logger.error("%s: %s", type(e), e) post_mortem() else: logger.exception("Unhandled error:") sys.exit(1) except KeyboardInterrupt: # Hide ^C in terminal sys.stderr.write('\r') if SETTINGS.DEBUG: logger.warn("Dropping in post interrupt PDB!") post_mortem() else: tb = traceback.format_tb(sys.exc_info()[-1]) tb = tb[-6:] logger.warn("Interrupted at:\n%s", ''.join(tb).strip()) sys.exit(1) finally: CACHE.close() sys.exit(0)
def check_interactive_exception(call, report): return call.excinfo and not ( hasattr(report, "wasxfail") or call.excinfo.errisinstance(skip.Exception) or call.excinfo.errisinstance(bdb.BdbQuit))
def test_bdb_quit(): from temboardagent.cli import cli from bdb import BdbQuit @cli def main(argv, environ): raise BdbQuit() with pytest.raises(SystemExit) as ei: main() assert 1 == ei.value.code
def BdbQuit_excepthook(et, ev, tb, excepthook=None): """Exception hook which handles `BdbQuit` exceptions. All other exceptions are processed using the `excepthook` parameter. """ warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1", DeprecationWarning, stacklevel=2) if et==bdb.BdbQuit: print('Exiting Debugger.') elif excepthook is not None: excepthook(et, ev, tb) else: # Backwards compatibility. Raise deprecation warning? BdbQuit_excepthook.excepthook_ori(et,ev,tb)
def run(self, cmd,globals=None, locals=None, start_stepping = 1): if not isinstance(cmd, (basestring, types.CodeType)): raise TypeError("Only strings can be run") self.last_cmd_debugged = cmd if start_stepping: self.isInitialBreakpoint = 0 else: self.isInitialBreakpoint = 1 try: if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() self.prep_run(cmd) sys.settrace(self.trace_dispatch) if type(cmd) != types.CodeType: cmd = cmd+'\n' try: try: if start_stepping: self.skipBotFrame = SKIP_STEP else: self.skipBotFrame = SKIP_RUN exec cmd in globals, locals except bdb.BdbQuit: pass finally: self.skipBotFrame = SKIP_NONE self.quitting = 1 sys.settrace(None) finally: self.done_run(cmd)
def runexec(self, what, globs=None, locs=None): self.reset() sys.settrace(self.trace_dispatch) try: try: exec what in globs, locs except bdb.BdbQuit: pass finally: self.quitting = 1 sys.settrace(None)
def run(self, cmd,globals=None, locals=None, start_stepping = 1): if not isinstance(cmd, (str, types.CodeType)): raise TypeError("Only strings can be run") self.last_cmd_debugged = cmd if start_stepping: self.isInitialBreakpoint = 0 else: self.isInitialBreakpoint = 1 try: if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() self.prep_run(cmd) sys.settrace(self.trace_dispatch) if type(cmd) != types.CodeType: cmd = cmd+'\n' try: try: if start_stepping: self.skipBotFrame = SKIP_STEP else: self.skipBotFrame = SKIP_RUN exec(cmd, globals, locals) except bdb.BdbQuit: pass finally: self.skipBotFrame = SKIP_NONE self.quitting = 1 sys.settrace(None) finally: self.done_run(cmd)
def runexec(self, what, globs=None, locs=None): self.reset() sys.settrace(self.trace_dispatch) try: try: exec(what, globs, locs) except bdb.BdbQuit: pass finally: self.quitting = 1 sys.settrace(None)
def enable_debug(self): """Wrap the resource methods with debugger.""" debug(self.initialize, ignore_exceptions=[KeyboardInterrupt, BdbQuit]) debug(self.finalize, ignore_exceptions=[KeyboardInterrupt, BdbQuit]) debug(self.validate, ignore_exceptions=[KeyboardInterrupt, BdbQuit]) debug(self.reset, ignore_exceptions=[KeyboardInterrupt, BdbQuit]) debug(self.store_state, ignore_exceptions=[KeyboardInterrupt, BdbQuit]) for resource in self.get_sub_resources(): resource.enable_debug()
def test_pdb_on_BdbQuit(self, testdir, pdblist): rep = runpdb_and_get_report(testdir, """ import bdb def test_func(): raise bdb.BdbQuit """) assert rep.failed assert len(pdblist) == 0
def BdbQuit_excepthook(et, ev, tb, excepthook=None): """Exception hook which handles `BdbQuit` exceptions. All other exceptions are processed using the `excepthook` parameter. """ warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1", DeprecationWarning) if et==bdb.BdbQuit: print('Exiting Debugger.') elif excepthook is not None: excepthook(et, ev, tb) else: # Backwards compatibility. Raise deprecation warning? BdbQuit_excepthook.excepthook_ori(et,ev,tb)
def trace_dispatch(self, frame, event, arg): try: return super(Pdb, self).trace_dispatch(frame, event, arg) except bdb.BdbQuit: pass
def main(): parser = argparse.ArgumentParser() parser.add_argument('command', choices=['run', 'list_events', 'print_configuration']) parser.add_argument('components', nargs='?', default=None, type=str) parser.add_argument('--verbose', '-v', action='store_true') parser.add_argument('--config', '-c', type=str, default=None, help='Path to a config file to load which will take precedence over all other configs') parser.add_argument('--input_draw', '-d', type=int, default=0, help='Which GBD draw to use') parser.add_argument('--model_draw', type=int, default=0, help="Which draw from the model's own variation to use") parser.add_argument('--results_path', '-o', type=str, default=None, help='Path to write results to') parser.add_argument('--process_number', '-n', type=int, default=1, help='Instance number for this process') parser.add_argument('--log', type=str, default=None, help='Path to log file') parser.add_argument('--pdb', action='store_true', help='Run in the debugger') args = parser.parse_args() log_level = logging.DEBUG if args.verbose else logging.ERROR logging.basicConfig(filename=args.log, level=log_level) try: do_command(args) except (BdbQuit, KeyboardInterrupt): raise except Exception as e: if args.pdb: import pdb import traceback traceback.print_exc() pdb.post_mortem() else: logging.exception("Uncaught exception {}".format(e)) raise
def __init__(self, file, fresh=False): self.file = file info = os.stat(self.file) self.hash = str(hash(info.st_size + round(info.st_mtime))) # Why round: during file copying we may cut mikrosecond part behind mantisa. #MailDraft.setHash(self.hash) #MailDraft.setDir(os.path.dirname(file) + "/") # cache-file s metadaty zdrojoveho souboru Config.setCacheDir(os.path.dirname(file) + "/" + ntpath.basename(self.file) + "_convey" + self.hash + "/") self.cacheFile = Config.getCacheDir() + ntpath.basename(self.file) + ".cache" #"cache/" + if os.path.isfile(self.cacheFile) and not fresh: print("File {} has already been processed.".format(self.file)) #import pdb;pdb.set_trace() try: # try to depickle self.csv = jsonpickle.decode(open(self.cacheFile, "r").read(), keys = True) except: print("Cache file loading failed, let's process it all again. If you continue, cache gets deleted.") input() if Config.isDebug(): ipdb.set_trace() self._treat() if self.csv: try: if self.csv.isAnalyzed: self.csv.informer.soutInfo() elif self.csv.isFormatted: self.csv.informer.soutInfo() s = "It seems the file has already been formatted." # X Continue to analysis (or you'll be asked to do format again)?" print(s) #if Dialogue.isYes(s): # self.csv.runAnalysis() #else: # self._treat() except BdbQuit: # we do not want to catch quit() signal from ipdb print("Stopping.") quit() except Exception as e: #ipdb.set_trace() print(e) print("Format of the file may have changed since last time. Let's process it all again. If you continue, cache gets deleted.") self._treat() else: self._treat() # process file else: if not os.path.exists(Config.getCacheDir()): os.makedirs(Config.getCacheDir()) self._treat() # process file ## # Store
def debug(self, test, pm=False): self.test = test # Save the old stdout self.save_stdout = sys.stdout # Convert the source docstring to a script. script = self._script_from_examples(test.docstring) # Create a debugger. debugger = _OutputRedirectingPdb(sys.stdout) # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). save_set_trace = pdb.set_trace pdb.set_trace = debugger.set_trace # Write the script to a temporary file. 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(script) f.close() # Set up the globals test.globs['CHECK_OUTPUT'] = self._check_output test.globs['CHECK_EXCEPTION'] = self._check_exception test.globs['__print__'] = self._print_if_not_none test.globs['__set_trace__'] = debugger.set_trace test.globs['__examples__'] = self.test.examples try: if pm is False: debugger.run("execfile(%r)" % srcfilename, test.globs, test.globs) else: try: sys.stdout = _SpoofOut() try: execfile(srcfilename, test.globs) except bdb.BdbQuit: return except: sys.stdout = self.save_stdout exc_info = sys.exc_info() exc_msg = traceback.format_exception_only( exc_info[0], exc_info[1])[-1] self.save_stdout.write(self.runner.DIVIDER+'\n') self.save_stdout.write('Unexpected exception:\n' + _indent(exc_msg)) raise #self.post_mortem(debugger, exc_info[2]) finally: sys.stdout = self.save_stdout finally: sys.set_trace = save_set_trace os.remove(srcfilename)