python zipfile 线程安全吗? [英] Is python zipfile thread-safe?

查看:36
本文介绍了python zipfile 线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django项目中,我需要为db中的对象生成一些pdf文件.由于每个文件的生成需要几秒钟的时间,所以我使用 celery 异步运行任务.

In a django project, I need to generate some pdf files for objects in db. Since each file takes a few seconds to generate, I use celery to run tasks asynchronously.

问题是,我需要将每个文件添加到 zip 存档中.本来打算用python的zipfile模块,但是不同的任务可以在不同的线程中运行,我想知道如果两个任务同时尝试将一个文件添加到存档中会发生什么.

Problem is, I need to add each file to a zip archive. I was planning to use the python zipfile module, but different tasks can be run in different threads, and I wonder what will happen if two tasks try to add a file to the archive at the same time.

以下代码线程安全吗?我在 python 的官方文档中找不到任何有价值的信息.

Is the following code thread safe or not? I cannot find any valuable information in the python's official doc.

try:
    zippath = os.path.join(pdf_directory, 'archive.zip')
    zipfile = ZipFile(zippath, 'a')
    zipfile.write(pdf_fullname)
finally:
    zipfile.close()

注意:这是在python 2.6下运行

Note: this is running under python 2.6

推荐答案

不,从这个意义上说它不是线程安全的.如果您要附加到同一个 zip 文件,则需要在那里锁定,否则文件内容可能会被打乱.如果您要附加到不同的 zip 文件,使用单独的 ZipFile() 对象,那就没问题了.

No, it is not thread-safe in that sense. If you're appending to the same zip file, you'd need a lock there, or the file contents could get scrambled. If you're appending to different zip files, using separate ZipFile() objects, then you're fine.

这篇关于python zipfile 线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆