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

Python 如何使用pytest tmpdir.as_cwd获取临时路径,python,pytest,temporary-directory,Python,Pytest,Temporary Directory,在python测试函数中 def test_something(tmpdir): with tmpdir.as_cwd() as p: print('here', p) print(os.getcwd()) 我希望p和os.getcwd()会给出相同的结果。但实际上,p指向测试文件的目录,而os.getcwd()指向预期的临时文件 这是预期的行为吗? 您可以使用tmpdir装置,该装置将提供临时 测试调用的唯一目录,在基本临时目录中创建 目录 然而,ge

在python测试函数中

def test_something(tmpdir):
    with tmpdir.as_cwd() as p:
        print('here', p)
        print(os.getcwd())
我希望
p
os.getcwd()
会给出相同的结果。但实际上,
p
指向测试文件的目录,而
os.getcwd()
指向预期的临时文件

这是预期的行为吗?

您可以使用tmpdir装置,该装置将提供临时 测试调用的唯一目录,在基本临时目录中创建 目录


然而,
getcwd
代表获取当前工作目录,并返回启动python进程的目录。

查看以下文档:

返回上下文管理器,该管理器在托管“with”上下文期间更改为当前目录。在
\uuuu上输入\uuuu
返回旧目录

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

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

您可以显示传递给function@DobromirM这是一个固定装置: