我正在尝试删除一个临时文件夹,在该文件夹中保存图像并对其进行一些处理,然后返回一些结果。我使用了shutil.rmtree(filepath)
,它在Mac OS上可以正常工作。但是,当我在Windows服务器上运行它时,它失败并显示一条错误,指出文件仍在使用中。
我在堆栈溢出How to clean up temporary file used with send_file?上提到了这个问题
This answer使用弱引用有助于消除Windows上引发的错误,但仍不会删除该文件夹。尽管它仍然可以在Mac OS上正常工作。
在Windows系统上完成请求后,如何删除临时文件夹?
这是我的代码段供您参考。
def post(self):
try:
if 'photo' not in request.files:
raise NoFilesError
file = request.files['photo']
print('file = ', file)
if file.filename == '':
raise NoFilesError
if file and self._allowed_file(file.filename):
filename = secure_filename(file.filename)
dir_path = os.path.join(BaseAPIConfig.UPLOAD_FOLDER, get_timestamp())
create_directory(dir_path)
file_path = os.path.join(dir_path, filename)
file.save(file_path)
img_proc_main(dir_path, filename)
image_filename = filename.rsplit('.', 1)[0]
image_format = filename.rsplit('.', 1)[1]
result_file = os.path.join(dir_path, image_filename + '_bb.' + image_format)
response = make_response(send_file(result_file))
file_remover = FileRemover()
file_remover.cleanup_once_done(response, dir_path)
return response
...
FileRemover类
class FileRemover(object):
def __init__(self):
self.weak_references = dict() # weak_ref -> filepath to remove
def cleanup_once_done(self, response, filepath):
wr = weakref.ref(response, self._do_cleanup)
self.weak_references[wr] = filepath
def _do_cleanup(self, wr):
filepath = self.weak_references[wr]
print('Deleting %s' % filepath)
shutil.rmtree(filepath, ignore_errors=True)
答案 0 :(得分:0)
您正在使用ignore_errors=True
,它隐藏了shutil.rmtree
遇到的任何异常。
shutil.rmtree
可能无法删除目录的原因很多,也许您只是在Windows上没有正确的权限。将ignore_errors
设置为false可以为您提供更多提示。