栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

线程安全和容错文件写入

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线程安全和容错文件写入

您可以使用Python的

tempfile
模块为您提供一个临时文件名。它可以以线程安全的方式创建一个临时文件,而不是使用一个临时文件(
time.time()
如果同时在多个线程中使用该文件可能返回相同的名称)。

正如对您的问题的评论中所建议的那样,这可以与上下文管理器一起使用。通过查看Python

tempfile.py
源代码,您可以得到一些有关如何实现想要执行的操作的想法。

下面的代码段可能会做您想要的。它使用从返回的对象的某些内部

tempfile

  • 创建临时文件是线程安全的。
  • 成功完成文件重命名是原子的,至少在Linux上是如此。没有之间的单独检查
    os.path.exists()
    os.rename()
    可能引入竞争状态。对于Linux上的原子重命名,源和目标必须位于同一文件系统上,这就是为什么此代码将临时文件与目标文件放置在同一目录中的原因。
  • 在大多数情况下,
    RenamedTemporaryFile
    该类的行为应类似于a
    NamedTemporaryFile
    ,除非使用上下文管理器关闭该类时,文件会重命名。

样品:

import tempfileimport osclass RenamedTemporaryFile(object):    """    A temporary file object which will be renamed to the specified    path on exit.    """    def __init__(self, final_path, **kwargs):        tmpfile_dir = kwargs.pop('dir', None)        # Put temporary file in the same directory as the location for the        # final file so that an atomic move into place can occur.        if tmpfile_dir is None: tmpfile_dir = os.path.dirname(final_path)        self.tmpfile = tempfile.NamedTemporaryFile(dir=tmpfile_dir, **kwargs)        self.final_path = final_path    def __getattr__(self, attr):        """        Delegate attribute access to the underlying temporary file object.        """        return getattr(self.tmpfile, attr)    def __enter__(self):        self.tmpfile.__enter__()        return self    def __exit__(self, exc_type, exc_val, exc_tb):        if exc_type is None: self.tmpfile.delete = False result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb) os.rename(self.tmpfile.name, self.final_path)        else: result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb)        return result

然后可以像这样使用它:

with RenamedTemporaryFile('whatever') as f:    f.write('stuff')

在写入过程中,内容进入一个临时文件,退出时该文件被重命名。这段代码可能需要进行一些调整,但是总体思路应该可以帮助您入门。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号