[BangPypers] "continue" in "try..except"

Noufal Ibrahim noufal at gmail.com
Sun Nov 20 12:11:10 CET 2011


<Nikunj.Badjatya at emc.com> writes:

> Hi ,
>
> Please look at the below code snippet:
>
> {{{
>
> if __name__ == "__main__":
>     try:
>         main()
>     except KeyboardInterrupt:

[...]

KeyboardInterrupt is an exception that SIGINT(2) is translated into by
the interpreter.

If you want to handle a ctrl C, use the signal module and create a
handler that will do what you need rather than rely on an exception
which is only for "exceptional" things. In your case, a SIGINT is part
of the workflow.

Navin's suggestion to restructure your code is correct. This is not an
idiomatic way to use exceptions. Following is a suggestion (untested)

import sys
import signal

def user_interrupt_handler(sig, frame):
   if raw_input() == "y":
     sys.exit(-1)

def main():
   signal.signal(signal.SIGINT, user_interrupt_handler)
   do_install()

if __name__ == __main__:
    try:
      main()   
      # Successful
    except Exception:
      perform_cleanup()
      # Errors


[...]


-- 
~noufal
http://nibrahim.net.in

Cum tacent, clamant. When they are silent, they shout. -Cicero


More information about the BangPypers mailing list