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

标签 python pytest temporary-directory

在 python 测试函数中

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

我原以为 pos.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"当前目录,而是您更改的“旧”目录。

关于python - 如何使用 pytest tmpdir.as_cwd 获取临时路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55658866/

相关文章:

c# - 专门在 C# 中获取系统 TEMP 路径

python - 过滤后无法迭代列表

javascript - 将简单的 Perl 脚本翻译成 Python 以向客户端发送响应?

python - OpenCV BFMatcher match() 总是返回错误

python - 找到在opencv(python)中设置的白色像素的边界框

python - 在 pytest 中参数化并运行单个测试

python - pytest收集了0个项目

c - 创建临时目录的可靠方法

python - PyTest-Django 因缺少 django_migration 表而失败

java - Junit 4.11 TemporaryFolder 构造函数与 java.io.File