resume execution after catching with an excepthook?

andrea crotti andrea.crotti.0 at gmail.com
Thu Oct 25 10:27:24 EDT 2012


2012/10/25 Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
> On Wed, 24 Oct 2012 13:51:30 +0100, andrea crotti wrote:
>
>> So I would like to be able to ask for confirmation when I receive a C-c,
>> and continue if the answer is "N/n".
>
> I don't think there is any way to do this directly.
>
> Without a try...except block, execution will cease after an exception is
> caught, even when using sys.excepthook. I don't believe that there is any
> way to jump back to the line of code that just failed (and why would you,
> it will just fail again) or the next line (which will likely fail because
> the previous line failed).
>
> I think the only way you can do this is to write your own execution loop:
>
> while True:
>     try:
>         run(next_command())
>     except KeyboardInterrupt:
>         if confirm_quit():
>             break
>
>
> Of course you need to make run() atomic, or use transactions that can be
> reverted or backed out of. How plausible this is depends on what you are
> trying to do -- Python's Ctrl-C is not really designed to be ignored.
>
> Perhaps a better approach would be to treat Ctrl-C as an unconditional
> exit, and periodically poll the keyboard for another key press to use as
> a conditional exit. Here's a snippet of platform-specific code to get a
> key press:
>
> http://code.activestate.com/recipes/577977
>
> Note however that it blocks if there is no key press waiting.
>
> I suspect that you may need a proper event loop, as provided by GUI
> frameworks, or curses.
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list



Ok thanks, but here the point is not to resume something that is going
to fail again, just to avoid accidental kill of processes that take a
long time.  Probably needed only by me in debugging mode, but anyway I
can do the simple try/except then, thanks..



More information about the Python-list mailing list