Skip to main content
 首页 » 编程设计

python之如何使用 pytest tmpdir.as_cwd 获取临时路径

2024年11月24日7bonelee

在 python 测试函数中

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

我原以为 p 和 os.getcwd() 会给出相同的结果。但实际上,p 指向测试文件的目录,而 os.getcwd() 指向预期的临时文件。

这是预期的行为吗?

请您参考如下方法:

查看 py.path.as_cwd 的文档:

return context manager which changes to current dir during the managed "with" context. On __enter__ it returns the old dir.

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

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 不是您要更改到的"new"当前目录,而是您更改的“旧”目录。