Joe Wilson
Joe Wilson

Reputation: 77

Problems interrupting a python Input (Mac)

I am trying to allow a user to input multiple answers but only within an allocated amount of time. The problem is I have it running but the program will not interrupt the input. The program will only stop the user from inputing if the user inputs an answer after the time ends. Any ideas? Is what I am trying to do even possible in python?

I have tried using threading and the signal module however they both result in the same issue.

Using Signal:

    import signal

    def handler(signum, frame):
        raise Exception

    def answer_loop():
        score = 0
        while True:
            answer = input("Please input your answer")

    signal.signal(signal.SIGALRM, handler)
    signal.alarm(5)
    try:
        answer_loop()
    except Exception:
        print("end")

    signal.alarm(0)

Using Threading:

    from threading import Timer

    def end():
        print("Time is up")

    def answer_loop():
        score = 0
        while True:
            answer = input("Please input your answer")

    time_limit =  5
    t = Timer(time_limit, end)
    t.start()
    answer_loop()
    t.cancel()

Upvotes: 0

Views: 101

Answers (1)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19174

Your problem is that builtin input does not have a timeout parameter and, AFAIK, threads cannot be terminated by other threads. I suggest instead that you use a GUI with events to finely control user interaction. Here is a bare bones tkinter example.

import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text='answer')
entry = tk.Entry(root)
label.pack()
entry.pack()

def timesup():
    ans = entry.get()
    entry.destroy()
    label['text'] = f"Time is up.  You answered {ans}"

root.after(5000, timesup)

root.mainloop()

Upvotes: 1

Related Questions