2 Autotest tempfile wrapper for mkstemp (known as tempfile here) and
3 mkdtemp (known as tempdir).
5 This wrapper provides a mechanism to clean up temporary files/dirs once they
8 Files/Dirs will have a unique_id prepended to the suffix and a
9 _autotmp_ tag appended to the prefix.
11 It is required that the unique_id param is supplied when a temp dir/file is
15 import shutil
, os
, logging
16 import tempfile
as module_tempfile
18 _TEMPLATE
= '_autotmp_'
21 class tempfile(object):
23 A wrapper for tempfile.mkstemp
25 @param unique_id: required, a unique string to help identify what
26 part of code created the tempfile.
27 @var name: The name of the temporary file.
28 @var fd: the file descriptor of the temporary file that was created.
29 @return a tempfile object
31 t = autotemp.tempfile(unique_id='fig')
33 t.fd # file descriptor
35 t.clean() # clean up after yourself
37 def __init__(self
, unique_id
, suffix
='', prefix
='', dir=None,
39 suffix
= unique_id
+ suffix
40 prefix
= prefix
+ _TEMPLATE
41 self
.fd
, self
.name
= module_tempfile
.mkstemp(suffix
=suffix
,
44 self
.fo
= os
.fdopen(self
.fd
)
49 Remove the temporary file that was created.
50 This is also called by the destructor.
54 if self
.name
and os
.path
.exists(self
.name
):
57 self
.fd
= self
.fo
= self
.name
= None
62 if self
.name
is not None:
63 logging
.debug('Clean was not called for ' + self
.name
)
67 msg
= 'An exception occurred while calling the destructor'
68 logging
.exception(msg
)
73 class tempdir(object):
75 A wrapper for tempfile.mkdtemp
77 @var name: The name of the temporary dir.
78 @return A tempdir object
80 b = autotemp.tempdir(unique_id='exemdir')
81 b.name # your directory
82 b.clean() # clean up after yourself
84 def __init__(self
, suffix
='', unique_id
=None, prefix
='', dir=None):
85 suffix
= unique_id
+ suffix
86 prefix
= prefix
+ _TEMPLATE
87 self
.name
= module_tempfile
.mkdtemp(suffix
=suffix
,
88 prefix
=prefix
, dir=dir)
93 Remove the temporary dir that was created.
94 This is also called by the destructor.
96 if self
.name
and os
.path
.exists(self
.name
):
97 shutil
.rmtree(self
.name
)
105 logging
.debug('Clean was not called for ' + self
.name
)
109 msg
= 'An exception occurred while calling the destructor'
110 logging
.exception(msg
)