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

yipeiwu_com6年前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程序运行效率的6个方法

Python是一个很酷的语言,因为你可以在很短的时间内利用很少的代码做很多事情。不仅如此,它还能轻松地支持多任务,比如多进程等。Python批评者有时会说Python执行缓慢。本文将尝试...

wxPython的安装与使用教程

wxPython的安装与使用教程

一、wxPython介绍     1.wxPython是Python语言的一套优秀的GUI图形库。wxPython可以很方便的创建完整的、功能键全的GUI用...

浅谈python实现Google翻译PDF,解决换行的问题

浅谈python实现Google翻译PDF,解决换行的问题

我们复制PDF到Google翻译时,总是会出现换行的情况,如果自己手动去除,那就太麻烦了。 那么用Python就可以解决,复制到粘贴板以后,Python程序自动可以把\n换成空格,然后...

Python编程实现的图片识别功能示例

本文实例讲述了Python编程实现的图片识别功能。分享给大家供大家参考,具体如下: 1. 安装PIL,官方没有WIN64位,Pillow替代 pip install Pillow-2.7...

Python xlwt设置excel单元格字体及格式

Python xlwt设置excel单元格字体及格式

本文根据自己初学经验编写的使用xlwt模块设置单元格的一些基本样式,如设置单元格的背景颜色,下框线,字体,字体的颜色,设置列宽行高,插入简单的图片,详细程序如下: #!/usr/bi...