【问题标题】:How can I stop the 'input()' function after a certain amount of time?如何在一定时间后停止“输入()”功能?
【发布时间】:2019-09-06 20:29:21
【问题描述】:

我正在尝试弄清楚如何让 python 在一段时间后停止接受输入。

到目前为止,我所做的工作有效,但在用户按下 Enter 之前不会停止程序。如果重要的话,我会在 Anaconda 提示符下运行这个文件。

#I've made everything short so it's simpler
def f():
    try:
        if a != "Accepted word":
            timer.cancel
            print("...")
            quit()

    except NameError:
            #This makes the code run anyway since if the user inputs nothing 
            #'a' will still be undefined and python will still be waiting for an input
            timer.cancel
            print("...")
            if a == "":
            quit()
            #Like I said, Python won't actually stop until an input is made
    else:
        #This runs fine if the user inputs the 'accepted word'
        timer.cancel
        print(...)
        quit()
timer = threading.Timer(5.0, f)
timer.start()
a = input(">")

换句话说,我想做一些事情,让 Python 停止等待输入。如果用户在计时器结束之前输入任何内容,程序运行良好,这很好,除非玩家什么都不输入。如果他们甚至不按 Enter,那么整个过程就会停止。 (我也是 Python 的绝对初学者。事实上,仅仅学习如何制作计时器和使用 time.sleep 函数就花了我几个小时)(顺便说一下,这也是我的知识范围)

【问题讨论】:

  • Python 3 Timed Input 的可能重复项。查看投票率最高的答案(不是接受的答案)的第一部分(“如果可以接受阻止主线程......”)。
  • @iz_ 该代码基本上复制了我已有的。诚然,它比我写的要好,但只要时间到了,我仍然需要按 Enter 键来结束程序。
  • 对于初学者来说,timer.cancel 是一个方法,应该用timer.cancel() 调用。

标签: python python-3.x


【解决方案1】:

您可以为此使用多线程。

from threading import Thread
import time
import os

answer = None


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


def timing():
    time_limit = 5
    while True:
        time_taken = time.time() - start_time
        if answer is not None:
            print(f"You took {time_taken} seconds to enter a number.")
            os._exit(1)
        if time_taken > time_limit:
            print("Time's up !!! \n"
                  f"You took {time_taken} seconds.")
            os._exit(1)
        time.sleep(0.001)


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

【讨论】:

  • 欢迎来到 Stack Overflow!虽然这段代码可以解决问题,including an explanation 解决问题的方式和原因确实有助于提高帖子的质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的答案添加解释并说明适用的限制和假设。
【解决方案2】:

只需在另一个进程中输入并在一段时间后终止该进程。

import time, multiprocessing
def takeinput():
    stdin = open(0)
    print("give it up:", end = "", flush = 1)
    x = stdin.readline()
    print(x)
if __name__ == "__main__":
    process = multiprocessing.Process(target = takeinput)
    process.start()
    time.sleep(5)
    process.terminate()
    process.join()
    print("\nalright, times up!")

希望这会有所帮助:D

【讨论】:

    【解决方案3】:

    只需使用time.sleep() sleep 方法会导致 python 程序冻结一段时间(以毫秒为单位)。 所以,如果你想在一定时间内停止input(),那么你可以这样做,

    from time import sleep
    sleep(1000) #stops the program for 1 seconds
    s = input()
    

    sauce

    【讨论】:

    • 它会阻止 python 运行代码,但这只会延迟时间,直到输入被处理。如果我将“quit()”放在“s = input()”的正下方,那么程序可以无限期地保持打开状态。如果我解释得不好,我想要一行代码来关闭程序,无论用户是否输入任何内容。
    猜你喜欢
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多