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. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 13 | tempdir - If this is set to a string before the first use of |
| 14 | any routine from this module, it will be considered as |
| 15 | another candidate location to store temporary files. |
| 16 | """ |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 17 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 18 | __all__ = [ |
| 19 | "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 20 | "SpooledTemporaryFile", "TemporaryDirectory", |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 21 | "mkstemp", "mkdtemp", # low level safe interfaces |
| 22 | "mktemp", # deprecated unsafe interface |
| 23 | "TMP_MAX", "gettempprefix", # constants |
| 24 | "tempdir", "gettempdir" |
| 25 | ] |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 26 | |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 27 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 28 | # Imports. |
Tim Peters | 4fd5a06 | 2002-01-28 23:11:23 +0000 | [diff] [blame] | 29 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 30 | import warnings as _warnings |
| 31 | import sys as _sys |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 32 | import io as _io |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 33 | import os as _os |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 34 | from random import Random as _Random |
| 35 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 36 | try: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 37 | import fcntl as _fcntl |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 38 | except ImportError: |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 39 | def _set_cloexec(fd): |
| 40 | pass |
| 41 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 42 | def _set_cloexec(fd): |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 43 | try: |
| 44 | flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 45 | except OSError: |
Tim Peters | 90ee7eb | 2004-07-18 23:58:17 +0000 | [diff] [blame] | 46 | pass |
Alex Martelli | f09994e | 2003-11-09 16:44:09 +0000 | [diff] [blame] | 47 | else: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 48 | # flags read successfully, modify |
| 49 | flags |= _fcntl.FD_CLOEXEC |
| 50 | _fcntl.fcntl(fd, _fcntl.F_SETFD, flags) |
Tim Peters | 291f14e | 2003-07-22 02:50:01 +0000 | [diff] [blame] | 51 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 52 | |
| 53 | try: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 54 | import _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 55 | except ImportError: |
Georg Brandl | 2067bfd | 2008-05-25 13:05:15 +0000 | [diff] [blame] | 56 | import _dummy_thread as _thread |
Guido van Rossum | a093424 | 2002-12-30 22:36:09 +0000 | [diff] [blame] | 57 | _allocate_lock = _thread.allocate_lock |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 58 | |
| 59 | _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 60 | if hasattr(_os, 'O_NOINHERIT'): |
| 61 | _text_openflags |= _os.O_NOINHERIT |
| 62 | if hasattr(_os, 'O_NOFOLLOW'): |
| 63 | _text_openflags |= _os.O_NOFOLLOW |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 64 | |
| 65 | _bin_openflags = _text_openflags |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 66 | if hasattr(_os, 'O_BINARY'): |
| 67 | _bin_openflags |= _os.O_BINARY |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 68 | |
| 69 | if hasattr(_os, 'TMP_MAX'): |
| 70 | TMP_MAX = _os.TMP_MAX |
| 71 | else: |
| 72 | TMP_MAX = 10000 |
| 73 | |
R David Murray | 3a420c7 | 2011-06-22 21:01:13 -0400 | [diff] [blame] | 74 | # Although it does not have an underscore for historical reasons, this |
| 75 | # variable is an internal implementation detail (see issue 10354). |
Tim Peters | bd7b4c7 | 2002-08-13 23:33:56 +0000 | [diff] [blame] | 76 | template = "tmp" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 77 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 78 | # Internal routines. |
| 79 | |
| 80 | _once_lock = _allocate_lock() |
| 81 | |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 82 | if hasattr(_os, "lstat"): |
| 83 | _stat = _os.lstat |
| 84 | elif hasattr(_os, "stat"): |
| 85 | _stat = _os.stat |
| 86 | else: |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 87 | # Fallback. All we need is something that raises OSError if the |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 88 | # file doesn't exist. |
| 89 | def _stat(fn): |
Florent Xicluna | 46f5d14 | 2011-10-28 21:58:56 +0200 | [diff] [blame] | 90 | f = open(fn) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 91 | f.close() |
| 92 | |
| 93 | def _exists(fn): |
| 94 | try: |
| 95 | _stat(fn) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 96 | except OSError: |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 97 | return False |
| 98 | else: |
| 99 | return True |
| 100 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 101 | class _RandomNameSequence: |
| 102 | """An instance of _RandomNameSequence generates an endless |
| 103 | sequence of unpredictable strings which can safely be incorporated |
| 104 | into file names. Each string is six characters long. Multiple |
| 105 | threads can safely use the same instance at the same time. |
| 106 | |
| 107 | _RandomNameSequence is an iterator.""" |
| 108 | |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 109 | characters = "abcdefghijklmnopqrstuvwxyz0123456789_" |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 110 | |
Antoine Pitrou | 4558bad | 2011-11-25 21:28:15 +0100 | [diff] [blame] | 111 | @property |
| 112 | def rng(self): |
| 113 | cur_pid = _os.getpid() |
| 114 | if cur_pid != getattr(self, '_rng_pid', None): |
| 115 | self._rng = _Random() |
| 116 | self._rng_pid = cur_pid |
| 117 | return self._rng |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 118 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 119 | def __iter__(self): |
| 120 | return self |
| 121 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 122 | def __next__(self): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 123 | c = self.characters |
Tim Peters | 97701b5 | 2002-11-21 15:59:59 +0000 | [diff] [blame] | 124 | choose = self.rng.choice |
Raymond Hettinger | 572895b | 2010-11-09 03:43:58 +0000 | [diff] [blame] | 125 | letters = [choose(c) for dummy in "123456"] |
| 126 | return ''.join(letters) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 127 | |
| 128 | def _candidate_tempdir_list(): |
| 129 | """Generate a list of candidate temporary directories which |
| 130 | _get_default_tempdir will try.""" |
| 131 | |
| 132 | dirlist = [] |
| 133 | |
| 134 | # First, try the environment. |
| 135 | for envname in 'TMPDIR', 'TEMP', 'TMP': |
| 136 | dirname = _os.getenv(envname) |
| 137 | if dirname: dirlist.append(dirname) |
| 138 | |
| 139 | # Failing that, try OS-specific locations. |
Alexandre Vassalotti | eca20b6 | 2008-05-16 02:54:33 +0000 | [diff] [blame] | 140 | if _os.name == 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 141 | dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ]) |
| 142 | else: |
| 143 | dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ]) |
| 144 | |
| 145 | # As a last resort, the current directory. |
| 146 | try: |
| 147 | dirlist.append(_os.getcwd()) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 148 | except (AttributeError, OSError): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 149 | dirlist.append(_os.curdir) |
| 150 | |
| 151 | return dirlist |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 152 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 153 | def _get_default_tempdir(): |
| 154 | """Calculate the default directory to use for temporary files. |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 155 | This routine should be called exactly once. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 156 | |
| 157 | We determine whether or not a candidate temp dir is usable by |
| 158 | trying to create and write to a file in that directory. If this |
| 159 | is successful, the test file is deleted. To prevent denial of |
| 160 | service, the name of the test file must be randomized.""" |
| 161 | |
| 162 | namer = _RandomNameSequence() |
| 163 | dirlist = _candidate_tempdir_list() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 164 | |
| 165 | for dir in dirlist: |
| 166 | if dir != _os.curdir: |
| 167 | dir = _os.path.normcase(_os.path.abspath(dir)) |
| 168 | # Try only a few names per directory. |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 169 | for seq in range(100): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 170 | name = next(namer) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 171 | filename = _os.path.join(dir, name) |
| 172 | try: |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 173 | fd = _os.open(filename, _bin_openflags, 0o600) |
Guido van Rossum | 5424df2 | 2007-08-13 19:06:38 +0000 | [diff] [blame] | 174 | fp = _io.open(fd, 'wb') |
| 175 | fp.write(b'blat') |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 176 | fp.close() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 177 | _os.unlink(filename) |
| 178 | del fp, fd |
| 179 | return dir |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 180 | except FileExistsError: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 181 | pass |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 182 | except OSError: |
| 183 | break # no point trying more names in this directory |
| 184 | raise FileNotFoundError("No usable temporary directory found in %s" % dirlist) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 185 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 186 | _name_sequence = None |
| 187 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 188 | def _get_candidate_names(): |
| 189 | """Common setup sequence for all user-callable interfaces.""" |
| 190 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 191 | global _name_sequence |
| 192 | if _name_sequence is None: |
| 193 | _once_lock.acquire() |
| 194 | try: |
| 195 | if _name_sequence is None: |
| 196 | _name_sequence = _RandomNameSequence() |
| 197 | finally: |
| 198 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 199 | return _name_sequence |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 200 | |
| 201 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 202 | def _mkstemp_inner(dir, pre, suf, flags): |
| 203 | """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.""" |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 204 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 205 | names = _get_candidate_names() |
| 206 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 207 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 208 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 209 | file = _os.path.join(dir, pre + name + suf) |
| 210 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 211 | fd = _os.open(file, flags, 0o600) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 212 | _set_cloexec(fd) |
Martin v. Löwis | d662548 | 2003-10-12 17:37:01 +0000 | [diff] [blame] | 213 | return (fd, _os.path.abspath(file)) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 214 | except FileExistsError: |
| 215 | continue # try again |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 216 | |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 217 | raise FileExistsError("No usable temporary file name found") |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 218 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 219 | |
| 220 | # User visible interfaces. |
Guido van Rossum | b0e5718 | 1998-10-14 20:27:05 +0000 | [diff] [blame] | 221 | |
Guido van Rossum | 41f9503 | 1992-03-31 19:02:01 +0000 | [diff] [blame] | 222 | def gettempprefix(): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 223 | """Accessor for tempdir.template.""" |
| 224 | return template |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 225 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 226 | tempdir = None |
| 227 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 228 | def gettempdir(): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 229 | """Accessor for tempfile.tempdir.""" |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 230 | global tempdir |
| 231 | if tempdir is None: |
| 232 | _once_lock.acquire() |
| 233 | try: |
| 234 | if tempdir is None: |
| 235 | tempdir = _get_default_tempdir() |
| 236 | finally: |
| 237 | _once_lock.release() |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 238 | return tempdir |
| 239 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 240 | def mkstemp(suffix="", prefix=template, dir=None, text=False): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 241 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 242 | file. The return value is a pair (fd, name) where fd is the |
| 243 | file descriptor returned by os.open, and name is the filename. |
| 244 | |
| 245 | If 'suffix' is specified, the file name will end with that suffix, |
| 246 | otherwise there will be no suffix. |
| 247 | |
| 248 | If 'prefix' is specified, the file name will begin with that prefix, |
| 249 | otherwise a default prefix is used. |
| 250 | |
| 251 | If 'dir' is specified, the file will be created in that directory, |
| 252 | otherwise a default directory is used. |
| 253 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 254 | If 'text' is specified and true, the file is opened in text |
| 255 | mode. Else (the default) the file is opened in binary mode. On |
| 256 | some operating systems, this makes no difference. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 257 | |
| 258 | The file is readable and writable only by the creating user ID. |
| 259 | If the operating system uses permission bits to indicate whether a |
| 260 | file is executable, the file is executable by no one. The file |
| 261 | descriptor is not inherited by children of this process. |
| 262 | |
| 263 | Caller is responsible for deleting the file when done with it. |
Tim Peters | 9fadfb0 | 2001-01-13 03:04:02 +0000 | [diff] [blame] | 264 | """ |
| 265 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 266 | if dir is None: |
| 267 | dir = gettempdir() |
| 268 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 269 | if text: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 270 | flags = _text_openflags |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 271 | else: |
| 272 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 273 | |
| 274 | return _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | cff3454 | 1992-01-14 18:31:56 +0000 | [diff] [blame] | 275 | |
Guido van Rossum | eee9498 | 1991-11-12 15:38:08 +0000 | [diff] [blame] | 276 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 277 | def mkdtemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 278 | """User-callable function to create and return a unique temporary |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 279 | directory. The return value is the pathname of the directory. |
| 280 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 281 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 282 | not accepted. |
| 283 | |
| 284 | The directory is readable, writable, and searchable only by the |
| 285 | creating user. |
| 286 | |
| 287 | Caller is responsible for deleting the directory when done with it. |
| 288 | """ |
| 289 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 290 | if dir is None: |
| 291 | dir = gettempdir() |
| 292 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 293 | names = _get_candidate_names() |
Tim Peters | a0d55de | 2002-08-09 18:01:01 +0000 | [diff] [blame] | 294 | |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 295 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 296 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 297 | file = _os.path.join(dir, prefix + name + suffix) |
| 298 | try: |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 299 | _os.mkdir(file, 0o700) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 300 | return file |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 301 | except FileExistsError: |
| 302 | continue # try again |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 303 | |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 304 | raise FileExistsError("No usable temporary directory name found") |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 305 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 306 | def mktemp(suffix="", prefix=template, dir=None): |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 307 | """User-callable function to return a unique temporary file name. The |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 308 | file is not created. |
| 309 | |
Tim Peters | 04490bf | 2002-08-14 15:41:26 +0000 | [diff] [blame] | 310 | Arguments are as for mkstemp, except that the 'text' argument is |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 311 | not accepted. |
| 312 | |
| 313 | This function is unsafe and should not be used. The file name |
| 314 | refers to a file that did not exist at some point, but by the time |
| 315 | you get around to creating it, someone else may have beaten you to |
| 316 | the punch. |
| 317 | """ |
| 318 | |
Guido van Rossum | 44f602d | 2002-11-22 15:56:29 +0000 | [diff] [blame] | 319 | ## from warnings import warn as _warn |
| 320 | ## _warn("mktemp is a potential security risk to your program", |
| 321 | ## RuntimeWarning, stacklevel=2) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 322 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 323 | if dir is None: |
| 324 | dir = gettempdir() |
| 325 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 326 | names = _get_candidate_names() |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 327 | for seq in range(TMP_MAX): |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 328 | name = next(names) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 329 | file = _os.path.join(dir, prefix + name + suffix) |
Guido van Rossum | b25615939 | 2003-11-10 02:16:36 +0000 | [diff] [blame] | 330 | if not _exists(file): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 331 | return file |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 332 | |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 333 | raise FileExistsError("No usable temporary filename found") |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 334 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 335 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 336 | class _TemporaryFileWrapper: |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 337 | """Temporary file wrapper |
| 338 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 339 | This class provides a wrapper around files opened for |
| 340 | temporary use. In particular, it seeks to automatically |
| 341 | remove the file when it is no longer needed. |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 342 | """ |
Tim Peters | a255a72 | 2001-12-18 22:32:40 +0000 | [diff] [blame] | 343 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 344 | def __init__(self, file, name, delete=True): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 345 | self.file = file |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 346 | self.name = name |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 347 | self.close_called = False |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 348 | self.delete = delete |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 349 | |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 350 | def __getattr__(self, name): |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 351 | # Attribute lookups are delegated to the underlying file |
| 352 | # and cached for non-numeric results |
| 353 | # (i.e. methods are cached, closed and friends are not) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 354 | file = self.__dict__['file'] |
| 355 | a = getattr(file, name) |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 356 | if not isinstance(a, int): |
Guido van Rossum | 6b708d5 | 1999-06-01 18:55:36 +0000 | [diff] [blame] | 357 | setattr(self, name, a) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 358 | return a |
Guido van Rossum | ca54982 | 1997-08-12 18:00:12 +0000 | [diff] [blame] | 359 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 360 | # The underlying __enter__ method returns the wrong object |
| 361 | # (self.file) so override it to return the wrapper |
| 362 | def __enter__(self): |
| 363 | self.file.__enter__() |
| 364 | return self |
| 365 | |
Christian Heimes | 36d1f8e | 2008-02-28 22:21:11 +0000 | [diff] [blame] | 366 | # iter() doesn't use __getattr__ to find the __iter__ method |
Christian Heimes | c83b629 | 2008-02-28 21:10:17 +0000 | [diff] [blame] | 367 | def __iter__(self): |
Christian Heimes | 36d1f8e | 2008-02-28 22:21:11 +0000 | [diff] [blame] | 368 | return iter(self.file) |
Christian Heimes | c83b629 | 2008-02-28 21:10:17 +0000 | [diff] [blame] | 369 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 370 | # NT provides delete-on-close as a primitive, so we don't need |
| 371 | # the wrapper to do anything special. We still use it so that |
| 372 | # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile. |
| 373 | if _os.name != 'nt': |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 374 | # Cache the unlinker so we don't get spurious errors at |
| 375 | # shutdown when the module-level "os" is None'd out. Note |
| 376 | # that this must be referenced as self.unlink, because the |
| 377 | # name TemporaryFileWrapper may also get None'd out before |
| 378 | # __del__ is called. |
| 379 | unlink = _os.unlink |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 380 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 381 | def close(self): |
| 382 | if not self.close_called: |
Tim Peters | 6ef966e | 2002-11-21 15:48:33 +0000 | [diff] [blame] | 383 | self.close_called = True |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 384 | self.file.close() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 385 | if self.delete: |
| 386 | self.unlink(self.name) |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 387 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 388 | def __del__(self): |
| 389 | self.close() |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 390 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 391 | # Need to trap __exit__ as well to ensure the file gets |
| 392 | # deleted when used in a with statement |
| 393 | def __exit__(self, exc, value, tb): |
| 394 | result = self.file.__exit__(exc, value, tb) |
| 395 | self.close() |
| 396 | return result |
Benjamin Peterson | 98d23f2 | 2009-06-30 22:27:25 +0000 | [diff] [blame] | 397 | else: |
| 398 | def __exit__(self, exc, value, tb): |
Benjamin Peterson | 3f5de13 | 2009-07-01 15:47:07 +0000 | [diff] [blame] | 399 | self.file.__exit__(exc, value, tb) |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 400 | |
| 401 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 402 | def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 403 | newline=None, suffix="", prefix=template, |
| 404 | dir=None, delete=True): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 405 | """Create and return a temporary file. |
| 406 | Arguments: |
| 407 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 408 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 409 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 410 | 'encoding' -- the encoding argument to io.open (default None) |
| 411 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 412 | 'delete' -- whether the file is deleted on close (default True). |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 413 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 414 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 415 | Returns an object with a file-like interface; the name of the file |
| 416 | is accessible as file.name. The file will be automatically deleted |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 417 | 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] | 418 | """ |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 419 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 420 | if dir is None: |
| 421 | dir = gettempdir() |
| 422 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 423 | flags = _bin_openflags |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 424 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 425 | # Setting O_TEMPORARY in the flags causes the OS to delete |
| 426 | # the file when it is closed. This is only supported by Windows. |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 427 | if _os.name == 'nt' and delete: |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 428 | flags |= _os.O_TEMPORARY |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 429 | |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 430 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 431 | file = _io.open(fd, mode, buffering=buffering, |
| 432 | newline=newline, encoding=encoding) |
| 433 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 434 | return _TemporaryFileWrapper(file, name, delete) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 435 | |
Jason Tishler | 80c02af | 2002-08-14 15:10:09 +0000 | [diff] [blame] | 436 | if _os.name != 'posix' or _os.sys.platform == 'cygwin': |
| 437 | # On non-POSIX and Cygwin systems, assume that we cannot unlink a file |
| 438 | # while it is open. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 439 | TemporaryFile = NamedTemporaryFile |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 440 | |
| 441 | else: |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 442 | def TemporaryFile(mode='w+b', buffering=-1, encoding=None, |
| 443 | newline=None, suffix="", prefix=template, |
| 444 | dir=None): |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 445 | """Create and return a temporary file. |
| 446 | Arguments: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 447 | 'prefix', 'suffix', 'dir' -- as for mkstemp. |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 448 | 'mode' -- the mode argument to io.open (default "w+b"). |
| 449 | 'buffering' -- the buffer size argument to io.open (default -1). |
| 450 | 'encoding' -- the encoding argument to io.open (default None) |
| 451 | 'newline' -- the newline argument to io.open (default None) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 452 | The file is created as mkstemp() would do it. |
Tim Peters | 1baa22a | 2001-01-12 10:02:46 +0000 | [diff] [blame] | 453 | |
Raymond Hettinger | faa10eb | 2005-01-11 15:33:03 +0000 | [diff] [blame] | 454 | Returns an object with a file-like interface. The file has no |
| 455 | name, and will cease to exist when it is closed. |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 456 | """ |
| 457 | |
Guido van Rossum | e888cdc | 2002-08-17 14:50:24 +0000 | [diff] [blame] | 458 | if dir is None: |
| 459 | dir = gettempdir() |
| 460 | |
Amaury Forgeot d'Arc | 7d0bddd | 2009-11-30 00:08:56 +0000 | [diff] [blame] | 461 | flags = _bin_openflags |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 462 | |
| 463 | (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags) |
| 464 | try: |
| 465 | _os.unlink(name) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 466 | return _io.open(fd, mode, buffering=buffering, |
| 467 | newline=newline, encoding=encoding) |
Guido van Rossum | 0e54871 | 2002-08-09 16:14:33 +0000 | [diff] [blame] | 468 | except: |
| 469 | _os.close(fd) |
| 470 | raise |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 471 | |
| 472 | class SpooledTemporaryFile: |
| 473 | """Temporary file wrapper, specialized to switch from |
| 474 | StringIO to a real file when it exceeds a certain size or |
| 475 | when a fileno is needed. |
| 476 | """ |
| 477 | _rolled = False |
| 478 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 479 | def __init__(self, max_size=0, mode='w+b', buffering=-1, |
| 480 | encoding=None, newline=None, |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 481 | suffix="", prefix=template, dir=None): |
Guido van Rossum | 9a63470 | 2007-07-09 10:24:45 +0000 | [diff] [blame] | 482 | if 'b' in mode: |
| 483 | self._file = _io.BytesIO() |
| 484 | else: |
Guido van Rossum | 5d21255 | 2007-10-29 16:42:51 +0000 | [diff] [blame] | 485 | # Setting newline="\n" avoids newline translation; |
| 486 | # this is important because otherwise on Windows we'd |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 487 | # hget double newline translation upon rollover(). |
Alexandre Vassalotti | 3ade6f9 | 2008-06-12 01:13:54 +0000 | [diff] [blame] | 488 | self._file = _io.StringIO(newline="\n") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 489 | self._max_size = max_size |
| 490 | self._rolled = False |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 491 | self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering, |
| 492 | 'suffix': suffix, 'prefix': prefix, |
| 493 | 'encoding': encoding, 'newline': newline, |
| 494 | 'dir': dir} |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 495 | |
| 496 | def _check(self, file): |
| 497 | if self._rolled: return |
| 498 | max_size = self._max_size |
| 499 | if max_size and file.tell() > max_size: |
| 500 | self.rollover() |
| 501 | |
| 502 | def rollover(self): |
| 503 | if self._rolled: return |
| 504 | file = self._file |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 505 | newfile = self._file = TemporaryFile(**self._TemporaryFileArgs) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 506 | del self._TemporaryFileArgs |
| 507 | |
| 508 | newfile.write(file.getvalue()) |
| 509 | newfile.seek(file.tell(), 0) |
| 510 | |
| 511 | self._rolled = True |
| 512 | |
Christian Heimes | 3ecfea71 | 2008-02-09 20:51:34 +0000 | [diff] [blame] | 513 | # The method caching trick from NamedTemporaryFile |
| 514 | # won't work here, because _file may change from a |
| 515 | # _StringIO instance to a real file. So we list |
| 516 | # all the methods directly. |
| 517 | |
| 518 | # Context management protocol |
| 519 | def __enter__(self): |
| 520 | if self._file.closed: |
| 521 | raise ValueError("Cannot enter context with closed file") |
| 522 | return self |
| 523 | |
| 524 | def __exit__(self, exc, value, tb): |
| 525 | self._file.close() |
| 526 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 527 | # file protocol |
| 528 | def __iter__(self): |
| 529 | return self._file.__iter__() |
| 530 | |
| 531 | def close(self): |
| 532 | self._file.close() |
| 533 | |
| 534 | @property |
| 535 | def closed(self): |
| 536 | return self._file.closed |
| 537 | |
| 538 | @property |
| 539 | def encoding(self): |
| 540 | return self._file.encoding |
| 541 | |
| 542 | def fileno(self): |
| 543 | self.rollover() |
| 544 | return self._file.fileno() |
| 545 | |
| 546 | def flush(self): |
| 547 | self._file.flush() |
| 548 | |
| 549 | def isatty(self): |
| 550 | return self._file.isatty() |
| 551 | |
| 552 | @property |
| 553 | def mode(self): |
| 554 | return self._file.mode |
| 555 | |
| 556 | @property |
| 557 | def name(self): |
| 558 | return self._file.name |
| 559 | |
| 560 | @property |
| 561 | def newlines(self): |
| 562 | return self._file.newlines |
| 563 | |
| 564 | def next(self): |
| 565 | return self._file.next |
| 566 | |
| 567 | def read(self, *args): |
| 568 | return self._file.read(*args) |
| 569 | |
| 570 | def readline(self, *args): |
| 571 | return self._file.readline(*args) |
| 572 | |
| 573 | def readlines(self, *args): |
| 574 | return self._file.readlines(*args) |
| 575 | |
| 576 | def seek(self, *args): |
| 577 | self._file.seek(*args) |
| 578 | |
| 579 | @property |
| 580 | def softspace(self): |
| 581 | return self._file.softspace |
| 582 | |
| 583 | def tell(self): |
| 584 | return self._file.tell() |
| 585 | |
Antoine Pitrou | 0e86a58 | 2011-11-25 18:03:09 +0100 | [diff] [blame] | 586 | def truncate(self, size=None): |
| 587 | if size is None: |
| 588 | self._file.truncate() |
| 589 | else: |
| 590 | if size > self._max_size: |
| 591 | self.rollover() |
| 592 | self._file.truncate(size) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 593 | |
| 594 | def write(self, s): |
| 595 | file = self._file |
| 596 | rv = file.write(s) |
| 597 | self._check(file) |
| 598 | return rv |
| 599 | |
| 600 | def writelines(self, iterable): |
| 601 | file = self._file |
| 602 | rv = file.writelines(iterable) |
| 603 | self._check(file) |
| 604 | return rv |
| 605 | |
| 606 | def xreadlines(self, *args): |
| 607 | return self._file.xreadlines(*args) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 608 | |
| 609 | |
| 610 | class TemporaryDirectory(object): |
| 611 | """Create and return a temporary directory. This has the same |
| 612 | behavior as mkdtemp but can be used as a context manager. For |
| 613 | example: |
| 614 | |
| 615 | with TemporaryDirectory() as tmpdir: |
| 616 | ... |
| 617 | |
| 618 | Upon exiting the context, the directory and everthing contained |
| 619 | in it are removed. |
| 620 | """ |
| 621 | |
| 622 | def __init__(self, suffix="", prefix=template, dir=None): |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 623 | self._closed = False |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 624 | self.name = None # Handle mkdtemp throwing an exception |
| 625 | self.name = mkdtemp(suffix, prefix, dir) |
| 626 | |
| 627 | def __repr__(self): |
| 628 | return "<{} {!r}>".format(self.__class__.__name__, self.name) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 629 | |
| 630 | def __enter__(self): |
| 631 | return self.name |
| 632 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 633 | def cleanup(self, _warn=False): |
| 634 | if self.name and not self._closed: |
| 635 | try: |
| 636 | self._rmtree(self.name) |
| 637 | except (TypeError, AttributeError) as ex: |
| 638 | # Issue #10188: Emit a warning on stderr |
| 639 | # if the directory could not be cleaned |
| 640 | # up due to missing globals |
| 641 | if "None" not in str(ex): |
| 642 | raise |
| 643 | print("ERROR: {!r} while cleaning up {!r}".format(ex, self,), |
| 644 | file=_sys.stderr) |
| 645 | return |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 646 | self._closed = True |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 647 | if _warn: |
| 648 | self._warn("Implicitly cleaning up {!r}".format(self), |
| 649 | ResourceWarning) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 650 | |
| 651 | def __exit__(self, exc, value, tb): |
| 652 | self.cleanup() |
| 653 | |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 654 | def __del__(self): |
| 655 | # Issue a ResourceWarning if implicit cleanup needed |
| 656 | self.cleanup(_warn=True) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 657 | |
| 658 | # XXX (ncoghlan): The following code attempts to make |
| 659 | # this class tolerant of the module nulling out process |
| 660 | # that happens during CPython interpreter shutdown |
| 661 | # Alas, it doesn't actually manage it. See issue #10188 |
| 662 | _listdir = staticmethod(_os.listdir) |
| 663 | _path_join = staticmethod(_os.path.join) |
| 664 | _isdir = staticmethod(_os.path.isdir) |
Charles-François Natali | def3543 | 2011-07-29 18:59:24 +0200 | [diff] [blame] | 665 | _islink = staticmethod(_os.path.islink) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 666 | _remove = staticmethod(_os.remove) |
| 667 | _rmdir = staticmethod(_os.rmdir) |
Florent Xicluna | 68f71a3 | 2011-10-28 16:06:23 +0200 | [diff] [blame] | 668 | _os_error = OSError |
Nick Coghlan | 6b22f3f | 2010-12-12 15:24:21 +0000 | [diff] [blame] | 669 | _warn = _warnings.warn |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 670 | |
| 671 | def _rmtree(self, path): |
| 672 | # Essentially a stripped down version of shutil.rmtree. We can't |
| 673 | # use globals because they may be None'ed out at shutdown. |
| 674 | for name in self._listdir(path): |
| 675 | fullname = self._path_join(path, name) |
| 676 | try: |
Charles-François Natali | def3543 | 2011-07-29 18:59:24 +0200 | [diff] [blame] | 677 | isdir = self._isdir(fullname) and not self._islink(fullname) |
Nick Coghlan | 543af75 | 2010-10-24 11:23:25 +0000 | [diff] [blame] | 678 | except self._os_error: |
| 679 | isdir = False |
| 680 | if isdir: |
| 681 | self._rmtree(fullname) |
| 682 | else: |
| 683 | try: |
| 684 | self._remove(fullname) |
| 685 | except self._os_error: |
| 686 | pass |
| 687 | try: |
| 688 | self._rmdir(path) |
| 689 | except self._os_error: |
| 690 | pass |