使用pynput.Listener和keylogger监听特定的键? [英] Listening to specific keys with pynput.Listener and keylogger?
问题描述
我下面有以下python脚本:
I have the following python script below:
但是我想监听",或者如果足够的话,只需将以下键记录"到我的log.txt中:Key.left和Key.up.我该如何造成这种限制?
But I want to "listen" or, if it's enough, just "record" to my log.txt, the following keys: Key.left and Key.up. How can I cause this restriction?
此问题相似,但她的回复的代码结构有些相似有所不同,并且需要进行重大更改以允许键盘记录程序和Listener
上的此限制.
This question is similar but the code structures of her responses are somewhat different and would require a major change to allow the keylogger and this restriction on the Listener
.
还有另外一个问题对我来说,可能是寻找解决方法的灵感之源.
And this other question seems to me to be a potential source of inspiration for finding a method of solution.
我花了一些时间寻找一个可以给我这个答案或可以帮助我思考的问题,但找不到,但是如果已经发布了一个问题,请告诉我!
I spent some time looking for a question that would give me this answer or help me to reflect on it but I couldn't find it but if there is a question already published please let me know!
#in pynput, import keyboard Listener method
from pynput.keyboard import Listener
#set log file location
logFile = "/home/diego/log.txt"
def writeLog(key):
'''
This function will be responsible for receiving the key pressed.
via Listener and write to log file
'''
#convert the keystroke to string
keydata = str(key)
#open log file in append mode
with open(logFile, "a") as f:
f.write(keydata)
#open the Keyboard Listener and listen for the on_press event
#when the on_press event occurs call the writeLog function
with Listener(on_press=writeLog) as l:
l.join()
推荐答案
您可以从pynput.keyboard
导入Key
模块并检查击键的类型.
You can import Key
module from pynput.keyboard
and check for the type of key-strokes.
#in pynput, import keyboard Listener method
from pynput.keyboard import Listener, Key
#set log file location
logFile = "/home/diego/log.txt"
def writeLog(key):
'''
This function will be responsible for receiving the key pressed.
via Listener and write to log file
'''
if(key == Key.left or key == Key.up):
#convert the keystroke to string
keydata = str(key)
#open log file in append mode
with open(logFile, "a") as f:
f.write(keydata)
#open the Keyboard Listener and listen for the on_press event
#when the on_press event occurs call the writeLog function
with Listener(on_press=writeLog) as l:
l.join()
这篇关于使用pynput.Listener和keylogger监听特定的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!