RossC RossC - 4 months ago 18
Python Question

Disabling KeyboardInterrupt after it has been used once

Cont = 1
while Cont == 1:
while Cont == 1:
counter = counter + 0.1
counter = round(counter, 1)
if counter == crashNumber:
Cont = 0
except KeyboardInterrupt:
Multiplier = counter

Here the counter will continue to count up unitl it reaches the
, when Ctrl + C is pressed, it will take the number that the
is at and use it for the
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?


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:
        print ('...')
    except KeyboardInterrupt:
        if allow_interrupt:
            print ('interrupted!')
            allow_interrupt = False

Let me know if this addresses your use case.