简体   繁体   中英

How to ask Question by if statement via timeout

is there any way for ask question by if statement and after afew sec if user didnot give any answer , if state use a default answer?

inp = input("change music(1) or close the app(2)")

if inp = '1':
    print("Music changed)

elif inp = '2':
    print("good by")

in this case if user dont give any answer after 30 sec by default if statement choose number 3

from threading import Timer

out_of_time = False

def time_ran_out():
    print ('You didn\'t answer in time') # Default answer
    out_of_time = True

seconds = 5 # waiting time in seconds
t = Timer(seconds,time_ran_out)
t.start()
inp = input("change music(1) or close the app(2):\n")

if inp != None and not out_of_time:
     if inp == '1':
          print("Music changed")
     elif inp == '2':
          print("good by")
     else:
          print ("Wrong input")
     t.cancel()

Timer Objects

This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.

Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method. The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user.

For example:

 def hello(): print("hello, world") t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed 

class threading.Timer(interval, function, args=None, kwargs=None)

Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used.

cancel()

Stop the timer, and cancel the execution of the timer's action. This will only work if the timer is still in its waiting stage.

Here's an alternative way to do it (python 3), using multiprocessing. Note, to get the stdin to work in the child process, you have to re open it first. I'm also converting the input from string to int to use with the multiprocessing value, so you might want to error check there as well.

import multiprocessing as mp
import time
import sys
import os


TIMEOUT = 10
DEFAULT = 3


def get_input(resp: mp.Value, fn):
    sys.stdin = os.fdopen(fn)
    v = input('change music(1) or close the app (2)')
    try:
        resp.value = int(v)
    except ValueError:
        pass # bad input, maybe print error message, try again in loop.
        # could also use another mp.Value to signal main to restart the timer


if __name__ == '__main__':

    now = time.time()
    end = now + TIMEOUT

    inp = 0
    resp = mp.Value('i', 0)
    fn = sys.stdin.fileno()
    p = mp.Process(name='Get Input', target=get_input, args=(resp, fn))
    p.start()

    while True:
        t = end - time.time()
        print('Checking for timeout: Time = {:.2f}, Resp = {}'.format(t, resp.value))

        if t <= 0:
            print('Timeout occurred')
            p.terminate()
            inp = DEFAULT
            break
        elif resp.value > 0:
            print('Response received:', resp.value)
            inp = resp.value
            break
        else:
            time.sleep(1)

    print()
    if inp == 1:
        print('Music Changed')
    elif inp == 2:
        print('Good Bye')
    else:
        print('Other value:', inp)

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