小智..
41
Python有一个具有许多功能的键盘模块.安装它,也许使用此命令:
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
`keyboard`显然需要linux中的root:/ (36认同)
我不明白为什么try:except:会有用。 (6认同)
“为避免依赖X,Linux部件读取原始设备文件(/ dev / input / input *),但这需要root。” (2认同)
Mitrek..
24
对于那些在窗户上并且正在努力寻找工作答案的人来说,我的是:pynput
from pynput.keyboard import Key, Listener
def on_press(key):
print('{0} pressed'.format(
key))
def on_release(key):
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
return False
# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
上面的功能将打印您按下的任何键,并在释放'esc'键时启动操作.键盘文档在这里用于更多变化的用法.
在Linux中也可以使用,谢谢! (5认同)
@ nimig18 ...并且不需要root :) (2认同)
小智..
19
OP提到raw_input - 这意味着他想要cli解决方案.Linux:curses就是你想要的(windows PDCurses).Curses,是一个用于cli软件的图形API,您可以实现的不仅仅是检测关键事件.
此代码将检测键,直到按下新行.
import curses
import os
def main(win):
win.nodelay(True)
key=""
win.clear()
win.addstr("Detected key:")
while 1:
try:
key = win.getkey()
win.clear()
win.addstr("Detected key:")
win.addstr(str(key))
if key == os.linesep:
break
except Exception as e:
# No input
pass
curses.wrapper(main)
需要添加`import os`以便能够退出退出示例. (4认同)
Benjie..
11
对于Windows,您可以这样使用msvcrt:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print(key) # just to show the result
msvcrt是一个仅限Windows的模块. (7认同)
Black Thunde..
7
使用keyboard模块可以做更多的事情。
以下是一些方法:
方法1:
使用功能read_key():
import keyboard
while True:
if keyboard.read_key() == "p":
print("You pressed p")
break
p按下该键将打破循环。
方法2:
使用功能wait:
import keyboard
keyboard.wait("p")
print("You pressed p")
它将等待您按下p并继续按下代码。
方法3:
使用功能on_press_key:
import keyboard
keyboard.on_press_key("p", lambda _:print("You pressed p"))
它需要一个回调函数。我_之所以使用,是因为键盘功能将键盘事件返回到该功能。
一旦执行,当按下键时它将运行该功能。您可以通过运行以下行来停止所有挂钩:
keyboard.unhook_all()
方法4:
user8167727已经回答了这种方法,但是我不同意他们编写的代码。它将使用该函数,is_pressed但以另一种方式:
import keyboard
while True:
if keyboard.is_pressed("p"):
print("You pressed p")
break
p按下后将打破循环。
笔记:
keyboard 将从整个操作系统读取按键。
keyboard 在Linux上需要root
使用键盘模块最大的缺点是它要求您以ROOT用户身份运行。这使模块在我的代码中成为僵尸。仅轮询是否已按下键并不需要root特权。我已经阅读了文档并了解了为什么该限制会在模块中退出,但是如果您只需要轮询一个键,那么请查看其他地方... (3认同)
A.J. Uppal..
6
使用PyGame拥有一个窗口,然后您可以获取关键事件。
对于这封信p:
import pygame, sys
import pygame.locals
pygame.init()
BLACK = (0,0,0)
WIDTH = 1280
HEIGHT = 1024
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
windowSurface.fill(BLACK)
while True:
for event in pygame.event.get():
if event.key == pygame.K_p: # replace the 'p' to whatever key you wanted to be pressed
pass #Do what you want to here
if event.type == pygame.locals.QUIT:
pygame.quit()
sys.exit()
小智..
6
使用此代码查找按下了哪个键
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()