summaryrefslogtreecommitdiff
path: root/fs/tempfs.py
blob: dc4ca7e066db7a8ec31aab08023d0c81496e971d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python

from osfs import OSFS
import tempfile
from shutil import rmtree

class TempFS(OSFS):

    """Create a Filesystem in a tempory directory (with tempfile.mkdtemp),
    and removes it when the TempFS object is cleaned up."""

    def __init__(self, identifier=None, thread_syncronize=True):
        """Creates a temporary Filesystem

        identifier -- A string that is included in the name of the temporary directory,
        default uses "TempFS"

        """
        self._temp_dir = tempfile.mkdtemp(identifier or "TempFS")
        self._cleaned = False
        OSFS.__init__(self, self._temp_dir, thread_syncronize=thread_syncronize)

    def __str__(self):
        return '<TempFS: %s>' % self._temp_dir

    __repr__ = __str__

    def __unicode__(self):
        return unicode(self.__str__())

    def close(self):
        """Removes the temporary directory.
        This will be called automatically when the object is cleaned up by Python.
        Note that once this method has been called, the FS object may no longer be used."""

        if not self._cleaned and self.exists("/"):
            self._lock.acquire()
            try:
                rmtree(self._temp_dir)
                self._cleaned = True
            finally:
                self._lock.release()

    def __del__(self):
        self.close()

if __name__ == "__main__":

    tfs = TempFS()
    print tfs