python 异步读取键盘/标准输入

jv4diomz  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(156)

我有一个循环,在这个循环中我想做一些事情,直到一个键被按下。有没有一种方法可以从另一个线程的stdin中读取输入,直到一个特定的键被按下?有没有更好的方法可以做到这一点?

def capture_loop(dev_path, breakout_key="a"):
    captured_devs = []
    capture = True

    def wait_for_key():
        global capture
        while True:
           i, o, e = select.select([sys.stdin], [], [], 10)
            if len(i) > 0:
            input_string = i[0].read()
                if breakout_key in str(input_string):
                    capture = False
                    break
            else:
                print("You said nothing!")

    t = threading.Thread(target=wait_for_key)
    t.setDaemon(False)
    t.start()

    while capture:
        print("Doing Stuff until the 'a' key is pressed")
        time.sleep(10)
    print("Done doing stuff")
ru9i0ody

ru9i0ody1#

如果您只想在按下某个组合键之前执行某项操作,但并不关心 * 使用什么组合键 *,则可以捕获KeyboardInterrupt异常,该异常在按control-C时引发:

try:
        while True:
            print("Doing something until C-c is pressed...")
            time.sleep(1)
    except KeyboardInterrupt:
        print("Done!")

相关问题