0

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()
1
  • The input() function is blocking. It halts your program in place. None of the other statements are evaluated until the function returns. This is why your current setup won't work. unfortunately i can't point you in a direction that does work. That's a few levels above my paygrade. Commented Oct 9, 2019 at 11:18

1 Answer 1

1

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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.