我需要帮助来理解 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/