problem printing a string within except? Program just ends instead of printing statement

Viewed 41

The program isn't printing what I want ("too slow") after the except with the KeyboardInterrupt, which should end the program and print the string, instead the program just ends. I tried messing around with it a bit but can't seem to figure it out. What should I do?

import os
import signal
import threading
from random import randint

def timed_input(interval, *args):
    t = threading.Timer(interval, os.kill, args=(os.getpid(), signal.SIGINT))    
    t.start()
    try:
        return int(input(*args))
    except:
        pass
    finally:
        t.cancel()

while True:
    want = randint(1,9)
    try:
        got = timed_input(5, f'type "{want}": ')
    except KeyboardInterrupt:
        print('too slow')
    else:
        if got != want:
            print('You Lose.')
            break

1 Answers

This is because your first function is removing the KeyboardInterrupt thus making the second try block useless.

To fix this add another except block for the first function so it is properly raised:

import os
import signal
import threading
from random import randint

def timed_input(interval, *args):
    t = threading.Timer(interval, os.kill, args=(os.getpid(), signal.SIGINT))    
    t.start()
    try:
        return int(input(*args))
    except KeyboardInterrupt:
        raise
    except ValueError:
        pass
    finally:
        t.cancel()

while True:
    want = randint(1,9)
    try:
        got = timed_input(5, f'type "{want}": ')
    except KeyboardInterrupt:
        print('too slow')
    else:
        if got != want:
            print('You Lose.')
            break
Related