python / python/cpython

Confusing error message when rename target is an open file

未关闭
#129,230 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib topic-pathlib type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Bug report

Bug description:

Background

Writing a tool to update and rename some files, I made a mistake and tried to rename a file while it was still open. This works on Linux, but raises an error when writing to a Windows network shares. This is known and documented - see Path.rename docs.

The issue

The problem I have is that the error message is incorrect. It says "FileNotFound", which is confusing because the files do exist. If I had got a more useful message, I would have worked out what the problem was with my tool much sooner.

Repro case

    file1 = Path("test1.txt")
    file2 = Path("test2.txt")
    file1.open("w").write("file 1 text\n")
    file2.open("w").write("file 2 text\n")
    with file1.open():
        file2.rename(file1)

Outcomes;
On linux, writing to pwd or a linux network share, file is rewritten without error.
On linux, writing to a Windows network share, an incorrect error message is given.

$ python test.py
Traceback (most recent call last):
  File "/home/jontwo/test.py", line 17, in <module>
    main()
  File "/home/jontwo/test.py", line 13, in main
    file2.rename(file1)
  File "/usr/lib/python3.12/pathlib.py", line 1363, in rename
    os.rename(self, target)
FileNotFoundError: [Errno 2] No such file or directory: 'test2.txt' -> 'test1.txt'

On Windows, writing to pwd, a useful error message is given.

c:\temp>python test.py
Traceback (most recent call last):
  File "c:\temp\test.py", line 16, in <module>
    main()
  File "c:\temp\test.py", line 12, in main
    file2.rename(file1)
  File "C:\OSGeo4W\apps\Python312\Lib\pathlib.py", line 1363, in rename
    os.rename(self, target)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'test2.txt' -> 'test1.txt'
CPython versions tested on:

3.12

Operating systems tested on:

Linux, Windows

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先,在 Linux 以及 Windows 网络共享条件下复现 issue 中所示的 pathlib.Path.rename 案例。检查所报告的 rename 入口点附近的 pathlib.py,并将产生的错误与文档记录的 Path.rename 行为进行比较。当目标处于打开状态的案例不再显示具有误导性的 FileNotFound 消息,并且平台特定行为已由适当的测试覆盖时,即视为完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
operating-systems
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。