原子文件写入。
atomicwrites的Python项目详细描述
原子文件写入。
fromatomicwritesimportatomic_writewithatomic_write('foo.txt',overwrite=True)asf:f.write('Hello world.')# "foo.txt" doesn't exist yet.# Now it does.
区别于其他类似库的特性(请参见Alternatives and Credit):
Windows支持,尽管没有经过很好的测试。MSDN资源不是很丰富 明确哪些操作是原子的我的假设是基于a comment 作者是Doug Crook,他出现了 成为微软员工:
FAQ: Is MoveFileEx atomic Frequently asked question: Is MoveFileEx atomic if the existing and new files are both on the same drive?
The simple answer is “usually, but in some cases it will silently fall-back to a non-atomic method, so don’t count on it”.
The implementation of MoveFileEx looks something like this: […]
The problem is if the rename fails, you might end up with a CopyFile, which is definitely not atomic.
If you really need atomic-or-nothing, you can try calling NtSetInformationFile, which is unsupported but is much more likely to be atomic.
跨平台的一致错误处理
工作原理
它使用与给定路径在同一目录中的临时文件这确保了 临时文件位于同一个文件系统上。
然后,临时文件将自动移动到目标位置:on posix将使用rename如果文件应该被覆盖,否则 link和unlink的组合。在windows上,它使用MoveFileEx到 stdlib的ctypes带有适当的标志。
注意,对于link和unlink,有一个时间窗口 可能在文件系统中的两个条目下可用: 临时文件,以及目标文件的名称。
还要注意,目标文件的权限可能会这样更改。在一些 可以在没有任何并发问题的情况下发出chmod,但是 因为情况并非总是这样,所以这个库并不是自己做的。
fsync
在posix上,fsync在临时文件被写入(到 刷新文件内容和元数据),并在文件 移动(刷新文件名)。
fsync不处理磁盘的内部缓冲区,但似乎没有 成为任何标准的posixapi。在os x上,fcntl与 F_FULLFSYNC而不是fsync因为这个原因。
在Windows上,_commit 已使用,但无法保证磁盘内部缓冲区。
替代品和信用
AtomicWrites直接受到以下库的启发(并共享 最小代码量):
- TRAC项目的utility functions, 也用于Werkzeug和 mitsuhiko/python-atomicfile使用的想法 ctypes而不是PyWin32起源于此。
- abarnert/fatomic。窗口支持 (基于PyWin32)最初是从那里获得的。
原子写入的其他替代方案包括:
- sashka/atomicfile。原来我 考虑过使用它,但当时它缺少很多特性 需要(Windows支持,覆盖参数,通过 子类化)。
- 那Boltons library collection 提供了一个用于原子文件写入的类,它看起来与 overwrite参数。但它缺少windows支持。
许可证
根据麻省理工学院授权,请参见LICENSE。