raw_input
这样的方法,因为它会在继续执行之前等待用户的输入。有人知道如何在while循环中实现这个功能吗?
我希望能够在多个平台上运行,但如果不可能的话,我的主要开发目标是Linux。
raw_input
这样的方法,因为它会在继续执行之前等待用户的输入。Python有一个名为keyboard的模块,具有许多功能。可以使用以下命令安装它:
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
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()
from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be
#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
if current_window == desired_window_name:
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
pip install pynput
命令,它安装了 某些东西,但是当我运行你的代码时,出现了这个错误:No connection could be made because the target machine actively refused it
。 - john k使用keyboard
模块可以做更多的事情。您可以使用pip install keyboard
安装此模块。以下是一些方法:
使用函数read_key()
:
import keyboard
while True:
if keyboard.read_key() == "p":
print("You pressed p")
break
当按下键盘上的 p 键时,将会打破循环。
使用函数wait
:
import keyboard
keyboard.wait("p")
print("You pressed p")
它将等待您按p键,一旦按下继续执行代码。
使用函数on_press_key
:
import keyboard
keyboard.on_press_key("p", lambda _:print("You pressed p"))
它需要一个回调函数。我使用了 _
,因为键盘函数将键盘事件返回到该函数。
执行后,当按下键时,它将运行该函数。您可以通过运行此行来停止所有挂钩:
keyboard.unhook_all()
这种方法与user8167727已经提供的答案类似,但我不同意他们的代码。这将使用函数is_pressed
,但使用另一种方式:
import keyboard
while True:
if keyboard.is_pressed("p"):
print("You pressed p")
break
按下 p 键时,它将打破循环。
你也可以使用keyboard.record
。 它记录所有按下和释放的按键,直到您按下escape
键或在until
参数中定义的键,并返回一个包含keyboard.KeyboardEvent
元素列表。
import keyboard
keyboard.record(until="p")
print("You pressed p")
注意:
keyboard
将从整个操作系统读取按键记录。keyboard
在Linux上需要root权限。keyboard.wait()
等待多个按键,如果其中任何一个被按下,则继续执行。 - Preetkaran Singhkeyboard.read_key()
中使用suppress
关键字的用法,以及何时使用和何时不使用它... - Preetkaran Singhinput
组中,因此您只需要将用户添加到附加组即可。 - Patrick B.正如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
才能够退出示例。 - maltewin.nodelay(False)
代替True
,它就不会每秒产生一百万个异常。 - Johannes Hoff对于 Windows,您可以像这样使用 msvcrt
:
import msvcrt
while True:
if msvcrt.kbhit():
key = msvcrt.getch()
print(key) # just to show the result
使用此代码以查找按下的键
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()
neoDev在问题本身的评论可能很容易被忽略,但它链接到的解决方案在这里的任何答案中都没有提到。
使用此解决方案无需导入keyboard
。
解决方案从另一个问题中复制,所有功劳归@neoDev。
这对我在macOS Sierra和Python 2.7.10和3.6.3上都有效。
import sys,tty,os,termios
def getkey():
old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
try:
while True:
b = os.read(sys.stdin.fileno(), 3).decode()
if len(b) == 3:
k = ord(b[2])
else:
k = ord(b)
key_mapping = {
127: 'backspace',
10: 'return',
32: 'space',
9: 'tab',
27: 'esc',
65: 'up',
66: 'down',
67: 'right',
68: 'left'
}
return key_mapping.get(k, chr(k))
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
try:
while True:
k = getkey()
if k == 'esc':
quit()
else:
print(k)
except (KeyboardInterrupt, SystemExit):
os.system('stty sane')
print('stopping.')
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()
非root版本,可通过ssh运行:sshkeyboard。使用pip install sshkeyboard
进行安装,
然后编写以下脚本:
from sshkeyboard import listen_keyboard
def press(key):
print(f"'{key}' pressed")
def release(key):
print(f"'{key}' released")
listen_keyboard(
on_press=press,
on_release=release,
)
输出结果为:
'a' pressed
'a' released
A
键时,默认情况下,按下 ESC
键将结束监听。我基于这篇文章制作了一个游戏(使用msvcr库和Python 3.7)。
以下是游戏的主要功能,即检测按键:
import msvcrt
def _secret_key(self):
# Get the key pressed by the user and check if he/she wins.
bk = chr(10) + "-"*25 + chr(10)
while True:
print(bk + "Press any key(s)" + bk)
#asks the user to type any key(s)
kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
# Store key's value.
if r'\xe0' in kp:
kp += str(msvcrt.getch()).replace("b'", "").replace("'", "")
# Refactor the variable in case of multi press.
if kp == r'\xe0\x8a':
# If user pressed the secret key, the game ends.
# \x8a is CTRL+F12, that's the secret key.
print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk)
print("Press any key to exit the game")
msvcrt.getch()
break
else:
print(" You pressed:'", kp + "', that's not the secret key(s)\n")
if self.select_continue() == "n":
if self.secondary_options():
self._main_menu()
break