【问题标题】:Detect keypress with python (not msvct)用python检测按键(不是msvct)
【发布时间】:2014-10-07 06:22:00
【问题描述】:

我正在寻找一个可以让我检测键盘事件的 python 模块。现在我知道这个模块 msvct,但它只适用于在控制台中完成的按键操作。我需要创建一个可以挂接到键盘的被动程序,但我找不到方法..

感谢您的帮助

【问题讨论】:

  • 你可以使用tkinterpyqt这样的模块
  • 试过 Tkinter。但它与 msvct 相同,用户需要在程序中才能检测到按键。
  • 我没有测试过,但你可能会发现this Python keylogger很有用。

标签: python key keypress


【解决方案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

可以设置为多个Key Detection:

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

【讨论】:

    【解决方案2】:

    你甚至可以试试这个代码

    sudo apt-get install python-xlib
    

    日志.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))
    

    此键盘记录器将附加您按下的每个键。

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2013-08-17
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2015-07-09
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多