def debugexcept(type, value, tb):
    if hasattr(sys, 'ps1') or not (sys.stderr.isatty() and sys.stdin.isatty()
        ) or type == SyntaxError:
        sys.__excepthook__(type, value, tb)
Catching a python app before it exits