繁体   English   中英

如何通过超时通过if语句提问

[英]How to ask Question by if statement via timeout

有没有什么办法可以通过if语句来问问题,并且在几秒钟后如果用户没有给出任何答案,状态是否使用默认答案?

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

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

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

在这种情况下,如果用户默认情况下在30秒后不给出任何答案,则选择语句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是Thread的子类,因此也可以作为创建自定义线程的示例。

与线程一样,计时器通过调用其start()方法来启动。 可以通过调用cancel()方法来停止计时器(在其动作开始之前)。 计时器在执行其操作之前将等待的时间间隔可能与用户指定的时间间隔不完全相同。

例如:

 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)

在间隔秒过去之后,创建一个计时器,该计时器将使用参数args和关键字参数kwargs运行函数。 如果args为None(默认值),则将使用一个空列表。 如果kwargs为None(默认值),则将使用空dict。

取消()

停止计时器,并取消执行计时器的操作。 仅当计时器仍处于等待阶段时,此功能才起作用。

这是使用多重处理的另一种方法(python 3)。 请注意,要使stdin在子进程中正常工作,必须先重新打开它。 我还将输入从字符串转换为int以便与多处理值一起使用,因此您可能还想在那里进行错误检查。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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