gpt4 book ai didi

python - 如何将上下文扩展到整个脚本?

转载 作者:太空宇宙 更新时间:2023-11-03 18:17:02 26 4
gpt4 key购买 nike

我正在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)

关于python - 如何将上下文扩展到整个脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24856479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com