【问题标题】:Can't delete file after using Pool() multiprocessing functionality in python在 python 中使用 Pool() 多处理功能后无法删除文件
【发布时间】:2022-06-21 22:24:40
【问题描述】:

我正在使用 python 多处理功能来并行处理大型栅格数据集。一切似乎都很好。处理完成后,我需要自动删除所有并行进程创建的所有文件。但是,这失败并出现以下错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'xxxxxxxx.tif'

这是我正在使用的代码:

def my_function_1(info):
    ...

def my_function_2(...):
    ...

delete_func():
    ...

info = {}
info = .... #I populate a dict with the parameters I want to send to the function
pool = Pool(processes=16)
pool.map(my_function_1, info.items())
pool.close()
pool.join()  

my_function_2(...)    #Processing files created during the multiprocessing

delete_func()         #Delete files created during the multiprocessing

当调用 delete_func() 时,它开始删除在多处理期间创建的所有文件(数百个),但在某些时候它会抛出上述错误。似乎某些进程正在/仍在保留一个或一些文件。如何确保所有进程都已关闭并且所有文件都“免费”可以删除?

【问题讨论】:

  • 如果没有minimal reproducible example,真的没有办法提供帮助。您甚至没有提供完整的错误消息...问题几乎可以肯定是您未提供的功能的详细信息(我怀疑my_function_2)。
  • 另外,这不应该在 Windows 上工作,因为你没有用 pool.map 保护你的调用 if __name__ == "__main__": 保护...这应该会创建一个多处理炸弹。
  • 整个代码大约600行。 my_function_2 唯一要做的就是将在多处理过程中创建的所有 tif 文件合并到一个唯一的大 tif 文件中。合并发生后,我不再需要马赛克的所有瓷砖,只想删除它们。 “多处理炸弹”是什么意思?

标签: python multiprocessing pool


【解决方案1】:

您可以通过更改这些行来实现:

pool = Pool(processes=16)
pool.map(my_function_1, info.items())
pool.close()
pool.join()  

到这里

with Pool(16) as pool:
   pool.map(my_function_1, info.items())

如果您使用此代码,它将在所有进程停止后执行程序的其余部分

如果您写入文件,请使用此代码

with open("path_to_your_file","the_mode_you_want") as file:
   file.write("text")
   #or do what ever you want with the file   

使用 with 格式会导致这种情况,例如当您想要访问文件时。如果不再使用,文件会自动关闭

【讨论】:

  • 在发布此问题之前,我实际上已经尝试过您的建议。不幸的是,我得到了完全相同的错误。
【解决方案2】:

@Pitrako Junior
您是否同时解决了这个问题?我遇到了同样的问题,但没有找到任何有用的提示来解决它。 感谢您的帮助:-)

【讨论】:

猜你喜欢
  • 2022-08-24
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多