python等待用户输入并超时退出

在python中需要等待用户输入,并在等待超时后之后直接结束等待。

使用系统的input函数可以等待,但是无法超时,于是想出一个超时结束的法子:

使用一个线程来执行input,并将线程join到主线程实现超时,当超时之后,模拟键盘输入enter键,令input得到一个退出信号而结束。

参考代码如下:

#encoding: utf-8

import threading
from pykeyboard import *

def thread_entry(userInput:str, waitSec:int=3):
    userInput['input'] = input(f'请在 {waitSec} 秒内完成信息输入并回车\n :) ')

def run():
    userInput = {'input': None} # 默认为空
    waitSec = 10
    t = threading.Thread(target=thread_entry, args=(userInput, waitSec))
    t.start()
    t.join(waitSec)

    if userInput['input'] is None or 0 == len(userInput['input']):
        k = PyKeyboard()
        k.tap_key(k.enter_key)
        print("超时。使用默认值。")
    else:
        print(f"你的输入为“{userInput['input']}”")

if __name__=="__main__":
    run()

  

测试结果:

 

 由于开辟了一个新的线程,利用 PyKeyboard 模拟输入按键之后,可以稍微等待一会儿确保等待用户输入的线程结束之后再处理后续逻辑。

这不是必须的,但是还是建议给个几十上百毫秒的等待。我这里是特意死等直到线程结束。

import time
# ...

    if userInput['input'] is None or 0 == len(userInput['input']):
        k = PyKeyboard()
        k.tap_key(k.enter_key)

        while t.is_alive(): # 睡眠一会儿等待input线程结束
            print("线程尚未退出!")
            time.sleep(0.2)

        print("超时。使用默认值。")

    else:

        print(f"你的输入为“{userInput['input']}”")

# ...

 

 

 

依赖的包:

  1. pykeyboard 可参考Python模拟鼠标键盘:pykeyboard库的使用_小白华的博客-CSDN博客_pykeyboard
  2. threading

 

posted @ 2022-05-03 23:01  -ssdq-  阅读(3617)  评论(1编辑  收藏  举报