【问题标题】:Key press and wait for a fixed amount of time按键并等待固定的时间
【发布时间】:2014-07-16 12:45:09
【问题描述】:

我想让一个 python 程序在每个循环周期等待 1'' (不必是实时的,所以我对 time.sleep(1) 的准确性很好)之后我想知道一个键被按下了,如果是的话,是哪一个。

我在这里找到了解决方案Python wait x secs for a key and continue execution if not pressed,但这不完全是我的问题。因为当按钮被按下时,我仍然想等待第二秒的剩余时间。

操作系统:Win 7 - 但最好是跨平台(至少对于 ubuntu)

我确实尝试过msvcrt,但这对我来说似乎相当笨拙,我想知道是否不存在任何更直接的方法。当然我不是第一个遇到这个问题的人。

【问题讨论】:

  • @wastl 添加了一些信息
  • @magu_ 我的回答对你有用还是你在寻找不同的东西?

标签: python input time


【解决方案1】:

这是一个使用线程的简单示例。

import threading
import time

# define a thread which takes input
class InputThread(threading.Thread):
    def __init__(self):            
        threading.Thread.__init__(self)
        self.user_input = None

    def run(self):
        self.user_input = input('input something: ')

    def get_user_input(self):
        return self.user_input

# main
it = InputThread()
it.start()
while True:
    print('\nsleeping 1s and waiting for input... ')
    time.sleep(1)
    ui = it.get_user_input()
    if ui != None:
        print('The user input was', ui)
        it = InputThread()
        it.start()

【讨论】:

  • 正是我正在寻找的东西,除了我使用 msvcrt.getch() 不需要回车。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 2015-07-27
相关资源
最近更新 更多