HPierce
HPierce

Reputation: 7409

How can I expand context to an entire script?

I am creating a class in Python and one of the methods needs to handle files and save them in a temporary directory. Once the method completes the temporary directory gets deleted. I need the temporary directory to be available to the entire script, as opposed to just the method.

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)

Output:

tmp dir available in start_tmp_dir: True
tmp dir available in use_tmp_dir: False

The Python manual 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.

Which makes sense given the example I created. The docs also talk about using with and a context manager, but I can't seem to make either of them work.

Upvotes: 1

Views: 90

Answers (2)

Jahaja
Jahaja

Reputation: 3302

For that to be true you need to use it as a context manager. Something like this:

#!/usr/bin/python

import tempfile
import os

class Sandbox(object):
    def __init__(self, temp_dir):
        self.temp_dir = temp_dir
        print('tmp dir available in constructor: ' + str(os.path.isdir(self.temp_dir)))

    def use_tmp_dir(self):
        print('tmp dir available in use_tmp_dir: ' + str(os.path.isdir(self.temp_dir)))

if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as temp_dir:
        s = Sandbox(temp_dir)
        s.use_tmp_dir()

Upvotes: 0

furas
furas

Reputation: 142879

Create instance of that class and use self.temp_dir and it will exist as long as object/instance exists.

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)

Upvotes: 1

Related Questions