Python 中的文件处理:正在被另一个进程使用

File handling in Python: being used by another process

好吧,我制作了这个脚本,它支持记录一些击键一段时间,将它们保存在一个文件中,然后如果用户想要删除文件,但是当脚本试图删除文件时,我得到了这个错误。

Traceback (most recent call last):File "C:\Users\Tormentor\Desktop\S.D.A.K.L\pregunta.py", line 34, in os.remove(path2+"\"+name) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:'C:\Users\Public\myfile.txt'

我做了一些研究,我认为它无法删除,因为我的 "snp" 函数从不关闭记录击键的文件,所以我如何关闭文件以删除它? 感谢您的帮助:).

import os
import time
import pyHook, pythoncom, sys, logging

path="C:\Users\Public\myfile.txt"

path2="C:\Users\Public"

name="myfile.txt"

TinM=10

def snp(event):    #<---------- Not closing file ???
    global path
    logging.basicConfig(filename=path, level=logging.DEBUG, format='%(message)s')
    chr(event.Ascii)
    logging.log(10,chr(event.Ascii))
    return True


timeout=time.time()+TinM
while timeout > time.time():
    hooks_manager = pyHook.HookManager()
    hooks_manager.KeyDown = snp
    hooks_manager.HookKeyboard()
    print("Logging keystrokes")
    pythoncom.PumpWaitingMessages()
else:
    hooks_manager.UnhookKeyboard()
    x=input("Keylogger stoped do you want to delete the archive? y / n")
    if x == "y":
        for(path2,dirs,files) in os.walk(path2):
            if name in files:
                os.remove(path2+"\"+name) # <----- This line triggers the error.
                print("Archive deleted. Goodbye")
            else:
                print("Archive does not exist or cant be found goodbye! :D")
    else:
        print("Goodbye! :D")

您自己的进程正在打开该文件。

logging.basicConfig(filename=path, level=logging.DEBUG...

打开 filename 指定的文件。在进程退出或调用 logging.shutdown() 之前它不会关闭它,因此您可以在 snp() 函数中调用 shutdown()

但是,这需要在每次按下按键时都初始化日志记录,这是非常低效的。更好的设计是在脚本的主要部分调用一次 logging.basicConfig() ,然后在删除文件之前调用 logging.shutdown()。您的 snp() 函数将变为:

def snp(event):
    logging.log(logging.DEBUG, chr(event.Ascii))
    return True

和脚本的主要部分:

logging.basicConfig(filename=path, level=logging.DEBUG, format='%(message)s')
timeout=time.time()+TinM
while timeout > time.time():
    hooks_manager = pyHook.HookManager()
    hooks_manager.KeyDown = snp
    hooks_manager.HookKeyboard()
    print("Logging keystrokes")
    pythoncom.PumpWaitingMessages

hooks_manager.UnhookKeyboard()
logging.shutdown()
x=input("Keylogger stoped do you want to delete the archive? y / n")
if x == "y":
    for(path2,dirs,files) in os.walk(path2):
        if name in files:
            os.remove(path2+"\"+name) # <----- This line triggers the error.
            print("Archive deleted. Goodbye")
        else:
            print("Archive does not exist or cant be found goodbye! :D")
else:
    print("Goodbye! :D")

请注意,我还从 while 语句中删除了 else 子句,因为它始终针对您显示的代码执行。