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模块结构与布局操作方法实例分析

本文实例讲述了Python模块结构与布局操作方法。分享给大家供大家参考,具体如下: #coding=utf8 #起始行 #!/usr/bin/env python #模块文档 '''...

python 把数据 json格式输出的实例代码

有个要求需要在python的标准输出时候显示json格式数据,如果缩进显示查看数据效果会很好,这里使用json的包会有很多操作 import json date = {u'ver...

使用Python的Twisted框架编写简单的网络客户端

Protocol   和服务器一样,也是通过该类来实现。先看一个简短的例程: from twisted.internet.protocol import Protocol...

python实现文件分组复制到不同目录的例子

场景:某个文件夹下面包含数量巨大的文件,需求需要将这些文件按组(比如5000个一组)存放到不同的目录中去。 复制代码 代码如下:# Filename: CopyFiles.pyimpor...

Python3 循环语句(for、while、break、range等)

Python3 循环语句(for、while、break、range等)

本章节将为大家介绍Python循环语句的使用。 Python中的循环语句有 for 和 while。 Python循环语句的控制结构图如下所示: while 循环 Python中whi...