0

I'm writing a program in Python 3.8. I'd like to make an input, let's say variable v. If v is input as "n," then some code is run. Any other input does nothing. Additionally, if the time runs out and nothing is inputted for v, then the "n" code is run.

I've tried a couple of different timers which work alright, but I'm struggling on how to cancel the input, since it stops my whole program and won't proceed onto the code I want to run.

Here's what I have:

def timerMethod():
    timeout = 10
    t = Timer(timeout, print, ['Sorry, times up'])
    t.start()
    prompt = "You have %d seconds to choose: are you feeling ok? y/n: \n" % timeout
    answer = input(prompt)
    if (answer == "n"):
        feelingBad = True
    t.cancel()

The two problems that I've encountered are 1. feelingBad (global variable) will never be made true. I feel like this is a basic Py principle that I've forgotten here, and I can change the way the code is written here, but if you'd like to point out my error please do. The main problem 2. is that if there is no input for the answer variable, the timer will end but the program will not proceed. If someone could please help me on the right track as on how to cancel the input prompt when the timer runs out, I'd greatly appreciate it.

  • Does this answer your question? [How can I stop the 'input()' function after a certain amount of time?](https://stackoverflow.com/questions/57828224/how-can-i-stop-the-input-function-after-a-certain-amount-of-time) – abhigyanj Jan 05 '21 at 01:17
  • @AbhigyanJaiswal Thanks, I was able to solve the problem using that thread. – fCode10 Jan 05 '21 at 02:52

2 Answers2

0

Check the multithreading here. I wish there was a better explanation on how it works. In my own words, one thread starts and sets the start time which is taken up by the second. Instead of a timer that counts down, it runs an if statement which compares the time taken with the time limit, which gives a space for any code to be run before the program exits.

-1

You can try this:

import time
from threading import Thread

user = None

def timeout():
    cpt = 0
    while user == None:
        time.sleep(1); cpt += 1
        if user != None:
            return
        if cpt == 10:
            break
    print("Pass")

Thread(target = timeout).start()

user = input()
Synthase
  • 5,849
  • 2
  • 12
  • 34
  • The timer here works great, however there needs to be an input for the program to continue. Thanks for the answer though – fCode10 Jan 05 '21 at 02:54
  • There is an input... This is the user var. Just use in down in the code and that's fine – Synthase Jan 05 '21 at 02:58