din*_*aur 10 python linux shutil
我正在编写一个python脚本,它在Linux上使用shutil.copyfile()复制文件.在复制过程中,其他进程可能正在尝试读取该文件.以下内容是否足以确保外部进程不会损坏文件?
os.unlink(dest)
shutil.copyfile(src, dest)
Run Code Online (Sandbox Code Playgroud)
也就是说,是shutil.copyfile()原子,以便其他进程在复制操作完成之前无法读取目标文件?
不,shutil.copyfile不是原子的。这是定义的一部分:shutil.copyfile
def copyfile(src, dst, *, follow_symlinks=True):
...
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
Run Code Online (Sandbox Code Playgroud)
def copyfileobj(fsrc, fdst, length=16*1024):
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
Run Code Online (Sandbox Code Playgroud)
线程调用copyfile可以在这个内部停止while-loop,此时其他一些进程可以尝试打开要读取的文件。它将获得损坏的文件视图。
| 归档时间: |
|
| 查看次数: |
1587 次 |
| 最近记录: |