0

I am trying to not stop the program when the user press Ctrl + C.

Now it's like this:

(programm running)
...
(user press ctrl+c)
You pressed ctrl+c
breaks

What I want is:

(programm running)
...
(user press ctrl+c)
You pressed ctrl+c
not breaks

How can I do this? Is it impossible?

I tried this code:

try:
    while True: 
        userinput = input()
        if userinput == "stop":
            break
except (KeyboardInterrupt, SystemExit):
    print('You pressed ctrl+c')

I tried adding pass to except, but It doesn't give the expected output.

ppwater
  • 2,277
  • 4
  • 8
  • 25
  • Seems like this was answered here: https://stackoverflow.com/questions/6990474/how-can-i-override-the-keyboard-interrupt-python – Elisha Kupietzky Dec 06 '20 at 12:12
  • 2
    It does work, it's just that your try-catch is outside of your while loop, so the programme just ends (after your print). If you put the try-catch inside the while it would continue the loop – dpwr Dec 06 '20 at 12:12

2 Answers2

4

Move it inside the loop as I'm guessing you want to continue looping instead of exiting:

while True:
    try:
        userinput = input()
        if userinput == "stop":
            break
    except (KeyboardInterrupt, SystemExit):
        print('You pressed ctrl+c')
        # or just pass to print nothing
dpwr
  • 2,503
  • 1
  • 19
  • 36
  • Okay, thanks, but is there a way by *not* using try.. except? – ppwater Dec 06 '20 at 12:24
  • 1
    Yes, but you'll find it more complicated rather than less: https://stackoverflow.com/questions/4205317/capture-keyboardinterrupt-in-python-without-try-except Basically installing an interrupt handler. – dpwr Dec 06 '20 at 12:26
1

you can easily implement the next step within the try & except or set a pass after it.

while True:
    try:
        userinput = input()
        if userinput == "stop":
            break
    except (KeyboardInterrupt, SystemExit):
        # or edit it to the next state in the program.
        pass