繁体   English   中英

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

[英]File handling in Python: being used by another process

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

回溯(最近一次调用最后一次):文件“C:\\Users\\Tormentor\\Desktop\\SDAKL\\pregunta.py”,第 34 行,在 os.remove(path2+"\\"+name) PermissionError: [WinError 32] The process cannot访问该文件,因为它正被另一个进程使用:'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指定的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子句,因为它始终针对您显示的代码执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM