python-3.x - 为什么使用关键字 "with"调用 tempfile.TemporaryDirectory() 时,它的返回类型会发生变化?

标签 python-3.x temporary-files

我需要帮助来理解 tempfile.TemporaryDirectory() 的返回类型。

import tempfile

temp_dir = tempfile.TemporaryDirectory()
print(type(temp_dir)) # It yields: <class 'tempfile.TemporaryDirectory'>

with tempfile.TemporaryDirectory() as temp_dir:
    print(type(temp_dir)) # It yields: <class 'str'>

正如我们所看到的,当使用关键字“with”调用 tempfile.TemporaryDirectory() 时,它的返回类型发生了变化。有人可以向我解释一下为什么吗?

作为比较,当使用关键字“with”或不使用关键字“with”调用 subprocess.Popen() 时,其返回类型不会改变。这是预期的行为。

import subprocess

cmd="ls -l"
response = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(type(response)) # It yields: <class 'subprocess.Popen'>

with subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as response:
    print(type(response)) # It yields: <class 'subprocess.Popen'>

最佳答案

当你使用with语句时,它实际上调用了__enter__方法,所以它与赋值不同。在 with 内的代码完成后,它还会调用 __exit__

当您在 with 语句中使用 TemporaryDirectory 时,它会在离开 with 语句后自动处理目录删除,因此您无需担心那。但是当你像这样使用它时

temp_dir = tempfile.TemporaryDirectory()

然后它不知道何时删除该目录,您必须自己执行此操作 - 因此它为您提供该目录的句柄而不是仅路径。

关于python-3.x - 为什么使用关键字 "with"调用 tempfile.TemporaryDirectory() 时,它的返回类型会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75248614/

相关文章:

python - 如何在打印之前对 JSON float 据进行排序

python - 提高 MigrationSchemaMissing ("Unable to create the django_migrations table (%s)"% exc)

python - 使用 FUSE 在 python 中创建一个临时文件

python 临时文件 + gzip + json 转储

postgresql - 为什么postgresql在磁盘空间足够的情况下提示错误 'perhaps out of disk space'?

python - 更新 Python 2.x->3.x 时对 Unicode 字符串行为进行故障排除

Python - 打印存在于 2 个文件中的字符串

python - 在 Python 中创建临时文件,该文件将在一段时间后自动删除

java - renameTo() 在 eclipse Helios 中不起作用

python-3.x - 如何修复 TypeError : G must be a 'd' matrix?