代码之家  ›  专栏  ›  技术社区  ›  nos

如何使用pytest tmpdir.as\u cwd获取临时路径

  •  1
  • nos  · 技术社区  · 7 年前

    在python测试函数中

    def test_something(tmpdir):
        with tmpdir.as_cwd() as p:
            print('here', p)
            print(os.getcwd())
    

    我在期待 p os.getcwd() 会得到同样的结果。但实际上, 指向测试文件的目录 os.getcwd() 指向所需的临时文件。

    1 回复  |  直到 7 年前
        1
  •  4
  •   hoefling    7 年前

    看看你的文件 py.path.as_cwd :

    返回上下文管理器,它在托管“with”上下文中更改为当前目录。在 __enter__

    因此,你观察到的行为是正确的:

    def test_something(tmpdir):
        print('current directory where you are before changing it:', os.getcwd())
        # the current directory will be changed now
        with tmpdir.as_cwd() as old_dir:
            print('old directory where you were before:', old_dir)
            print('current directory where you are now:', os.getcwd())
        print('you now returned to the old current dir', os.getcwd())
    

    记住这一点 p 在您的示例中,不是您要更改到的“新”当前目录,而是您从中更改的“旧”目录。

        2
  •  0
  •   DobromirM    7 年前

    From the documentation:

    您可以使用tmpdir装置,它将提供一个临时的 目录。

    鉴于, getcwd