# 信号

# 如何响应键盘事件?

import signal

is_sigint_up = False

def sigint_handler(signum, frame):
  global is_sigint_up
  is_sigint_up = True
  print ('Interrupted!')

signal.signal(signal.SIGINT, sigint_handler)

while True:
    if is_sigint_up == True:
        break
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 如何定时中断?

import signal

# Define signal handler function
def myHandler(signum, frame):
    print("Now, it's the time")
    exit()
    
 # register signal.SIGALRM's handler 
signal.signal(signal.SIGALRM, myHandler)
signal.alarm(5)
while True:
    print('not yet')
1
2
3
4
5
6
7
8
9
10
11
12

# 如何检测哪个键被按下?

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
        else:
            pass
    except:
        break  # if user pressed a key other than the given key the loop will break
1
2
3
4
5
6
7
8
9
10

# 如何检查方向键是否被按下?

import readchar

while True:
    keypress = readchar.readkey()
    if keypress == readchar.key.UP:
        print("UP")
    elif keypress == readchar.key.DOWN:
        print("DOWN")
    elif keypress == readchar.key.LEFT:
        print("LEFT")
    elif keypress == readchar.key.RIGHT:
        print("RIGHT")
    elif keypress in (readchar.key.CR, readchar.key.CTRL_C):
        break
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 如何使用Opencv读取按键?

import cv2 

img = cv2.imread('directions.png')
cv2.imshow('img',img)
while True:
    key = cv2.waitKey(-1)
    print(key)
1
2
3
4
5
6
7

使用本地任意一张图代替directions.png即可。

上次更新: 1/30/2020, 12:32:41 PM