如何通过timeou通过if语句提问

2024-09-29 12:24:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如果用户没有给出任何答案,在几秒钟后,如果州政府使用默认答案,是否有任何方式通过if语句提问

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

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

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

在这种情况下,如果用户在30秒后没有给出任何答案,默认情况下,if语句选择3


Tags: or答案用户closeinputif方式music
2条回答

下面是另一种方法(python3),使用多处理。注意,要使stdin在子进程中工作,必须首先重新打开它。我还将输入从string转换为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)
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.

相关问题 更多 >