gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:25 24 4
gpt4 key购买 nike

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

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 的条款语句,因为它总是针对您显示的代码执行。

关于python - Python 中的文件处理 : being used by another process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com