【问题标题】:Why are we still stuck on this function despite threading?为什么尽管有线程,我们仍然停留在这个函数上?
【发布时间】:2017-06-11 16:30:32
【问题描述】:

我想创建一个等待输入的函数,如果 2 秒内没有任何输入,则跳过输入并继续该函数的其余部分。

我从另一个线程尝试了这个功能:

import time
from threading import Thread

answer = None

def check():
    time.sleep(2)
    if answer != None:
        return "ayy"
    print("Too slow")
    return "No input"

Thread(target = check).start()

answer = input("Input something: ")
print(answer)

此代码要求输入,如果 2 秒内未添加任何输入,则会打印“太慢”。但是它永远不会继续打印(答案),我认为它一直在等待用户输入。

我想询问用户输入,如果需要的时间太长,它只需要 input = None 并转到它下面的函数。我查看了涉及信号的超时方法,但这仅适用于 linux 和 windows 上的 im。

【问题讨论】:

    标签: multithreading python-3.x


    【解决方案1】:

    你的假设是正确的。 input() 调用正在等待用户提交在您的情况下永远不会发生的任何输入。

    一个跨平台的解决方案是使用select():

    import sys
    import select
    
    def timed_input(prompt, timeout=10):
        """
        Wait ``timeout`` seconds for user input
    
        Returns a tuple:
            [0] -> Flag if timeout occured
            [1] -> User input
        """
        sys.stdout.write(prompt)
        sys.stdout.flush()
    
        input, output, error = select.select([sys.stdin], [], [], 2)
    
        if input:
            return True, sys.stdin.readline().strip()
        else:
            return False, None
    
    timed_input('Input something: ', timeout=2)
    

    这是一个肮脏的原型。我建议对超时使用异常或更直观的函数返回值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 2023-03-26
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 1970-01-01
      相关资源
      最近更新 更多