44

有没有办法在没有巨大臃肿模块的情况下在 python 中做关键监听器pygame

一个例子是,当我按下a键时,它会打印到控制台

a键被按下了!

它还应该监听箭头键/空格键/shift 键。

4

6 回答 6

47

我正在寻找一个没有窗口焦点的简单解决方案。Jayk 的回答pynput对我来说是完美的。这是我如何使用它的示例。

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys
于 2017-03-30T00:34:17.670 回答
28

不幸的是,要做到这一点并不容易。如果您正在尝试制作某种文本用户界面,您可能需要查看curses. 如果您想像通常在终端中那样显示内容,但又想要这样的输入,那么您将不得不使用termios,不幸的是,这似乎在 Python 中记录得很差。不幸的是,这些选项都不是那么简单。此外,它们不能在 Windows 下工作;如果您需要它们在 Windows 下工作,则必须使用PDCurses代替pywin32curses不是.termios


我能够让这个工作得体。它打印出您键入的键的十六进制表示。正如我在您问题的评论中所说,箭头很棘手;我想你会同意的。

#!/usr/bin/env python
import sys
import termios
import contextlib


@contextlib.contextmanager
def raw_mode(file):
    old_attrs = termios.tcgetattr(file.fileno())
    new_attrs = old_attrs[:]
    new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
    try:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
        yield
    finally:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)


def main():
    print 'exit with ^C or ^D'
    with raw_mode(sys.stdin):
        try:
            while True:
                ch = sys.stdin.read(1)
                if not ch or ch == chr(4):
                    break
                print '%02x' % ord(ch),
        except (KeyboardInterrupt, EOFError):
            pass


if __name__ == '__main__':
    main()
于 2012-08-12T01:39:43.790 回答
17

有一种方法可以在 python 中进行关键侦听器。此功能可通过pynput 获得

命令行:

$ pip install pynput

Python代码:

from pynput import keyboard
# your code here
于 2016-08-30T03:21:28.757 回答
16

以下是如何在 Windows 上执行此操作:

"""

    Display series of numbers in infinite loop
    Listen to key "s" to stop
    Only works on Windows because listening to keys
    is platform dependent

"""

# msvcrt is a windows specific native module
import msvcrt
import time

# asks whether a key has been acquired
def kbfunc():
    #this is boolean for whether the keyboard has bene hit
    x = msvcrt.kbhit()
    if x:
        #getch acquires the character encoded in binary ASCII
        ret = msvcrt.getch()
    else:
        ret = False
    return ret

#begin the counter
number = 1

#infinite loop
while True:

    #acquire the keyboard hit if exists
    x = kbfunc() 

    #if we got a keyboard hit
    if x != False and x.decode() == 's':
        #we got the key!
        #because x is a binary, we need to decode to string
        #use the decode() which is part of the binary object
        #by default, decodes via utf8
        #concatenation auto adds a space in between
        print ("STOPPING, KEY:", x.decode())
        #break loop
        break
    else:
        #prints the number
        print (number)
        #increment, there's no ++ in python
        number += 1
        #wait half a second
        time.sleep(0.5)
于 2014-04-16T03:08:24.580 回答
9

键盘

使用这个小型 Python 库完全控制您的键盘。挂钩全局事件、注册热键、模拟按键等等。

所有键盘上的全局事件挂钩(无论焦点如何都捕获键)。监听并发送键盘事件。适用于 Windows 和 Linux(需要 sudo),具有实验性 OS X 支持(感谢@glitchassassin!)。纯 Python,无需编译 C 模块。零依赖。安装和部署很简单,只需复制文件即可。Python 2 和 3。具有可控超时的复杂热键支持(例如 Ctrl+Shift+M、Ctrl+Space)。包括高级 API(例如录制和播放、add_abbreviation)。映射键,因为它们实际上在您的布局中,具有完整的国际化支持(例如 Ctrl+ç)。在单独的线程中自动捕获事件,不会阻塞主程序。测试并记录在案。不会破坏带重音的死键(我在看着你,pyHook)。通过项目鼠标(pip install mouse)提供鼠标支持。

README.md

import keyboard

keyboard.press_and_release('shift+s, space')

keyboard.write('The quick brown fox jumps over the lazy dog.')

# Press PAGE UP then PAGE DOWN to type "foobar".
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))

# Blocks until you press esc.
keyboard.wait('esc')

# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed.
keyboard.play(recorded, speed_factor=3)

# Type @@ then press space to replace with abbreviation.
keyboard.add_abbreviation('@@', 'my.long.email@example.com')
# Block forever.
keyboard.wait()
于 2017-10-28T20:03:28.967 回答
2

虽然我喜欢使用键盘模块来捕获键盘事件,但我不喜欢它的record()功能,因为它返回一个类似 的数组[KeyboardEvent("A"), KeyboardEvent("~")],我觉得它有点难以阅读。所以,为了记录键盘事件,我喜欢同时使用键盘模块和线程模块,像这样:

import keyboard
import string
from threading import *


# I can't find a complete list of keyboard keys, so this will have to do:
keys = list(string.ascii_lowercase)
"""
Optional code(extra keys):

keys.append("space_bar")
keys.append("backspace")
keys.append("shift")
keys.append("esc")
"""
def listen(key):
    while True:
        keyboard.wait(key)
        print("[+] Pressed",key)
threads = [Thread(target=listen, kwargs={"key":key}) for key in keys]
for thread in threads:
    thread.start()
于 2018-02-25T19:03:41.987 回答