blob: 7a1fc26c1b5df49bc3e50f37c38f2241c5b07a45 [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Temporary files and filenames."""
2
Guido van Rossum41f95031992-03-31 19:02:01 +00003# 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...
Guido van Rossumeee94981991-11-12 15:38:08 +00006
Guido van Rossum41f95031992-03-31 19:02:01 +00007import os
Guido van Rossumeee94981991-11-12 15:38:08 +00008
Skip Montanaro40fc1602001-03-01 04:27:19 +00009__all__ = ["mktemp", "TemporaryFile", "tempdir", "gettempprefix"]
10
Guido van Rossum41f95031992-03-31 19:02:01 +000011# Parameters that the caller may set to override the defaults
Guido van Rossum41f95031992-03-31 19:02:01 +000012tempdir = None
13template = None
14
Guido van Rossum41f95031992-03-31 19:02:01 +000015def gettempdir():
Guido van Rossume7b146f2000-02-04 15:28:42 +000016 """Function to calculate the directory to use."""
Guido van Rossumf4aaf861996-05-28 23:31:34 +000017 global tempdir
Guido van Rossum4033ad71996-08-08 18:33:56 +000018 if tempdir is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000019 return tempdir
Guido van Rossum29e5f5d1998-04-09 14:27:57 +000020 try:
21 pwd = os.getcwd()
22 except (AttributeError, os.error):
23 pwd = os.curdir
Guido van Rossum7dcf84f2001-03-02 05:51:16 +000024 attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', pwd]
Guido van Rossum3e065ad1996-08-20 20:38:59 +000025 if os.name == 'nt':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000026 attempdirs.insert(0, 'C:\\TEMP')
27 attempdirs.insert(0, '\\TEMP')
Guido van Rossumf4f756c1997-04-11 19:00:53 +000028 elif os.name == 'mac':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000029 import macfs, MACFS
30 try:
Tim Petersb90f89a2001-01-15 03:26:36 +000031 refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
32 MACFS.kTemporaryFolderType, 1)
33 dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
34 attempdirs.insert(0, dirname)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000035 except macfs.error:
36 pass
Guido van Rossumca549821997-08-12 18:00:12 +000037 for envname in 'TMPDIR', 'TEMP', 'TMP':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000038 if os.environ.has_key(envname):
39 attempdirs.insert(0, os.environ[envname])
Guido van Rossum3e065ad1996-08-20 20:38:59 +000040 testfile = gettempprefix() + 'test'
Guido van Rossumf4aaf861996-05-28 23:31:34 +000041 for dir in attempdirs:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000042 try:
Tim Petersb90f89a2001-01-15 03:26:36 +000043 filename = os.path.join(dir, testfile)
44 if os.name == 'posix':
45 try:
Jeremy Hyltonc348cd72001-02-19 15:34:10 +000046 fd = os.open(filename,
47 os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700)
Tim Petersb90f89a2001-01-15 03:26:36 +000048 except OSError:
49 pass
50 else:
51 fp = os.fdopen(fd, 'w')
52 fp.write('blat')
53 fp.close()
54 os.unlink(filename)
55 del fp, fd
56 tempdir = dir
57 break
58 else:
59 fp = open(filename, 'w')
60 fp.write('blat')
61 fp.close()
62 os.unlink(filename)
63 tempdir = dir
64 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000065 except IOError:
66 pass
Guido van Rossumf4aaf861996-05-28 23:31:34 +000067 if tempdir is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000068 msg = "Can't find a usable temporary directory amongst " + `attempdirs`
69 raise IOError, msg
Guido van Rossumf4aaf861996-05-28 23:31:34 +000070 return tempdir
Guido van Rossum41f95031992-03-31 19:02:01 +000071
72
Tim Peters9fadfb02001-01-13 03:04:02 +000073# template caches the result of gettempprefix, for speed, when possible.
74# XXX unclear why this isn't "_template"; left it "template" for backward
75# compatibility.
76if os.name == "posix":
77 # We don't try to cache the template on posix: the pid may change on us
78 # between calls due to a fork, and on Linux the pid changes even for
79 # another thread in the same process. Since any attempt to keep the
80 # cache in synch would have to call os.getpid() anyway in order to make
81 # sure the pid hasn't changed between calls, a cache wouldn't save any
82 # time. In addition, a cache is difficult to keep correct with the pid
83 # changing willy-nilly, and earlier attempts proved buggy (races).
84 template = None
85
86# Else the pid never changes, so gettempprefix always returns the same
87# string.
88elif os.name == "nt":
89 template = '~' + `os.getpid()` + '-'
90elif os.name == 'mac':
91 template = 'Python-Tmp-'
92else:
93 template = 'tmp' # XXX might choose a better one
Guido van Rossumb0e57181998-10-14 20:27:05 +000094
Guido van Rossum41f95031992-03-31 19:02:01 +000095def gettempprefix():
Tim Peters9fadfb02001-01-13 03:04:02 +000096 """Function to calculate a prefix of the filename to use.
97
98 This incorporates the current process id on systems that support such a
99 notion, so that concurrent processes don't generate the same prefix.
100 """
101
Tim Peters83732182001-01-14 05:12:40 +0000102 global template
Guido van Rossumb0e57181998-10-14 20:27:05 +0000103 if template is None:
Tim Peters83732182001-01-14 05:12:40 +0000104 return '@' + `os.getpid()` + '.'
Tim Peters9fadfb02001-01-13 03:04:02 +0000105 else:
106 return template
Guido van Rossumcff34541992-01-14 18:31:56 +0000107
Guido van Rossumeee94981991-11-12 15:38:08 +0000108
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000109def mktemp(suffix=""):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000110 """User-callable function to return a unique temporary file name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 dir = gettempdir()
112 pre = gettempprefix()
113 while 1:
Tim Peters1baa22a2001-01-12 10:02:46 +0000114 i = _counter.get_next()
115 file = os.path.join(dir, pre + str(i) + suffix)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000116 if not os.path.exists(file):
117 return file
Guido van Rossumca549821997-08-12 18:00:12 +0000118
119
120class TemporaryFileWrapper:
121 """Temporary file wrapper
122
123 This class provides a wrapper around files opened for temporary use.
124 In particular, it seeks to automatically remove the file when it is
125 no longer needed.
126 """
127 def __init__(self, file, path):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000128 self.file = file
129 self.path = path
Guido van Rossumca549821997-08-12 18:00:12 +0000130
131 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000132 self.file.close()
133 os.unlink(self.path)
Guido van Rossumca549821997-08-12 18:00:12 +0000134
135 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000136 try: self.close()
137 except: pass
Guido van Rossumca549821997-08-12 18:00:12 +0000138
139 def __getattr__(self, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000140 file = self.__dict__['file']
141 a = getattr(file, name)
Guido van Rossum6b708d51999-06-01 18:55:36 +0000142 if type(a) != type(0):
143 setattr(self, name, a)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 return a
Guido van Rossumca549821997-08-12 18:00:12 +0000145
146
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000147def TemporaryFile(mode='w+b', bufsize=-1, suffix=""):
Guido van Rossume7b146f2000-02-04 15:28:42 +0000148 """Create and return a temporary file (opened read-write by default)."""
Guido van Rossumb8c42c91997-12-19 04:29:50 +0000149 name = mktemp(suffix)
Guido van Rossumdce3d551998-10-24 01:34:45 +0000150 if os.name == 'posix':
151 # Unix -- be very careful
152 fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
Guido van Rossum2457fc21998-10-24 15:02:59 +0000153 try:
154 os.unlink(name)
155 return os.fdopen(fd, mode, bufsize)
156 except:
157 os.close(fd)
158 raise
Guido van Rossumca549821997-08-12 18:00:12 +0000159 else:
Guido van Rossumdce3d551998-10-24 01:34:45 +0000160 # Non-unix -- can't unlink file that's still open, use wrapper
161 file = open(name, mode, bufsize)
162 return TemporaryFileWrapper(file, name)
Tim Peters1baa22a2001-01-12 10:02:46 +0000163
164# In order to generate unique names, mktemp() uses _counter.get_next().
165# This returns a unique integer on each call, in a threadsafe way (i.e.,
166# multiple threads will never see the same integer). The integer will
167# usually be a Python int, but if _counter.get_next() is called often
168# enough, it will become a Python long.
169# Note that the only name that survives this next block of code
170# is "_counter".
171
172class _ThreadSafeCounter:
173 def __init__(self, mutex, initialvalue=0):
174 self.mutex = mutex
175 self.i = initialvalue
176
177 def get_next(self):
178 self.mutex.acquire()
179 result = self.i
180 try:
181 newi = result + 1
182 except OverflowError:
183 newi = long(result) + 1
184 self.i = newi
185 self.mutex.release()
186 return result
187
188try:
189 import thread
190
191except ImportError:
192 class _DummyMutex:
193 def acquire(self):
194 pass
195
196 release = acquire
197
198 _counter = _ThreadSafeCounter(_DummyMutex())
199 del _DummyMutex
200
201else:
202 _counter = _ThreadSafeCounter(thread.allocate_lock())
203 del thread
204
205del _ThreadSafeCounter