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
67 if os
.name
== 'posix' and _pid
and _pid
!= os
.getpid():
68 # Our pid changed; we must have forked -- zap the template
71 if os
.name
== 'posix':
73 template
= '@' + `_pid`
+ '.'
75 template
= '~' + `os
.getpid()`
+ '-'
76 elif os
.name
== 'mac':
77 template
= 'Python-Tmp-'
79 template
= 'tmp' # XXX might choose a better one
83 # Counter for generating unique names
88 # User-callable function to return a unique temporary file name
90 def mktemp(suffix
=""):
96 file = os
.path
.join(dir, pre
+ `counter`
+ suffix
)
97 if not os
.path
.exists(file):
101 class TemporaryFileWrapper
:
102 """Temporary file wrapper
104 This class provides a wrapper around files opened for temporary use.
105 In particular, it seeks to automatically remove the file when it is
108 def __init__(self
, file, path
):
120 def __getattr__(self
, name
):
121 file = self
.__dict
__['file']
122 a
= getattr(file, name
)
123 setattr(self
, name
, a
)
127 def TemporaryFile(mode
='w+b', bufsize
=-1, suffix
=""):
128 name
= mktemp(suffix
)
129 if os
.name
== 'posix':
130 # Unix -- be very careful
131 fd
= os
.open(name
, os
.O_RDWR|os
.O_CREAT|os
.O_EXCL
, 0700)
134 return os
.fdopen(fd
, mode
, bufsize
)
139 # Non-unix -- can't unlink file that's still open, use wrapper
140 file = open(name
, mode
, bufsize
)
141 return TemporaryFileWrapper(file, name
)