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设计】。

相关文章

matplotlib.pyplot画图并导出保存的实例

我就废话不多说了,直接上代码吧! import pandas as pd import numpy as np import matplotlib.pyplot as plt fig...

python 转换 Javascript %u 字符串为python unicode的代码

web采集的数据为 %u6B63%u5F0F%u4EBA%u5458,需要读取并转换为python对象,想了下不调用Javascript去eval,只能自己翻译了。 核心代码: i...

基于python的selenium两种文件上传操作实现详解

基于python的selenium两种文件上传操作实现详解

方法一、input标签上传 如果是input标签,可以直接输入路径,那么可以直接调用send_keys输入路径,这里不做过多赘述,前文有相关操作方法。 方法二、非input标签上传 这种...

Django之无名分组和有名分组的实现

Django之无名分组和有名分组的实现

在Django 2.0版本之前,在urls,py文件中,用url设定视图函数 urlpatterns = [ url(r'login/',views.login), ] 其...

pandas 空的dataframe 插入列名的示例

如下所示: colum = ['性别','年龄','M','样本类型'] + muta_list + ['B'] data1 = pd.DataFrame(columns=colum...