简体   繁体   中英

How to give the user certain amount of time to answer and print a message as soon as the time expires? (Python)

I have tried to use multi-threading for limiting the input time for the user, but this code doesn't seem to work.

# giving the user less than 5 seconds to enter a number

import time
from threading import Thread


def ask():
    start_time = time.time()
    a = float(input("Enter a number:\n"))
    time.sleep(0.001)


def timing():
    if time.time() - start_time > 5: 
        print("Time's Up")
        quit()
    time.sleep(0.001)


t1 = Thread(target=ask)
t2 = Thread(target=timing)
t1.start()
t2.start()
t1.join()
t2.join()

You need to put timing function in infinite mode. Bcz it's running only one time.

Try below code:

import time
import os
from threading import Thread

start_time = time.time()
a = None

def ask():
    global start_time
    start_time = time.time()
    global a
    a = float(input("Enter a number:\n"))
    time.sleep(0.001)


def timing():
    while True:
        global a
        if a is not None:
            break
        if time.time() - start_time > 5: 
            print("Time's Up")
            os._exit(1)
        time.sleep(0.001)


t1 = Thread(target=ask)
t2 = Thread(target=timing)
t1.start()
t2.start()
t1.join()
t2.join()

I don't like global variables but the following piece of code seems to work well for your need:

import time
from threading import Thread
import sys

start_time = 0
timeUp = False

def ask():
    global start_time, timeUp
    start_time = time.time()
    a = float(input("Enter a number:\n"))
    time.sleep(0.001)
    if a and (not timeUp):
        print('This is a: ', a)

def timing():
    global timeUp
    while True:
        if time.time() - start_time > 5: 
            print("Time's Up")
            timeUp = True
            sys.exit()
        time.sleep(0.001)


t1 = Thread(target=ask)
t2 = Thread(target=timing)
t1.start()
t2.start()
t1.join()
t2.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM