如何检测按键?

问题描述:

我正在用 Python 制作一个秒表类型的程序,我想知道如何检测某个键是否被按下(例如 p 表示暂停,s 表示停止),我不希望它像 raw_input 这样的东西,它在继续执行之前等待用户的输入.

I am making a stopwatch type program in Python and I would like to know how to detect if a key is pressed (such as p for pause and s for stop), and I would not like it to be something like raw_input, which waits for the user's input before continuing execution.

有人知道如何在 while 循环中执行此操作吗?

Anyone know how to do this in a while loop?

我想让这个跨平台,但如果这不可能,那么我的主要开发目标是 Linux.

I would like to make this cross-platform but, if that is not possible, then my main development target is Linux.

Python 有一个 keyboard 模块具有许多功能.安装它,也许使用以下命令:

Python has a keyboard module with many features. Install it, perhaps with this command:

pip3 install keyboard

然后在代码中使用它:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break