1 # Temporary file name allocation
3 # XXX This tries to be not UNIX specific, but I don't know beans about
4 # how to choose a temp directory or filename on MS-DOS or other
5 # systems so it may have to be changed...
11 # Parameters that the caller may set to override the defaults
17 # Function to calculate the directory to use
21 if tempdir
is not None:
25 except (AttributeError, os
.error
):
27 attempdirs
= ['/usr/tmp', '/tmp', pwd
]
29 attempdirs
.insert(0, 'C:\\TEMP')
30 attempdirs
.insert(0, '\\TEMP')
31 elif os
.name
== 'mac':
34 refnum
, dirid
= macfs
.FindFolder(MACFS
.kOnSystemDisk
,
35 MACFS
.kTemporaryFolderType
, 1)
36 dirname
= macfs
.FSSpec((refnum
, dirid
, '')).as_pathname()
37 attempdirs
.insert(0, dirname
)
40 for envname
in 'TMPDIR', 'TEMP', 'TMP':
41 if os
.environ
.has_key(envname
):
42 attempdirs
.insert(0, os
.environ
[envname
])
43 testfile
= gettempprefix() + 'test'
44 for dir in attempdirs
:
46 filename
= os
.path
.join(dir, testfile
)
47 fp
= open(filename
, 'w')
56 msg
= "Can't find a usable temporary directory amongst " + `attempdirs`
61 # Function to calculate a prefix of the filename to use
66 if os
.name
== 'posix':
67 template
= '@' + `os
.getpid()`
+ '.'
69 template
= '~' + `os
.getpid()`
+ '-'
70 elif os
.name
== 'mac':
71 template
= 'Python-Tmp-'
73 template
= 'tmp' # XXX might choose a better one
77 # Counter for generating unique names
82 # User-callable function to return a unique temporary file name
84 def mktemp(suffix
=""):
90 file = os
.path
.join(dir, pre
+ `counter`
+ suffix
)
91 if not os
.path
.exists(file):
95 class TemporaryFileWrapper
:
96 """Temporary file wrapper
98 This class provides a wrapper around files opened for temporary use.
99 In particular, it seeks to automatically remove the file when it is
102 def __init__(self
, file, path
):
114 def __getattr__(self
, name
):
115 file = self
.__dict
__['file']
116 a
= getattr(file, name
)
117 setattr(self
, name
, a
)
121 def TemporaryFile(mode
='w+b', bufsize
=-1, suffix
=""):
122 name
= mktemp(suffix
)
123 file = open(name
, mode
, bufsize
)
127 # Non-unix -- can't unlink file that's still open, use wrapper
128 return TemporaryFileWrapper(file, name
)