Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling KeyboardInterrupt after it has been used once

Cont = 1
while Cont == 1:
    try:
        while Cont == 1:
            counter = counter + 0.1
            counter = round(counter, 1)
            print(counter)
            time.sleep(0.1)
            if counter == crashNumber:
                Cont = 0
    except KeyboardInterrupt:
        Multiplier = counter

Here the counter will continue to count up unitl it reaches the crashNumber, when Ctrl + C is pressed, it will take the number that the counter is at and use it for the Multiplier to be used later.

However I only want to give the user the chance to press this once, then it is disabled. Is there any way that this can be done?

like image 577
RossC Avatar asked Dec 06 '25 08:12

RossC


1 Answers

The KeyboardInterrupt exception will be thrown whether you want it or not: the solution, then, is to deal with the exception in different ways in your except block. My chosen implementation will use a simple boolean value that starts as True and is set to False on the first interruption:

import time

allow_interrupt = True
while True:
    try:
        time.sleep(1)
        print ('...')
    except KeyboardInterrupt:
        if allow_interrupt:
            print ('interrupted!')
            allow_interrupt = False

Let me know if this addresses your use case.

like image 65
brianpck Avatar answered Dec 08 '25 20:12

brianpck