resume execution after catching with an excepthook?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Oct 24 21:15:10 EDT 2012
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
More information about the Python-list
mailing list