0

I'am writing console program. I want that save flow may break with Cntr-c only after answer on question: Do you really want break it?

def sigint_handler(signal, frame):
    try:
        Exit = (str(raw_input("Break ? Y/N")))
        if Exit == "Y" or Exit=="y":
            raise KeyboardInterrupt()
    except KeyboardInterrupt:
        raise KeyboardInterrupt()
    except Exception as e:
        pass

signal.signal(signal.SIGINT,sigint_handler)
i=0

while i<1000:
    i=i+1
    print "%d\n"%i
    sleep(0.5)

It's fail if I try cntl+c instead of Y:

71

72

73

74

75

^CBreak ? Y/Ny

File "/home.local/valerys/rde_1_3/rdepyui/bin/../api/cli.py", line 48, in sigint_handler Exit = (str(raw_input("Break ? Y/N"))) RuntimeError: can't re-enter readline

1 Answer 1

3

Why do you make a re-raise of KeyboardInterrupt in the except block? In this way you catch the first KeyboardInterrupt but you don't have another try/except block for catching the second. Maybe a better solution is to call

try:
    Exit = (str(raw_input("Break ? Y/N")))
    if Exit == "Y" or Exit=="y":
        raise KeyboardInterrupt()
except KeyboardInterrupt:
    sys.exit()

for a clean exit strategy. I hope this can help you.

Sign up to request clarification or add additional context in comments.

3 Comments

why not exiting directly, without raising the exception?
@Pynchia : I suppose that this exception raise is needed to other purpose not shown in this simplified version of code but, other this, I don't see any reason to raise this exception.
It's CLI and I want that user doesn't cancel execution of program flow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.