【问题标题】:How to get the temporary path using pytest tmpdir.as_cwd如何使用 pytest tmpdir.as_cwd 获取临时路径
【发布时间】:2019-04-12 20:16:23
【问题描述】:
在python测试函数中
def test_something(tmpdir):
with tmpdir.as_cwd() as p:
print('here', p)
print(os.getcwd())
我期待 p 和 os.getcwd() 会给出相同的结果。但实际上,p 指向测试文件的目录,而os.getcwd() 指向预期的临时文件。
这是预期的行为吗?
【问题讨论】:
标签:
python
pytest
temporary-directory
【解决方案1】:
看看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】:
From the documentation:
您可以使用 tmpdir 固定装置,它会提供一个临时的
测试调用唯一的目录,在基础临时目录中创建
目录。
而getcwd 代表获取当前工作目录,并返回您的 python 进程已启动的目录。