用Python检测按键(非msvcrt)

0 投票
2 回答
1059 浏览
提问于 2025-04-18 17:11

我在找一个可以检测键盘事件的Python模块。现在我知道有一个叫msvct的模块,但它只适用于在控制台中按键。我需要创建一个被动的程序,能够监控键盘,但我找不到方法。

谢谢你的帮助。

2 个回答

1

你可以试试这段代码

sudo apt-get install python-xlib

Log.py

import os
import pyxhook

# This tells the keylogger where the log file will go.
# You can set the file path as an environment variable ('pylogger_file'),
# or use the default ~/Desktop/file.log
log_file = os.environ.get(
    'pylogger_file',
    os.path.expanduser('~/Desktop/file.log')
)
# Allow setting the cancel key from environment args, Default: `
cancel_key = ord(
    os.environ.get(
        'pylogger_cancel',
        '`'
    )[0]
)

# Allow clearing the log file on start, if pylogger_clean is defined.
if os.environ.get('pylogger_clean', None) is not None:
    try:
        os.remove(log_file)
    except EnvironmentError:
       # File does not exist, or no permissions.
        pass

#creating key pressing event and saving it into log file
def OnKeyPress(event):
    with open(log_file, 'a') as f:
        f.write('{}\n'.format(event.Key))

# create a hook manager object
new_hook = pyxhook.HookManager()
new_hook.KeyDown = OnKeyPress
# set the hook
new_hook.HookKeyboard()
try:
    new_hook.start()         # start the hook
except KeyboardInterrupt:
    # User cancelled from command line.
    pass
except Exception as ex:
    # Write exceptions to the log file, for analysis later.
    msg = 'Error while catching events:\n  {}'.format(ex)
    pyxhook.print_err(msg)
    with open(log_file, 'a') as f:
        f.write('\n{}'.format(msg))

这个键盘记录器会把你按下的每一个键都记录下来。

1

Python 有一个叫做 keyboard 的模块,它有很多功能。你可以在 ShellConsole 中使用它。这个模块还能监测整个 Windows 系统的按键。
你可以用下面的命令来安装它:

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('a'): #if key 'a' is pressed 
            print('You Pressed A Key!')
            break #finishing the loop
        else:
            pass
    except:
        break  #if user pressed other than the given key the loop will break

你还可以设置它来检测多个按键:

if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'):  # and so on
    #then do this

撰写回答