我正在Python中创建一个类,其中一个方法需要处理文件并将它们保存在临时目录中。该方法完成后,临时目录将被删除。我需要临时目录可供整个脚本使用,而不仅仅是方法。
import tempfile
import os
class sandbox:
def start_tmp_dir():
temp_dir = tempfile.TemporaryDirectory()
print('tmp dir available in start_tmp_dir: ' + str(os.path.isdir(temp_dir.name)))
return temp_dir.name
def use_tmp_dir(dir_name):
print('tmp dir available in use_tmp_dir: ' + str(os.path.isdir(dir_name)))
if __name__ == "__main__":
sandbox = sandbox
dir_name = sandbox.start_tmp_dir()
sandbox.use_tmp_dir(dir_name)
输出:
tmp dir available in start_tmp_dir: True
tmp dir available in use_tmp_dir: False
Python 手册 says this :
On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.
鉴于我创建的示例,这是有道理的。文档还讨论了使用 with
和上下文管理器,但我似乎无法使它们中的任何一个工作。
创建该类的实例并使用self.temp_dir
,只要对象/实例存在,它就会存在。
import tempfile
import os
class Sandbox(): # uppercase - see "PEP 8 -- Style Guide for Python Code"
def start_tmp_dir(self): # self
self.temp_dir = tempfile.TemporaryDirectory() # self.temp_dir
print('tmp dir available in start_tmp_dir: ' + str(os.path.isdir(self.temp_dir.name))) # self.temp_dir
return self.temp_dir.name # self.temp_dir
def use_tmp_dir(self, dir_name):
print('tmp dir available in use_tmp_dir: ' + str(os.path.isdir(dir_name)))
if __name__ == "__main__":
sandbox = Sandbox() # uppercase and ()
dir_name = sandbox.start_tmp_dir()
sandbox.use_tmp_dir(dir_name)
我是一名优秀的程序员,十分优秀!