【英文】Python3监测按键按下

Preface

Detecting key press in Python3

Terminating the program when a key is pressed

Installing dependencies

1
pip3 install pynput

Detecting the ESC key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import threading
from pynput import keyboard

isEnd = False

# Function to execute when a key is pressed, using try and except because of special keys (function keys)
def keyboard_on_press(key):
global isEnd
try:
print(f'Letter key {key.char} pressed')
except AttributeError:
print(f'Special key {key}')
if key == keyboard.Key.esc:
isEnd = True
return False


# Interrupted program
def function():
# Infinite loop of the main program
while True:
pass


def main():
global isEnd
# Create keyboard listening thread
listener = keyboard.Listener(on_press=keyboard_on_press)
listener.daemon = 1

# Create main program thread
t = threading.Thread(target=function)
t.daemon = 1

# Start keyboard listening thread
listener.start()
# Start main program thread
t.start()

while True:
if isEnd:
return


if __name__ == "__main__":
main()

Executing the program when a key is pressed

Detecting the ESC key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import keyboard


# Program to execute when a key is pressed
def function():
pass


def main():
keyboard.add_hotkey("esc", function)
keyboard.wait()


if __name__ == "__main__":
main()

Pitfalls

  • Error: OSError: Error 13 - Must be run as administrator

Solution

  • Run the program as an administrator

<filename>: Python file name

1
sudo python3 <filename>.py

Completion

References

CSDN——广大菜鸟
CSDN——IT技术学习