简体   繁体   English

如何在一定时间后停止“input()”function?

[英]How can I stop the 'input()' function after a certain amount of time?

I'm trying to figure out how to make python stop accepting input after a certain amount of time.我想弄清楚如何让 python 在一定时间后停止接受输入。

What I've got so far works, but won't stop the program until the user presses Enter.到目前为止,我所做的一切都有效,但在用户按下 Enter 之前不会停止程序。 If it matters, I'm running this file in the Anaconda prompt.如果重要,我将在 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(">")

To put it in different words, I want to make something so that Python will stop waiting for an input.换句话说,我想做一些事情,让 Python 停止等待输入。 If the user inputs anything before the timer ends, the program runs fine, which is great, unless the player inputs nothing.如果用户在计时器结束之前输入任何内容,程序运行良好,这很好,除非玩家什么都不输入。 If they don't even press Enter, then the whole process halts.如果他们甚至不按 Enter,那么整个过程就会停止。 (I'm also an absolute beginner in Python. In fact, just learning how to make a timer and use the time.sleep function took me a couple hours)(Which is also, by the way, the extent of my knowledge) (我也是 Python 的绝对初学者。事实上,仅仅学习如何制作计时器和使用 time.sleep function 就花了我几个小时)(顺便说一句,这也是我的知识范围)

You could use Multi-threading for this.您可以为此使用多线程。

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()

Just take the input in another process and after some time terminate the process.只需在另一个进程中输入,并在一段时间后终止该进程。

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!")

Hope this helps:D希望这有帮助:D

just use time.sleep() The sleep method causes a python program to freeze for certain amount of time (in milliseconds).只需使用time.sleep() sleep 方法会导致 python 程序冻结一定时间(以毫秒为单位)。 So, if you want to stop input() for a certain amount of time then you can do it this way,所以,如果你想停止input()一段时间,那么你可以这样做,

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

sauce

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

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