前言:因為嫌棄通過參數啟動過于繁瑣绳锅,并且對于需要進行分支選擇的情況不好處理西饵,想使用命令行按鍵菜單的形式給用戶做選擇,結果居然發(fā)現python沒有提供現成的API鳞芙,于是研究了一些解決方案眷柔。
方案一、pygame
這是百度出來的大多數答案原朝,個人不是很推薦驯嘱,首先pygame是用來做游戲的,提供了太多額外的功能喳坠,而不是單純的鍵盤響應鞠评,過于臃腫,好處是游戲庫的多平臺適配一定是沒問題的壕鹉,anyway剃幌,如果你還是要用的話,示例代碼如下:
import pygame
while True:
for event in pygame.event.get():
if event.type == pygame.KEY_DOWN:
if event.unicode == '':
print('#', event.key, event.mod)
else:
print(event.unicode, event.key.event.mod)
方案二晾浴、keyboard
參考stack overflow负乡,可以使用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
然而這個庫有個問題是linux系統(tǒng)下面需要root權限,為了確保多平臺穩(wěn)定性脊凰,我還是沒有用它抖棘,如果你確保程序是Windows環(huán)境下運行或者你的linux運行環(huán)境允許root那么keyboard庫是一個比較方便的選擇。
方案三、getkey
同參考stack overflow钉答,下面有人貼出了另一個庫:getkey,是對C原生getchar的封裝杈抢,在linux下不存在需要root權限的問題:
from getkey import getkey
while True: # Breaks when key is pressed
key = getkey()
print(key) # Optionally prints out the key.
然而這個庫有個問題数尿,在Windows下會報錯,因為它的getchars返回值在Windows下是bytes類型惶楼,而它的代碼里用了+=來進行字符串拼接右蹦,這會拋出類型不匹配的問題,該段代碼的本意應該是需要把bytes類型解碼的歼捐,所以你可以手動修改那段代碼:
...
def getkey(self, blocking=True):
buffer = ''
for c in self.getchars(blocking):
#下面兩行代碼是我手動添加的
if type(c) == bytes:
c = c.decode('utf-8')
buffer += c #就是這里報錯
if buffer not in self.keys.escapes:
break
...
如此何陆,getkey就可以在多平臺上正確運行了,如果不想動site package里面的代碼豹储,那么在Windows平臺使用keyboard贷盲,在linux使用getkey也是一個可行的方案。
除了以上三個module剥扣,還有很多第三方庫可以讀取鍵盤事件巩剖,大多是Windows下才能使用或者代碼不夠簡潔之類的,在此不多贅述钠怯。