Search code examples
pythonpython-3.xkeyboardinterrupt

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?


Solution

  • 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.