From 2952c9ba597033c469bd06d65dea67cd7c36f0dd Mon Sep 17 00:00:00 2001 From: Stan Seibert Date: Tue, 16 Aug 2011 15:55:38 -0400 Subject: Move general utility functions out of sim.py into tools. The enable_debug_on_crash() function sets the exception hook to start up PDB on uncaught exceptions The @profile_if_possible decorator applies the kernprof.py @profile decorator if available (because of profiling in progress), otherwise does nothing. --- sim.py | 26 +++----------------------- tools.py | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/sim.py b/sim.py index 0bd335d..579dae8 100755 --- a/sim.py +++ b/sim.py @@ -11,34 +11,14 @@ import generator from generator import constant import gpu from fileio import root -import ROOT +from tools import profile_if_possible, enable_debug_on_crash def pick_seed(): '''Returns a seed for a random number generator selected using a mixture of the current time and the current process ID.''' return int(time.time()) ^ (os.getpid() << 16) -def info(type, value, tb): - 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, tb) - else: - import traceback, pdb - # we are NOT in interactive mode, print the exception... - traceback.print_exception(type, value, tb) - print - # ...then start the debugger in post-mortem mode. - pdb.pm() - - -# Allow profile decorator to exist, but do nothing if not running under kernprof -try: - profile = profile -except NameError: - profile = lambda x: x - -@profile +@profile_if_possible def main(): parser = optparse.OptionParser('%prog') parser.add_option('-b', type='int', dest='nbits', default=10) @@ -148,5 +128,5 @@ def main(): print >>sys.stderr, 'Done. %1.1f events/sec, %1.0f photons/sec.' % (options.nevents/(end_sim - start_sim), nphotons/(end_sim - start_sim)) if __name__ == '__main__': - sys.excepthook = info + enable_debug_on_crash() main() diff --git a/tools.py b/tools.py index 6835228..ba36f6d 100644 --- a/tools.py +++ b/tools.py @@ -1,6 +1,30 @@ import numpy as np import time import datetime +import sys + +def debugger_hook(type, value, tb): + 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, tb) + else: + import traceback, pdb + # we are NOT in interactive mode, print the exception... + traceback.print_exception(type, value, tb) + print + # ...then start the debugger in post-mortem mode. + pdb.pm() + +def enable_debug_on_crash(): + '''Start the PDB console when an uncaught exception propagates to the top.''' + sys.excepthook = debugger_hook + +# Allow profile decorator to exist, but do nothing if not running under kernprof +try: + profile_if_possible = profile +except NameError: + profile_if_possible = lambda x: x def timeit(func): def f(*args, **kwargs): -- cgit