python - python 的 shutil.copyfile() 是原子的吗?

标签 python linux shutil

我正在编写一个使用 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/

相关文章:

cx_Oracle 中的 Python 长时间空闲连接获取 : DPI-1080: connection was closed by ORA-3113

python - 血管图像处理问题

python - shutil.rmtree 在 Windows 上失败并显示 'Access is denied'

python - shutil.rmtree 可以抛出的异常的完整列表是什么

python - 将函数应用于 DataFrame 中的每个单元格

python - django - 将列表转换回查询集

python - 如何在python中获取linux系统变量

c - 读取客户端响应导致服务器崩溃

mysql - Windows 和 ubuntu 上的 SQL timeStamp 格式不同

尽管代码工作正常,Python 仍抛出错误