python 获取键盘输入,同时有超时的功能示例

yipeiwu_com5年前Python基础

如下所示:

'''
###get keyboard input and timeout =5

import sys, time, msvcrt

def readInput( caption, default, timeout = 5):
 start_time = time.time()
 sys.stdout.write('%s(%s):'%(caption, default));
 input = ''
 while True:
  if msvcrt.kbhit():
   chr = msvcrt.getche()
   if ord(chr) == 13: # enter_key
    break
   elif ord(chr) >= 32: #space_char
    input += chr
  if len(input) == 0 and (time.time() - start_time) > timeout:
   break

 print '' # needed to move to next line
 if len(input) > 0:
  return input
 else:
  return default
  
readInput("TEst1",10)

'''

###catch keyboard input, if key == ESC, stop 

import sys, time, msvcrt

def readKeyBoardInput(timeout = 5):
 start_time = time.time()
 sys.stdout.write("If you want to stop test process,please click ESC button");
 input = ''
 while True:
  if msvcrt.kbhit():
   chr = msvcrt.getche()
   if ord(chr) == 27: # ESC
    return True
  if len(input) == 0 and (time.time() - start_time) > timeout:
   return False

以上这篇python 获取键盘输入,同时有超时的功能示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中os模块详解

os模块提供了对目录或者文件的新建/删除/查看文件属性,还提供了对文件以及目录的路径操作。比如说:绝对路径,父目录…… os.sep可以取代操作系统特定的路径分隔符。windows下为...

Python中elasticsearch插入和更新数据的实现方法

Python中elasticsearch插入和更新数据的实现方法

    首先,我的索引结构是酱紫的。          存储以name_id为主键的索引,待插...

Python多线程结合队列下载百度音乐的方法

本文实例讲述了Python多线程结合队列下载百度音乐的方法。分享给大家供大家参考。具体如下: 一直想做个下载音乐的脚本,后来决定就拿百度音乐开刀,经过多次分析,终于制作了一个下载百度音乐...

python读写ini配置文件方法实例分析

本文实例讲述了python读写ini配置文件方法。分享给大家供大家参考。具体实现方法如下: import ConfigParser import os class ReadWrite...

python将list转为matrix的方法

如下所示: import numpy as np tmp = [[1,2,3],[4,5,6],[7,8,9]]; np.matrix(tmp) 以上这篇python将list转...