我正在编写一个使用 shutil.copyfile() 复制文件的 Python 脚本在 Linux 上。在复制过程中,其他进程可能正在尝试读取该文件。以下是否足以确保外部进程不会获得损坏的文件 View ?
os.unlink(dest)
shutil.copyfile(src, dest)
也就是说,shutil.copyfile() 是原子的,以至于在复制操作完成之前其他进程无法读取目标文件吗?
最佳答案
不,shutil.copyfile
不是原子的。这是 definition of shutil.copyfile
: 的一部分
def copyfile(src, dst, *, follow_symlinks=True):
...
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
哪里copyfileobj
is defined like this :
def copyfileobj(fsrc, fdst, length=16*1024):
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
调用copyfile
的线程可以在此while-loop
中停止,此时一些其他进程可能会尝试打开要读取的文件。它会得到损坏的文件 View 。
关于python - python 的 shutil.copyfile() 是原子的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20873723/