Chinaunix

标题: 请教如何设置raw_input的等待时间? [打印本页]

作者: 风中有只鸟    时间: 2012-04-04 07:37
标题: 请教如何设置raw_input的等待时间?
例如设置多少秒没有输入就自动跳过
作者: anonymous0502    时间: 2012-04-04 09:40
本帖最后由 anonymous0502 于 2012-04-04 09:40 编辑

这有个别人写的例子,我试了能运行:
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import time
  5. import msvcrt


  6. def readInput(caption, default, timeout=5):
  7.     start_time = time.time()
  8.     sys.stdout.write('%s(%s):' % (caption, default))
  9.     input = ''
  10.     while True:
  11.         if msvcrt.kbhit():
  12.             chr = msvcrt.getche()
  13.             if ord(chr) == 13:  # enter_key
  14.                 break
  15.             elif ord(chr) >= 32:

  16.                                  # space_char

  17.                 input += chr
  18.         if len(input) == 0 and time.time() - start_time > timeout:
  19.             break

  20.     print ''  # needed to move to next line
  21.     if len(input) > 0:
  22.         return input
  23.     else:
  24.         return default


  25. # and some examples of usage

  26. ans = readInput('Please type a name', 'john')
  27. print 'The name is %s' % ans
  28. ans = readInput('Please enter a number', 10)
  29. print 'The number is %s' % ans
复制代码

作者: 风中有只鸟    时间: 2012-04-04 12:09
上面的代码测试成功,不过不太明白代码的含义

尝试改为easygui.enterbox("Enter Code: "),却不成功
作者: anonymous0502    时间: 2012-04-04 13:08
没有用过easygui,不太清楚了。
作者: 风中有只鸟    时间: 2012-04-04 20:24
多谢,继续折腾看看
作者: 5iwww    时间: 2012-04-10 06:50
   if len(input) == 0 and time.time() - start_time > timeout:

            break

关键就是这一句




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2