Calculate the default directory to use for temporary files. This routine should be called exactly once. We determine whether or not a candidate temp dir is usable by trying to create and write to a file in that directory. If this is successful, the test file is deleted. To prevent
(dirlist=None)
| 181 | return dirlist |
| 182 | |
| 183 | def _get_default_tempdir(dirlist=None): |
| 184 | """Calculate the default directory to use for temporary files. |
| 185 | This routine should be called exactly once. |
| 186 | |
| 187 | We determine whether or not a candidate temp dir is usable by |
| 188 | trying to create and write to a file in that directory. If this |
| 189 | is successful, the test file is deleted. To prevent denial of |
| 190 | service, the name of the test file must be randomized.""" |
| 191 | |
| 192 | namer = _RandomNameSequence() |
| 193 | if dirlist is None: |
| 194 | dirlist = _candidate_tempdir_list() |
| 195 | |
| 196 | for dir in dirlist: |
| 197 | if dir != _os.curdir: |
| 198 | dir = _os.path.abspath(dir) |
| 199 | # Try only a few names per directory. |
| 200 | for seq in range(100): |
| 201 | name = next(namer) |
| 202 | filename = _os.path.join(dir, name) |
| 203 | try: |
| 204 | fd = _os.open(filename, _bin_openflags, 0o600) |
| 205 | try: |
| 206 | try: |
| 207 | _os.write(fd, b'blat') |
| 208 | finally: |
| 209 | _os.close(fd) |
| 210 | finally: |
| 211 | _os.unlink(filename) |
| 212 | return dir |
| 213 | except FileExistsError: |
| 214 | pass |
| 215 | except PermissionError: |
| 216 | # This exception is thrown when a directory with the chosen name |
| 217 | # already exists on windows. |
| 218 | if (_os.name == 'nt' and _os.path.isdir(dir) and |
| 219 | _os.access(dir, _os.W_OK)): |
| 220 | continue |
| 221 | break # no point trying more names in this directory |
| 222 | except OSError: |
| 223 | break # no point trying more names in this directory |
| 224 | raise FileNotFoundError(_errno.ENOENT, |
| 225 | "No usable temporary directory found in %s" % |
| 226 | dirlist) |
| 227 | |
| 228 | _name_sequence = None |
| 229 |
no test coverage detected