Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """Temporary files and filenames.""" |
| 2 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 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... |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 7 | import os |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 8 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 9 | __all__ = ["mktemp", "TemporaryFile", "tempdir", "gettempprefix"] |
| 10 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 11 | # Parameters that the caller may set to override the defaults |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 12 | tempdir = None |
| 13 | template = None |
| 14 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 15 | def gettempdir(): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 16 | """Function to calculate the directory to use.""" |
Guido van Rossum | f4aaf86 | 1996-05-28 23:31:34 +0000 | [diff] [blame] | 17 | global tempdir |
Guido van Rossum | 4033ad7 | 1996-08-08 18:33:56 +0000 | [diff] [blame] | 18 | if tempdir is not None: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 19 | return tempdir |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 20 | |
| 21 | # _gettempdir_inner deduces whether a candidate temp dir is usable by |
| 22 | # trying to create a file in it, and write to it. If that succeeds, |
| 23 | # great, it closes the file and unlinks it. There's a race, though: |
| 24 | # the *name* of the test file it tries is the same across all threads |
| 25 | # under most OSes (Linux is an exception), and letting multiple threads |
| 26 | # all try to open, write to, close, and unlink a single file can cause |
| 27 | # a variety of bogus errors (e.g., you cannot unlink a file under |
| 28 | # Windows if anyone has it open, and two threads cannot create the |
| 29 | # same file in O_EXCL mode under Unix). The simplest cure is to serialize |
| 30 | # calls to _gettempdir_inner. This isn't a real expense, because the |
| 31 | # first thread to succeed sets the global tempdir, and all subsequent |
| 32 | # calls to gettempdir() reuse that without trying _gettempdir_inner. |
| 33 | _tempdir_lock.acquire() |
| 34 | try: |
| 35 | return _gettempdir_inner() |
| 36 | finally: |
| 37 | _tempdir_lock.release() |
| 38 | |
| 39 | def _gettempdir_inner(): |
| 40 | """Function to calculate the directory to use.""" |
| 41 | global tempdir |
| 42 | if tempdir is not None: |
| 43 | return tempdir |
Guido van Rossum | 29e5f5d | 1998-04-09 14:27:57 +0000 | [diff] [blame] | 44 | try: |
| 45 | pwd = os.getcwd() |
| 46 | except (AttributeError, os.error): |
| 47 | pwd = os.curdir |
Guido van Rossum | 7dcf84f | 2001-03-02 05:51:16 +0000 | [diff] [blame] | 48 | attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', pwd] |
Guido van Rossum | 3e065ad | 1996-08-20 20:38:59 +0000 | [diff] [blame] | 49 | if os.name == 'nt': |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 50 | attempdirs.insert(0, 'C:\\TEMP') |
| 51 | attempdirs.insert(0, '\\TEMP') |
Guido van Rossum | f4f756c | 1997-04-11 19:00:53 +0000 | [diff] [blame] | 52 | elif os.name == 'mac': |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 53 | import macfs, MACFS |
| 54 | try: |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 55 | refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, |
| 56 | MACFS.kTemporaryFolderType, 1) |
| 57 | dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() |
| 58 | attempdirs.insert(0, dirname) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 59 | except macfs.error: |
| 60 | pass |
Guido van Rossum | e2ae77b | 2001-10-24 20:42:55 +0000 | [diff] [blame] | 61 | elif os.name == 'riscos': |
| 62 | scrapdir = os.getenv('Wimp$ScrapDir') |
| 63 | if scrapdir: |
| 64 | attempdirs.insert(0, scrapdir) |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 65 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 66 | if envname in os.environ: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 67 | attempdirs.insert(0, os.environ[envname]) |
Guido van Rossum | 3e065ad | 1996-08-20 20:38:59 +0000 | [diff] [blame] | 68 | testfile = gettempprefix() + 'test' |
Guido van Rossum | f4aaf86 | 1996-05-28 23:31:34 +0000 | [diff] [blame] | 69 | for dir in attempdirs: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 70 | try: |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 71 | filename = os.path.join(dir, testfile) |
| 72 | if os.name == 'posix': |
| 73 | try: |
Jeremy Hylton | c348cd7 | 2001-02-19 15:34:10 +0000 | [diff] [blame] | 74 | fd = os.open(filename, |
| 75 | os.O_RDWR | os.O_CREAT | os.O_EXCL, 0700) |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 76 | except OSError: |
| 77 | pass |
| 78 | else: |
| 79 | fp = os.fdopen(fd, 'w') |
| 80 | fp.write('blat') |
| 81 | fp.close() |
| 82 | os.unlink(filename) |
| 83 | del fp, fd |
| 84 | tempdir = dir |
| 85 | break |
| 86 | else: |
| 87 | fp = open(filename, 'w') |
| 88 | fp.write('blat') |
| 89 | fp.close() |
| 90 | os.unlink(filename) |
| 91 | tempdir = dir |
| 92 | break |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 93 | except IOError: |
| 94 | pass |
Guido van Rossum | f4aaf86 | 1996-05-28 23:31:34 +0000 | [diff] [blame] | 95 | if tempdir is None: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 96 | msg = "Can't find a usable temporary directory amongst " + `attempdirs` |
| 97 | raise IOError, msg |
Guido van Rossum | f4aaf86 | 1996-05-28 23:31:34 +0000 | [diff] [blame] | 98 | return tempdir |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 99 | |
| 100 | |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 101 | # template caches the result of gettempprefix, for speed, when possible. |
| 102 | # XXX unclear why this isn't "_template"; left it "template" for backward |
| 103 | # compatibility. |
| 104 | if os.name == "posix": |
| 105 | # We don't try to cache the template on posix: the pid may change on us |
| 106 | # between calls due to a fork, and on Linux the pid changes even for |
| 107 | # another thread in the same process. Since any attempt to keep the |
| 108 | # cache in synch would have to call os.getpid() anyway in order to make |
| 109 | # sure the pid hasn't changed between calls, a cache wouldn't save any |
| 110 | # time. In addition, a cache is difficult to keep correct with the pid |
| 111 | # changing willy-nilly, and earlier attempts proved buggy (races). |
| 112 | template = None |
| 113 | |
| 114 | # Else the pid never changes, so gettempprefix always returns the same |
| 115 | # string. |
| 116 | elif os.name == "nt": |
| 117 | template = '~' + `os.getpid()` + '-' |
Guido van Rossum | e2ae77b | 2001-10-24 20:42:55 +0000 | [diff] [blame] | 118 | elif os.name in ('mac', 'riscos'): |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 119 | template = 'Python-Tmp-' |
| 120 | else: |
| 121 | template = 'tmp' # XXX might choose a better one |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 122 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 123 | def gettempprefix(): |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 124 | """Function to calculate a prefix of the filename to use. |
| 125 | |
| 126 | This incorporates the current process id on systems that support such a |
| 127 | notion, so that concurrent processes don't generate the same prefix. |
| 128 | """ |
| 129 | |
Tim Peters | 8373218 | 2001-01-14 05:12:40 +0000 | [diff] [blame] | 130 | global template |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 131 | if template is None: |
Tim Peters | 8373218 | 2001-01-14 05:12:40 +0000 | [diff] [blame] | 132 | return '@' + `os.getpid()` + '.' |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 133 | else: |
| 134 | return template |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 135 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 136 | |
Guido van Rossum | b8c42c9 | 1997-12-19 04:29:50 +0000 | [diff] [blame] | 137 | def mktemp(suffix=""): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 138 | """User-callable function to return a unique temporary file name.""" |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 139 | dir = gettempdir() |
| 140 | pre = gettempprefix() |
| 141 | while 1: |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 142 | i = _counter.get_next() |
| 143 | file = os.path.join(dir, pre + str(i) + suffix) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 144 | if not os.path.exists(file): |
| 145 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 146 | |
| 147 | |
| 148 | class TemporaryFileWrapper: |
| 149 | """Temporary file wrapper |
| 150 | |
| 151 | This class provides a wrapper around files opened for temporary use. |
| 152 | In particular, it seeks to automatically remove the file when it is |
| 153 | no longer needed. |
| 154 | """ |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 155 | |
| 156 | # Cache the unlinker so we don't get spurious errors at shutdown |
Tim Peters | 81b61bd | 2001-12-18 23:22:01 +0000 | [diff] [blame] | 157 | # when the module-level "os" is None'd out. Note that this must |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 158 | # be referenced as self.unlink, because the name TemporaryFileWrapper |
| 159 | # may also get None'd out before __del__ is called. |
| 160 | unlink = os.unlink |
| 161 | |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 162 | def __init__(self, file, path): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 163 | self.file = file |
| 164 | self.path = path |
Tim Peters | c57a285 | 2001-10-29 21:46:08 +0000 | [diff] [blame] | 165 | self.close_called = 0 |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 166 | |
| 167 | def close(self): |
Tim Peters | c57a285 | 2001-10-29 21:46:08 +0000 | [diff] [blame] | 168 | if not self.close_called: |
| 169 | self.close_called = 1 |
| 170 | self.file.close() |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 171 | self.unlink(self.path) |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 172 | |
| 173 | def __del__(self): |
Tim Peters | c57a285 | 2001-10-29 21:46:08 +0000 | [diff] [blame] | 174 | self.close() |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 175 | |
| 176 | def __getattr__(self, name): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 177 | file = self.__dict__['file'] |
| 178 | a = getattr(file, name) |
Guido van Rossum | 6b708d5 | 1999-06-01 18:55:36 +0000 | [diff] [blame] | 179 | if type(a) != type(0): |
| 180 | setattr(self, name, a) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 181 | return a |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 182 | |
Neil Schemenauer | 153cc0f | 2002-03-24 22:21:48 +0000 | [diff] [blame] | 183 | try: |
| 184 | import fcntl as _fcntl |
| 185 | def _set_cloexec(fd, flag=_fcntl.FD_CLOEXEC): |
| 186 | flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) |
| 187 | if flags >= 0: |
| 188 | # flags read successfully, modify |
| 189 | flags |= flag |
| 190 | _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) |
| 191 | except (ImportError, AttributeError): |
| 192 | def _set_cloexec(fd): |
| 193 | pass |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 194 | |
Guido van Rossum | b8c42c9 | 1997-12-19 04:29:50 +0000 | [diff] [blame] | 195 | def TemporaryFile(mode='w+b', bufsize=-1, suffix=""): |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 196 | """Create and return a temporary file (opened read-write by default).""" |
Guido van Rossum | b8c42c9 | 1997-12-19 04:29:50 +0000 | [diff] [blame] | 197 | name = mktemp(suffix) |
Guido van Rossum | dce3d55 | 1998-10-24 01:34:45 +0000 | [diff] [blame] | 198 | if os.name == 'posix': |
| 199 | # Unix -- be very careful |
| 200 | fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700) |
Neil Schemenauer | 153cc0f | 2002-03-24 22:21:48 +0000 | [diff] [blame] | 201 | _set_cloexec(fd) |
Guido van Rossum | 2457fc2 | 1998-10-24 15:02:59 +0000 | [diff] [blame] | 202 | try: |
| 203 | os.unlink(name) |
| 204 | return os.fdopen(fd, mode, bufsize) |
| 205 | except: |
| 206 | os.close(fd) |
| 207 | raise |
Tim Peters | c7349ee | 2002-01-30 07:47:51 +0000 | [diff] [blame] | 208 | elif os.name == 'nt': |
| 209 | # Windows -- can't unlink an open file, but O_TEMPORARY creates a |
| 210 | # file that "deletes itself" when the last handle is closed. |
| 211 | # O_NOINHERIT ensures processes created via spawn() don't get a |
| 212 | # handle to this too. That would be a security hole, and, on my |
| 213 | # Win98SE box, when an O_TEMPORARY file is inherited by a spawned |
| 214 | # process, the fd in the spawned process seems to lack the |
| 215 | # O_TEMPORARY flag, so the file doesn't go away by magic then if the |
| 216 | # spawning process closes it first. |
| 217 | flags = (os.O_RDWR | os.O_CREAT | os.O_EXCL | |
| 218 | os.O_TEMPORARY | os.O_NOINHERIT) |
| 219 | if 'b' in mode: |
| 220 | flags |= os.O_BINARY |
| 221 | fd = os.open(name, flags, 0700) |
| 222 | return os.fdopen(fd, mode, bufsize) |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 223 | else: |
Tim Peters | c7349ee | 2002-01-30 07:47:51 +0000 | [diff] [blame] | 224 | # Assume we can't unlink a file that's still open, or arrange for |
| 225 | # an automagically self-deleting file -- use wrapper. |
Guido van Rossum | dce3d55 | 1998-10-24 01:34:45 +0000 | [diff] [blame] | 226 | file = open(name, mode, bufsize) |
| 227 | return TemporaryFileWrapper(file, name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 228 | |
| 229 | # In order to generate unique names, mktemp() uses _counter.get_next(). |
| 230 | # This returns a unique integer on each call, in a threadsafe way (i.e., |
| 231 | # multiple threads will never see the same integer). The integer will |
| 232 | # usually be a Python int, but if _counter.get_next() is called often |
| 233 | # enough, it will become a Python long. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 234 | # Note that the only names that survive this next block of code |
| 235 | # are "_counter" and "_tempdir_lock". |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 236 | |
| 237 | class _ThreadSafeCounter: |
| 238 | def __init__(self, mutex, initialvalue=0): |
| 239 | self.mutex = mutex |
| 240 | self.i = initialvalue |
| 241 | |
| 242 | def get_next(self): |
| 243 | self.mutex.acquire() |
| 244 | result = self.i |
| 245 | try: |
| 246 | newi = result + 1 |
| 247 | except OverflowError: |
| 248 | newi = long(result) + 1 |
| 249 | self.i = newi |
| 250 | self.mutex.release() |
| 251 | return result |
| 252 | |
| 253 | try: |
| 254 | import thread |
| 255 | |
| 256 | except ImportError: |
| 257 | class _DummyMutex: |
| 258 | def acquire(self): |
| 259 | pass |
| 260 | |
| 261 | release = acquire |
| 262 | |
| 263 | _counter = _ThreadSafeCounter(_DummyMutex()) |
Tim Peters | 40915bf | 2002-01-30 09:11:42 +0000 | [diff] [blame] | 264 | _tempdir_lock = _DummyMutex() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 265 | del _DummyMutex |
| 266 | |
| 267 | else: |
| 268 | _counter = _ThreadSafeCounter(thread.allocate_lock()) |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 269 | _tempdir_lock = thread.allocate_lock() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 270 | del thread |
| 271 | |
| 272 | del _ThreadSafeCounter |