Reputation: 2277
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.
Upvotes: 0
Views: 563
Reputation: 23
CTRL-C actually means send SIGINT signal to the progress, so you can just handle this signal by your own function.
import signal
import sys
def signal_handler(signal, frame):
print("You pressed Ctrl+C - or killed me with -2")
# sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print("Press Ctrl+C")
signal.pause()
Upvotes: 0
Reputation: 31
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
Upvotes: 1
Reputation: 2812
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
Upvotes: 4