Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 1 | """Temporary files. |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 3 | This module provides generic, low- and high-level interfaces for |
| 4 | creating temporary files and directories. The interfaces listed |
| 5 | as "safe" just below can be used without fear of race conditions. |
| 6 | Those listed as "unsafe" cannot, and are provided for backward |
| 7 | compatibility only. |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 9 | This module also provides some data items to the user: |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 11 | TMP_MAX - maximum number of names that will be tried before |
| 12 | giving up. |
| 13 | template - the default prefix for all temporary names. |
| 14 | You may change this to control the default prefix. |
| 15 | tempdir - If this is set to a string before the first use of |
| 16 | any routine from this module, it will be considered as |
| 17 | another candidate location to store temporary files. |
| 18 | """ |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 19 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 20 | __all__ = [ |
| 21 | "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces |
Collin Winter | a8785cc | 2007-03-19 18:52:08 +0000 | [diff] [blame] | 22 | "SpooledTemporaryFile", |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 23 | "mkstemp", "mkdtemp", # low level safe interfaces |
| 24 | "mktemp", # deprecated unsafe interface |
| 25 | "TMP_MAX", "gettempprefix", # constants |
| 26 | "tempdir", "gettempdir" |
| 27 | ] |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 28 | |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 29 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 30 | # Imports. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 31 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 32 | import os as _os |
| 33 | import errno as _errno |
| 34 | from random import Random as _Random |
| 35 | |
| 36 | if _os.name == 'mac': |
Jack Jansen | bb829b7 | 2003-03-21 12:55:38 +0000 | [diff] [blame] | 37 | import Carbon.Folder as _Folder |
| 38 | import Carbon.Folders as _Folders |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 39 | |
| 40 | try: |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 41 | from cStringIO import StringIO as _StringIO |
Collin Winter | a8785cc | 2007-03-19 18:52:08 +0000 | [diff] [blame] | 42 | except: |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 43 | from StringIO import StringIO as _StringIO |
Collin Winter | a8785cc | 2007-03-19 18:52:08 +0000 | [diff] [blame] | 44 | |
| 45 | try: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 46 | import fcntl as _fcntl |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 47 | except ImportError: |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 48 | def _set_cloexec(fd): |
| 49 | pass |
| 50 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 51 | def _set_cloexec(fd): |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 52 | try: |
| 53 | flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) |
| 54 | except IOError: |
| 55 | pass |
Alex Martelli | f09994e | 2003-11-09 16:44:09 +0000 | [diff] [blame] | 56 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 57 | # flags read successfully, modify |
| 58 | flags |= _fcntl.FD_CLOEXEC |
| 59 | _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 60 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 61 | |
| 62 | try: |
| 63 | import thread as _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 64 | except ImportError: |
| 65 | import dummy_thread as _thread |
| 66 | _allocate_lock = _thread.allocate_lock |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 67 | |
| 68 | _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 69 | if hasattr(_os, 'O_NOINHERIT'): |
| 70 | _text_openflags |= _os.O_NOINHERIT |
| 71 | if hasattr(_os, 'O_NOFOLLOW'): |
| 72 | _text_openflags |= _os.O_NOFOLLOW |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 73 | |
| 74 | _bin_openflags = _text_openflags |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 75 | if hasattr(_os, 'O_BINARY'): |
| 76 | _bin_openflags |= _os.O_BINARY |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 77 | |
| 78 | if hasattr(_os, 'TMP_MAX'): |
| 79 | TMP_MAX = _os.TMP_MAX |
| 80 | else: |
| 81 | TMP_MAX = 10000 |
| 82 | |
Tim Peters | bd7b4c7 | 2002-08-13 23:33:56 +0000 | [diff] [blame] | 83 | template = "tmp" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 84 | |
| 85 | tempdir = None |
| 86 | |
| 87 | # Internal routines. |
| 88 | |
| 89 | _once_lock = _allocate_lock() |
| 90 | |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 91 | if hasattr(_os, "lstat"): |
| 92 | _stat = _os.lstat |
| 93 | elif hasattr(_os, "stat"): |
| 94 | _stat = _os.stat |
| 95 | else: |
| 96 | # Fallback. All we need is something that raises os.error if the |
| 97 | # file doesn't exist. |
| 98 | def _stat(fn): |
| 99 | try: |
| 100 | f = open(fn) |
| 101 | except IOError: |
| 102 | raise _os.error |
| 103 | f.close() |
| 104 | |
| 105 | def _exists(fn): |
| 106 | try: |
| 107 | _stat(fn) |
| 108 | except _os.error: |
| 109 | return False |
| 110 | else: |
| 111 | return True |
| 112 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 113 | class _RandomNameSequence: |
| 114 | """An instance of _RandomNameSequence generates an endless |
| 115 | sequence of unpredictable strings which can safely be incorporated |
| 116 | into file names. Each string is six characters long. Multiple |
| 117 | threads can safely use the same instance at the same time. |
| 118 | |
| 119 | _RandomNameSequence is an iterator.""" |
| 120 | |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 121 | characters = ("abcdefghijklmnopqrstuvwxyz" + |
| 122 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + |
Collin Winter | 9b2a109 | 2007-03-08 22:16:25 +0000 | [diff] [blame] | 123 | "0123456789_") |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 124 | |
| 125 | def __init__(self): |
| 126 | self.mutex = _allocate_lock() |
| 127 | self.rng = _Random() |
| 128 | self.normcase = _os.path.normcase |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 129 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 130 | def __iter__(self): |
| 131 | return self |
| 132 | |
| 133 | def next(self): |
| 134 | m = self.mutex |
| 135 | c = self.characters |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 136 | choose = self.rng.choice |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 137 | |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 138 | m.acquire() |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 139 | try: |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 140 | letters = [choose(c) for dummy in "123456"] |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 141 | finally: |
| 142 | m.release() |
| 143 | |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 144 | return self.normcase(''.join(letters)) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 145 | |
| 146 | def _candidate_tempdir_list(): |
| 147 | """Generate a list of candidate temporary directories which |
| 148 | _get_default_tempdir will try.""" |
| 149 | |
| 150 | dirlist = [] |
| 151 | |
| 152 | # First, try the environment. |
| 153 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 154 | dirname = _os.getenv(envname) |
| 155 | if dirname: dirlist.append(dirname) |
| 156 | |
| 157 | # Failing that, try OS-specific locations. |
| 158 | if _os.name == 'mac': |
| 159 | try: |
Jack Jansen | bb829b7 | 2003-03-21 12:55:38 +0000 | [diff] [blame] | 160 | fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk, |
| 161 | _Folders.kTemporaryFolderType, 1) |
| 162 | dirname = fsr.as_pathname() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 163 | dirlist.append(dirname) |
Jack Jansen | bb829b7 | 2003-03-21 12:55:38 +0000 | [diff] [blame] | 164 | except _Folder.error: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 165 | pass |
| 166 | elif _os.name == 'riscos': |
| 167 | dirname = _os.getenv('Wimp$ScrapDir') |
| 168 | if dirname: dirlist.append(dirname) |
| 169 | elif _os.name == 'nt': |
| 170 | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 171 | else: |
| 172 | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 173 | |
| 174 | # As a last resort, the current directory. |
| 175 | try: |
| 176 | dirlist.append(_os.getcwd()) |
| 177 | except (AttributeError, _os.error): |
| 178 | dirlist.append(_os.curdir) |
| 179 | |
| 180 | return dirlist |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 181 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 182 | def _get_default_tempdir(): |
| 183 | """Calculate the default directory to use for temporary files. |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 184 | This routine should be called exactly once. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 185 | |
| 186 | We determine whether or not a candidate temp dir is usable by |
| 187 | trying to create and write to a file in that directory. If this |
| 188 | is successful, the test file is deleted. To prevent denial of |
| 189 | service, the name of the test file must be randomized.""" |
| 190 | |
| 191 | namer = _RandomNameSequence() |
| 192 | dirlist = _candidate_tempdir_list() |
| 193 | flags = _text_openflags |
| 194 | |
| 195 | for dir in dirlist: |
| 196 | if dir != _os.curdir: |
| 197 | dir = _os.path.normcase(_os.path.abspath(dir)) |
| 198 | # Try only a few names per directory. |
| 199 | for seq in xrange(100): |
| 200 | name = namer.next() |
| 201 | filename = _os.path.join(dir, name) |
| 202 | try: |
| 203 | fd = _os.open(filename, flags, 0600) |
| 204 | fp = _os.fdopen(fd, 'w') |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 205 | fp.write('blat') |
| 206 | fp.close() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 207 | _os.unlink(filename) |
| 208 | del fp, fd |
| 209 | return dir |
| 210 | except (OSError, IOError), e: |
| 211 | if e[0] != _errno.EEXIST: |
| 212 | break # no point trying more names in this directory |
| 213 | pass |
| 214 | raise IOError, (_errno.ENOENT, |
| 215 | ("No usable temporary directory found in %s" % dirlist)) |
| 216 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 217 | _name_sequence = None |
| 218 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 219 | def _get_candidate_names(): |
| 220 | """Common setup sequence for all user-callable interfaces.""" |
| 221 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 222 | global _name_sequence |
| 223 | if _name_sequence is None: |
| 224 | _once_lock.acquire() |
| 225 | try: |
| 226 | if _name_sequence is None: |
| 227 | _name_sequence = _RandomNameSequence() |
| 228 | finally: |
| 229 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 230 | return _name_sequence |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 231 | |
| 232 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 233 | def _mkstemp_inner(dir, pre, suf, flags): |
| 234 | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 235 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 236 | names = _get_candidate_names() |
| 237 | |
| 238 | for seq in xrange(TMP_MAX): |
| 239 | name = names.next() |
| 240 | file = _os.path.join(dir, pre + name + suf) |
| 241 | try: |
| 242 | fd = _os.open(file, flags, 0600) |
| 243 | _set_cloexec(fd) |
Martin v. Löwis | d662548 | 2003-10-12 17:37:01 +0000 | [diff] [blame] | 244 | return (fd, _os.path.abspath(file)) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 245 | except OSError, e: |
| 246 | if e.errno == _errno.EEXIST: |
| 247 | continue # try again |
| 248 | raise |
| 249 | |
| 250 | raise IOError, (_errno.EEXIST, "No usable temporary file name found") |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 251 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 252 | |
| 253 | # User visible interfaces. |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 254 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 255 | def gettempprefix(): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 256 | """Accessor for tempdir.template.""" |
| 257 | return template |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 258 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 259 | tempdir = None |
| 260 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 261 | def gettempdir(): |
| 262 | """Accessor for tempdir.tempdir.""" |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 263 | global tempdir |
| 264 | if tempdir is None: |
| 265 | _once_lock.acquire() |
| 266 | try: |
| 267 | if tempdir is None: |
| 268 | tempdir = _get_default_tempdir() |
| 269 | finally: |
| 270 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 271 | return tempdir |
| 272 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 273 | def mkstemp(suffix="", prefix=template, dir=None, text=False): |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 274 | """mkstemp([suffix, [prefix, [dir, [text]]]]) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 275 | User-callable function to create and return a unique temporary |
| 276 | file. The return value is a pair (fd, name) where fd is the |
| 277 | file descriptor returned by os.open, and name is the filename. |
| 278 | |
| 279 | If 'suffix' is specified, the file name will end with that suffix, |
| 280 | otherwise there will be no suffix. |
| 281 | |
| 282 | If 'prefix' is specified, the file name will begin with that prefix, |
| 283 | otherwise a default prefix is used. |
| 284 | |
| 285 | If 'dir' is specified, the file will be created in that directory, |
| 286 | otherwise a default directory is used. |
| 287 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 288 | If 'text' is specified and true, the file is opened in text |
| 289 | mode. Else (the default) the file is opened in binary mode. On |
| 290 | some operating systems, this makes no difference. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 291 | |
| 292 | The file is readable and writable only by the creating user ID. |
| 293 | If the operating system uses permission bits to indicate whether a |
| 294 | file is executable, the file is executable by no one. The file |
| 295 | descriptor is not inherited by children of this process. |
| 296 | |
| 297 | Caller is responsible for deleting the file when done with it. |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 298 | """ |
| 299 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 300 | if dir is None: |
| 301 | dir = gettempdir() |
| 302 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 303 | if text: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 304 | flags = _text_openflags |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 305 | else: |
| 306 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 307 | |
| 308 | return _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 309 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 310 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 311 | def mkdtemp(suffix="", prefix=template, dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 312 | """mkdtemp([suffix, [prefix, [dir]]]) |
| 313 | User-callable function to create and return a unique temporary |
| 314 | directory. The return value is the pathname of the directory. |
| 315 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 316 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 317 | not accepted. |
| 318 | |
| 319 | The directory is readable, writable, and searchable only by the |
| 320 | creating user. |
| 321 | |
| 322 | Caller is responsible for deleting the directory when done with it. |
| 323 | """ |
| 324 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 325 | if dir is None: |
| 326 | dir = gettempdir() |
| 327 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 328 | names = _get_candidate_names() |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 329 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 330 | for seq in xrange(TMP_MAX): |
| 331 | name = names.next() |
| 332 | file = _os.path.join(dir, prefix + name + suffix) |
| 333 | try: |
| 334 | _os.mkdir(file, 0700) |
| 335 | return file |
| 336 | except OSError, e: |
| 337 | if e.errno == _errno.EEXIST: |
| 338 | continue # try again |
| 339 | raise |
| 340 | |
| 341 | raise IOError, (_errno.EEXIST, "No usable temporary directory name found") |
| 342 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 343 | def mktemp(suffix="", prefix=template, dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 344 | """mktemp([suffix, [prefix, [dir]]]) |
| 345 | User-callable function to return a unique temporary file name. The |
| 346 | file is not created. |
| 347 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 348 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 349 | not accepted. |
| 350 | |
| 351 | This function is unsafe and should not be used. The file name |
| 352 | refers to a file that did not exist at some point, but by the time |
| 353 | you get around to creating it, someone else may have beaten you to |
| 354 | the punch. |
| 355 | """ |
| 356 | |
Guido van Rossum | 44f602d | 2002-11-22 15:56:29 +0000 | [diff] [blame] | 357 | ## from warnings import warn as _warn |
| 358 | ## _warn("mktemp is a potential security risk to your program", |
| 359 | ## RuntimeWarning, stacklevel=2) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 360 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 361 | if dir is None: |
| 362 | dir = gettempdir() |
| 363 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 364 | names = _get_candidate_names() |
| 365 | for seq in xrange(TMP_MAX): |
| 366 | name = names.next() |
| 367 | file = _os.path.join(dir, prefix + name + suffix) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 368 | if not _exists(file): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 369 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 370 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 371 | raise IOError, (_errno.EEXIST, "No usable temporary filename found") |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 372 | |
Nick Coghlan | 97fac3e | 2008-02-09 15:28:09 +0000 | [diff] [blame] | 373 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 374 | class _TemporaryFileWrapper: |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 375 | """Temporary file wrapper |
| 376 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 377 | This class provides a wrapper around files opened for |
| 378 | temporary use. In particular, it seeks to automatically |
| 379 | remove the file when it is no longer needed. |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 380 | """ |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 381 | |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 382 | def __init__(self, file, name, delete=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 383 | self.file = file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 384 | self.name = name |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 385 | self.close_called = False |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 386 | self.delete = delete |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 387 | |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 388 | def __getattr__(self, name): |
Nick Coghlan | 97fac3e | 2008-02-09 15:28:09 +0000 | [diff] [blame] | 389 | # Attribute lookups are delegated to the underlying file |
| 390 | # and cached for non-numeric results |
| 391 | # (i.e. methods are cached, closed and friends are not) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 392 | file = self.__dict__['file'] |
| 393 | a = getattr(file, name) |
Nick Coghlan | 97fac3e | 2008-02-09 15:28:09 +0000 | [diff] [blame] | 394 | if not issubclass(type(a), type(0)): |
Guido van Rossum | 6b708d5 | 1999-06-01 18:55:36 +0000 | [diff] [blame] | 395 | setattr(self, name, a) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 396 | return a |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 397 | |
Nick Coghlan | 97fac3e | 2008-02-09 15:28:09 +0000 | [diff] [blame] | 398 | # The underlying __enter__ method returns the wrong object |
| 399 | # (self.file) so override it to return the wrapper |
| 400 | def __enter__(self): |
| 401 | self.file.__enter__() |
| 402 | return self |
| 403 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 404 | # NT provides delete-on-close as a primitive, so we don't need |
| 405 | # the wrapper to do anything special. We still use it so that |
| 406 | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
| 407 | if _os.name != 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 408 | # Cache the unlinker so we don't get spurious errors at |
| 409 | # shutdown when the module-level "os" is None'd out. Note |
| 410 | # that this must be referenced as self.unlink, because the |
| 411 | # name TemporaryFileWrapper may also get None'd out before |
| 412 | # __del__ is called. |
| 413 | unlink = _os.unlink |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 414 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 415 | def close(self): |
| 416 | if not self.close_called: |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 417 | self.close_called = True |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 418 | self.file.close() |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 419 | if self.delete: |
| 420 | self.unlink(self.name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 421 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 422 | def __del__(self): |
| 423 | self.close() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 424 | |
Nick Coghlan | 97fac3e | 2008-02-09 15:28:09 +0000 | [diff] [blame] | 425 | # Need to trap __exit__ as well to ensure the file gets |
| 426 | # deleted when used in a with statement |
| 427 | def __exit__(self, exc, value, tb): |
| 428 | result = self.file.__exit__(exc, value, tb) |
| 429 | self.close() |
| 430 | return result |
| 431 | |
| 432 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 433 | def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 434 | prefix=template, dir=None, delete=True): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 435 | """Create and return a temporary file. |
| 436 | Arguments: |
| 437 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
| 438 | 'mode' -- the mode argument to os.fdopen (default "w+b"). |
| 439 | 'bufsize' -- the buffer size argument to os.fdopen (default -1). |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 440 | 'delete' -- whether the file is deleted on close (default True). |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 441 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 442 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 443 | Returns an object with a file-like interface; the name of the file |
| 444 | is accessible as file.name. The file will be automatically deleted |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 445 | when it is closed unless the 'delete' argument is set to False. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 446 | """ |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 447 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 448 | if dir is None: |
| 449 | dir = gettempdir() |
| 450 | |
Tim Peters | c21ea74 | 2002-08-13 23:36:01 +0000 | [diff] [blame] | 451 | if 'b' in mode: |
| 452 | flags = _bin_openflags |
| 453 | else: |
| 454 | flags = _text_openflags |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 455 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 456 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 457 | # the file when it is closed. This is only supported by Windows. |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 458 | if _os.name == 'nt' and delete: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 459 | flags |= _os.O_TEMPORARY |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 460 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 461 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
| 462 | file = _os.fdopen(fd, mode, bufsize) |
Georg Brandl | 35ef9c1 | 2007-03-13 18:31:49 +0000 | [diff] [blame] | 463 | return _TemporaryFileWrapper(file, name, delete) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 464 | |
Jason Tishler | 80c02af | 2002-08-14 15:10:09 +0000 | [diff] [blame] | 465 | if _os.name != 'posix' or _os.sys.platform == 'cygwin': |
| 466 | # On non-POSIX and Cygwin systems, assume that we cannot unlink a file |
| 467 | # while it is open. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 468 | TemporaryFile = NamedTemporaryFile |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 469 | |
| 470 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 471 | def TemporaryFile(mode='w+b', bufsize=-1, suffix="", |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 472 | prefix=template, dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 473 | """Create and return a temporary file. |
| 474 | Arguments: |
Neal Norwitz | 946aea2 | 2006-06-16 04:31:06 +0000 | [diff] [blame] | 475 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 476 | 'mode' -- the mode argument to os.fdopen (default "w+b"). |
| 477 | 'bufsize' -- the buffer size argument to os.fdopen (default -1). |
| 478 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 479 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 480 | Returns an object with a file-like interface. The file has no |
| 481 | name, and will cease to exist when it is closed. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 482 | """ |
| 483 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 484 | if dir is None: |
| 485 | dir = gettempdir() |
| 486 | |
Tim Peters | c21ea74 | 2002-08-13 23:36:01 +0000 | [diff] [blame] | 487 | if 'b' in mode: |
| 488 | flags = _bin_openflags |
| 489 | else: |
| 490 | flags = _text_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 491 | |
| 492 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
| 493 | try: |
| 494 | _os.unlink(name) |
| 495 | return _os.fdopen(fd, mode, bufsize) |
| 496 | except: |
| 497 | _os.close(fd) |
| 498 | raise |
Collin Winter | a8785cc | 2007-03-19 18:52:08 +0000 | [diff] [blame] | 499 | |
| 500 | class SpooledTemporaryFile: |
| 501 | """Temporary file wrapper, specialized to switch from |
| 502 | StringIO to a real file when it exceeds a certain size or |
| 503 | when a fileno is needed. |
| 504 | """ |
| 505 | _rolled = False |
| 506 | |
| 507 | def __init__(self, max_size=0, mode='w+b', bufsize=-1, |
| 508 | suffix="", prefix=template, dir=None): |
| 509 | self._file = _StringIO() |
| 510 | self._max_size = max_size |
| 511 | self._rolled = False |
| 512 | self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir) |
| 513 | |
| 514 | def _check(self, file): |
| 515 | if self._rolled: return |
| 516 | max_size = self._max_size |
| 517 | if max_size and file.tell() > max_size: |
| 518 | self.rollover() |
| 519 | |
| 520 | def rollover(self): |
| 521 | if self._rolled: return |
| 522 | file = self._file |
| 523 | newfile = self._file = TemporaryFile(*self._TemporaryFileArgs) |
| 524 | del self._TemporaryFileArgs |
| 525 | |
| 526 | newfile.write(file.getvalue()) |
| 527 | newfile.seek(file.tell(), 0) |
| 528 | |
| 529 | self._rolled = True |
Neal Norwitz | 0d4c06e | 2007-04-25 06:30:05 +0000 | [diff] [blame] | 530 | |
Nick Coghlan | 97fac3e | 2008-02-09 15:28:09 +0000 | [diff] [blame] | 531 | # The method caching trick from NamedTemporaryFile |
| 532 | # won't work here, because _file may change from a |
| 533 | # _StringIO instance to a real file. So we list |
| 534 | # all the methods directly. |
| 535 | |
| 536 | # Context management protocol |
| 537 | def __enter__(self): |
| 538 | if self._file.closed: |
| 539 | raise ValueError("Cannot enter context with closed file") |
| 540 | return self |
| 541 | |
| 542 | def __exit__(self, exc, value, tb): |
| 543 | self._file.close() |
| 544 | |
Collin Winter | a8785cc | 2007-03-19 18:52:08 +0000 | [diff] [blame] | 545 | # file protocol |
| 546 | def __iter__(self): |
| 547 | return self._file.__iter__() |
| 548 | |
| 549 | def close(self): |
| 550 | self._file.close() |
| 551 | |
| 552 | @property |
| 553 | def closed(self): |
| 554 | return self._file.closed |
| 555 | |
| 556 | @property |
| 557 | def encoding(self): |
| 558 | return self._file.encoding |
| 559 | |
| 560 | def fileno(self): |
| 561 | self.rollover() |
| 562 | return self._file.fileno() |
| 563 | |
| 564 | def flush(self): |
| 565 | self._file.flush() |
| 566 | |
| 567 | def isatty(self): |
| 568 | return self._file.isatty() |
| 569 | |
| 570 | @property |
| 571 | def mode(self): |
| 572 | return self._file.mode |
| 573 | |
| 574 | @property |
| 575 | def name(self): |
| 576 | return self._file.name |
| 577 | |
| 578 | @property |
| 579 | def newlines(self): |
| 580 | return self._file.newlines |
| 581 | |
| 582 | def next(self): |
| 583 | return self._file.next |
| 584 | |
| 585 | def read(self, *args): |
| 586 | return self._file.read(*args) |
| 587 | |
| 588 | def readline(self, *args): |
| 589 | return self._file.readline(*args) |
| 590 | |
| 591 | def readlines(self, *args): |
| 592 | return self._file.readlines(*args) |
| 593 | |
| 594 | def seek(self, *args): |
| 595 | self._file.seek(*args) |
| 596 | |
| 597 | @property |
| 598 | def softspace(self): |
| 599 | return self._file.softspace |
| 600 | |
| 601 | def tell(self): |
| 602 | return self._file.tell() |
| 603 | |
| 604 | def truncate(self): |
| 605 | self._file.truncate() |
| 606 | |
| 607 | def write(self, s): |
| 608 | file = self._file |
| 609 | rv = file.write(s) |
| 610 | self._check(file) |
| 611 | return rv |
| 612 | |
| 613 | def writelines(self, iterable): |
| 614 | file = self._file |
| 615 | rv = file.writelines(iterable) |
| 616 | self._check(file) |
| 617 | return rv |
| 618 | |
| 619 | def xreadlines(self, *args): |
| 620 | return self._file.xreadlines(*args) |