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