Skip to main content
 首页 » 编程设计

python之Python 中的文件处理 : being used by another process

2025年05月04日33dflying

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

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()被调用,所以你可以调用 shutdown()在你的snp()功能。

但是,这需要在每次按下按键时都初始化日志记录,这是非常低效的。更好的设计是调用 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") 

请注意,我还删除了 else来自 while 的条款语句,因为它总是针对您显示的代码执行。