tempfile.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. """Temporary files.
  2. This module provides generic, low- and high-level interfaces for
  3. creating temporary files and directories. All of the interfaces
  4. provided by this module can be used without fear of race conditions
  5. except for 'mktemp'. 'mktemp' is subject to race conditions and
  6. should not be used; it is provided for backward compatibility only.
  7. The default path names are returned as str. If you supply bytes as
  8. input, all return values will be in bytes. Ex:
  9. >>> tempfile.mkstemp()
  10. (4, '/tmp/tmptpu9nin8')
  11. >>> tempfile.mkdtemp(suffix=b'')
  12. b'/tmp/tmppbi8f0hy'
  13. This module also provides some data items to the user:
  14. TMP_MAX - maximum number of names that will be tried before
  15. giving up.
  16. tempdir - If this is set to a string before the first use of
  17. any routine from this module, it will be considered as
  18. another candidate location to store temporary files.
  19. """
  20. __all__ = [
  21. "NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
  22. "SpooledTemporaryFile", "TemporaryDirectory",
  23. "mkstemp", "mkdtemp", # low level safe interfaces
  24. "mktemp", # deprecated unsafe interface
  25. "TMP_MAX", "gettempprefix", # constants
  26. "tempdir", "gettempdir",
  27. "gettempprefixb", "gettempdirb",
  28. ]
  29. # Imports.
  30. import functools as _functools
  31. import warnings as _warnings
  32. import io as _io
  33. import os as _os
  34. import shutil as _shutil
  35. import errno as _errno
  36. from random import Random as _Random
  37. import sys as _sys
  38. import types as _types
  39. import weakref as _weakref
  40. import _thread
  41. _allocate_lock = _thread.allocate_lock
  42. _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
  43. if hasattr(_os, 'O_NOFOLLOW'):
  44. _text_openflags |= _os.O_NOFOLLOW
  45. _bin_openflags = _text_openflags
  46. if hasattr(_os, 'O_BINARY'):
  47. _bin_openflags |= _os.O_BINARY
  48. if hasattr(_os, 'TMP_MAX'):
  49. TMP_MAX = _os.TMP_MAX
  50. else:
  51. TMP_MAX = 10000
  52. # This variable _was_ unused for legacy reasons, see issue 10354.
  53. # But as of 3.5 we actually use it at runtime so changing it would
  54. # have a possibly desirable side effect... But we do not want to support
  55. # that as an API. It is undocumented on purpose. Do not depend on this.
  56. template = "tmp"
  57. # Internal routines.
  58. _once_lock = _allocate_lock()
  59. def _exists(fn):
  60. try:
  61. _os.lstat(fn)
  62. except OSError:
  63. return False
  64. else:
  65. return True
  66. def _infer_return_type(*args):
  67. """Look at the type of all args and divine their implied return type."""
  68. return_type = None
  69. for arg in args:
  70. if arg is None:
  71. continue
  72. if isinstance(arg, _os.PathLike):
  73. arg = _os.fspath(arg)
  74. if isinstance(arg, bytes):
  75. if return_type is str:
  76. raise TypeError("Can't mix bytes and non-bytes in "
  77. "path components.")
  78. return_type = bytes
  79. else:
  80. if return_type is bytes:
  81. raise TypeError("Can't mix bytes and non-bytes in "
  82. "path components.")
  83. return_type = str
  84. if return_type is None:
  85. return str # tempfile APIs return a str by default.
  86. return return_type
  87. def _sanitize_params(prefix, suffix, dir):
  88. """Common parameter processing for most APIs in this module."""
  89. output_type = _infer_return_type(prefix, suffix, dir)
  90. if suffix is None:
  91. suffix = output_type()
  92. if prefix is None:
  93. if output_type is str:
  94. prefix = template
  95. else:
  96. prefix = _os.fsencode(template)
  97. if dir is None:
  98. if output_type is str:
  99. dir = gettempdir()
  100. else:
  101. dir = gettempdirb()
  102. return prefix, suffix, dir, output_type
  103. class _RandomNameSequence:
  104. """An instance of _RandomNameSequence generates an endless
  105. sequence of unpredictable strings which can safely be incorporated
  106. into file names. Each string is eight characters long. Multiple
  107. threads can safely use the same instance at the same time.
  108. _RandomNameSequence is an iterator."""
  109. characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
  110. @property
  111. def rng(self):
  112. cur_pid = _os.getpid()
  113. if cur_pid != getattr(self, '_rng_pid', None):
  114. self._rng = _Random()
  115. self._rng_pid = cur_pid
  116. return self._rng
  117. def __iter__(self):
  118. return self
  119. def __next__(self):
  120. c = self.characters
  121. choose = self.rng.choice
  122. letters = [choose(c) for dummy in range(8)]
  123. return ''.join(letters)
  124. def _candidate_tempdir_list():
  125. """Generate a list of candidate temporary directories which
  126. _get_default_tempdir will try."""
  127. dirlist = []
  128. # First, try the environment.
  129. for envname in 'TMPDIR', 'TEMP', 'TMP':
  130. dirname = _os.getenv(envname)
  131. if dirname: dirlist.append(dirname)
  132. # Failing that, try OS-specific locations.
  133. if _os.name == 'nt':
  134. dirlist.extend([ _os.path.expanduser(r'~\AppData\Local\Temp'),
  135. _os.path.expandvars(r'%SYSTEMROOT%\Temp'),
  136. r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
  137. else:
  138. dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
  139. # As a last resort, the current directory.
  140. try:
  141. dirlist.append(_os.getcwd())
  142. except (AttributeError, OSError):
  143. dirlist.append(_os.curdir)
  144. return dirlist
  145. def _get_default_tempdir():
  146. """Calculate the default directory to use for temporary files.
  147. This routine should be called exactly once.
  148. We determine whether or not a candidate temp dir is usable by
  149. trying to create and write to a file in that directory. If this
  150. is successful, the test file is deleted. To prevent denial of
  151. service, the name of the test file must be randomized."""
  152. namer = _RandomNameSequence()
  153. dirlist = _candidate_tempdir_list()
  154. for dir in dirlist:
  155. if dir != _os.curdir:
  156. dir = _os.path.abspath(dir)
  157. # Try only a few names per directory.
  158. for seq in range(100):
  159. name = next(namer)
  160. filename = _os.path.join(dir, name)
  161. try:
  162. fd = _os.open(filename, _bin_openflags, 0o600)
  163. try:
  164. try:
  165. with _io.open(fd, 'wb', closefd=False) as fp:
  166. fp.write(b'blat')
  167. finally:
  168. _os.close(fd)
  169. finally:
  170. _os.unlink(filename)
  171. return dir
  172. except FileExistsError:
  173. pass
  174. except PermissionError:
  175. # This exception is thrown when a directory with the chosen name
  176. # already exists on windows.
  177. if (_os.name == 'nt' and _os.path.isdir(dir) and
  178. _os.access(dir, _os.W_OK)):
  179. continue
  180. break # no point trying more names in this directory
  181. except OSError:
  182. break # no point trying more names in this directory
  183. raise FileNotFoundError(_errno.ENOENT,
  184. "No usable temporary directory found in %s" %
  185. dirlist)
  186. _name_sequence = None
  187. def _get_candidate_names():
  188. """Common setup sequence for all user-callable interfaces."""
  189. global _name_sequence
  190. if _name_sequence is None:
  191. _once_lock.acquire()
  192. try:
  193. if _name_sequence is None:
  194. _name_sequence = _RandomNameSequence()
  195. finally:
  196. _once_lock.release()
  197. return _name_sequence
  198. def _mkstemp_inner(dir, pre, suf, flags, output_type):
  199. """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
  200. names = _get_candidate_names()
  201. if output_type is bytes:
  202. names = map(_os.fsencode, names)
  203. for seq in range(TMP_MAX):
  204. name = next(names)
  205. file = _os.path.join(dir, pre + name + suf)
  206. _sys.audit("tempfile.mkstemp", file)
  207. try:
  208. fd = _os.open(file, flags, 0o600)
  209. except FileExistsError:
  210. continue # try again
  211. except PermissionError:
  212. # This exception is thrown when a directory with the chosen name
  213. # already exists on windows.
  214. if (_os.name == 'nt' and _os.path.isdir(dir) and
  215. _os.access(dir, _os.W_OK)):
  216. continue
  217. else:
  218. raise
  219. return (fd, _os.path.abspath(file))
  220. raise FileExistsError(_errno.EEXIST,
  221. "No usable temporary file name found")
  222. # User visible interfaces.
  223. def gettempprefix():
  224. """The default prefix for temporary directories."""
  225. return template
  226. def gettempprefixb():
  227. """The default prefix for temporary directories as bytes."""
  228. return _os.fsencode(gettempprefix())
  229. tempdir = None
  230. def gettempdir():
  231. """Accessor for tempfile.tempdir."""
  232. global tempdir
  233. if tempdir is None:
  234. _once_lock.acquire()
  235. try:
  236. if tempdir is None:
  237. tempdir = _get_default_tempdir()
  238. finally:
  239. _once_lock.release()
  240. return tempdir
  241. def gettempdirb():
  242. """A bytes version of tempfile.gettempdir()."""
  243. return _os.fsencode(gettempdir())
  244. def mkstemp(suffix=None, prefix=None, dir=None, text=False):
  245. """User-callable function to create and return a unique temporary
  246. file. The return value is a pair (fd, name) where fd is the
  247. file descriptor returned by os.open, and name is the filename.
  248. If 'suffix' is not None, the file name will end with that suffix,
  249. otherwise there will be no suffix.
  250. If 'prefix' is not None, the file name will begin with that prefix,
  251. otherwise a default prefix is used.
  252. If 'dir' is not None, the file will be created in that directory,
  253. otherwise a default directory is used.
  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.
  256. If any of 'suffix', 'prefix' and 'dir' are not None, they must be the
  257. same type. If they are bytes, the returned name will be bytes; str
  258. otherwise.
  259. The file is readable and writable only by the creating user ID.
  260. If the operating system uses permission bits to indicate whether a
  261. file is executable, the file is executable by no one. The file
  262. descriptor is not inherited by children of this process.
  263. Caller is responsible for deleting the file when done with it.
  264. """
  265. prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
  266. if text:
  267. flags = _text_openflags
  268. else:
  269. flags = _bin_openflags
  270. return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
  271. def mkdtemp(suffix=None, prefix=None, dir=None):
  272. """User-callable function to create and return a unique temporary
  273. directory. The return value is the pathname of the directory.
  274. Arguments are as for mkstemp, except that the 'text' argument is
  275. not accepted.
  276. The directory is readable, writable, and searchable only by the
  277. creating user.
  278. Caller is responsible for deleting the directory when done with it.
  279. """
  280. prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
  281. names = _get_candidate_names()
  282. if output_type is bytes:
  283. names = map(_os.fsencode, names)
  284. for seq in range(TMP_MAX):
  285. name = next(names)
  286. file = _os.path.join(dir, prefix + name + suffix)
  287. _sys.audit("tempfile.mkdtemp", file)
  288. try:
  289. _os.mkdir(file, 0o700)
  290. except FileExistsError:
  291. continue # try again
  292. except PermissionError:
  293. # This exception is thrown when a directory with the chosen name
  294. # already exists on windows.
  295. if (_os.name == 'nt' and _os.path.isdir(dir) and
  296. _os.access(dir, _os.W_OK)):
  297. continue
  298. else:
  299. raise
  300. return file
  301. raise FileExistsError(_errno.EEXIST,
  302. "No usable temporary directory name found")
  303. def mktemp(suffix="", prefix=template, dir=None):
  304. """User-callable function to return a unique temporary file name. The
  305. file is not created.
  306. Arguments are similar to mkstemp, except that the 'text' argument is
  307. not accepted, and suffix=None, prefix=None and bytes file names are not
  308. supported.
  309. THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
  310. refer to a file that did not exist at some point, but by the time
  311. you get around to creating it, someone else may have beaten you to
  312. the punch.
  313. """
  314. ## from warnings import warn as _warn
  315. ## _warn("mktemp is a potential security risk to your program",
  316. ## RuntimeWarning, stacklevel=2)
  317. if dir is None:
  318. dir = gettempdir()
  319. names = _get_candidate_names()
  320. for seq in range(TMP_MAX):
  321. name = next(names)
  322. file = _os.path.join(dir, prefix + name + suffix)
  323. if not _exists(file):
  324. return file
  325. raise FileExistsError(_errno.EEXIST,
  326. "No usable temporary filename found")
  327. class _TemporaryFileCloser:
  328. """A separate object allowing proper closing of a temporary file's
  329. underlying file object, without adding a __del__ method to the
  330. temporary file."""
  331. file = None # Set here since __del__ checks it
  332. close_called = False
  333. def __init__(self, file, name, delete=True):
  334. self.file = file
  335. self.name = name
  336. self.delete = delete
  337. # NT provides delete-on-close as a primitive, so we don't need
  338. # the wrapper to do anything special. We still use it so that
  339. # file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
  340. if _os.name != 'nt':
  341. # Cache the unlinker so we don't get spurious errors at
  342. # shutdown when the module-level "os" is None'd out. Note
  343. # that this must be referenced as self.unlink, because the
  344. # name TemporaryFileWrapper may also get None'd out before
  345. # __del__ is called.
  346. def close(self, unlink=_os.unlink):
  347. if not self.close_called and self.file is not None:
  348. self.close_called = True
  349. try:
  350. self.file.close()
  351. finally:
  352. if self.delete:
  353. unlink(self.name)
  354. # Need to ensure the file is deleted on __del__
  355. def __del__(self):
  356. self.close()
  357. else:
  358. def close(self):
  359. if not self.close_called:
  360. self.close_called = True
  361. self.file.close()
  362. class _TemporaryFileWrapper:
  363. """Temporary file wrapper
  364. This class provides a wrapper around files opened for
  365. temporary use. In particular, it seeks to automatically
  366. remove the file when it is no longer needed.
  367. """
  368. def __init__(self, file, name, delete=True):
  369. self.file = file
  370. self.name = name
  371. self.delete = delete
  372. self._closer = _TemporaryFileCloser(file, name, delete)
  373. def __getattr__(self, name):
  374. # Attribute lookups are delegated to the underlying file
  375. # and cached for non-numeric results
  376. # (i.e. methods are cached, closed and friends are not)
  377. file = self.__dict__['file']
  378. a = getattr(file, name)
  379. if hasattr(a, '__call__'):
  380. func = a
  381. @_functools.wraps(func)
  382. def func_wrapper(*args, **kwargs):
  383. return func(*args, **kwargs)
  384. # Avoid closing the file as long as the wrapper is alive,
  385. # see issue #18879.
  386. func_wrapper._closer = self._closer
  387. a = func_wrapper
  388. if not isinstance(a, int):
  389. setattr(self, name, a)
  390. return a
  391. # The underlying __enter__ method returns the wrong object
  392. # (self.file) so override it to return the wrapper
  393. def __enter__(self):
  394. self.file.__enter__()
  395. return self
  396. # Need to trap __exit__ as well to ensure the file gets
  397. # deleted when used in a with statement
  398. def __exit__(self, exc, value, tb):
  399. result = self.file.__exit__(exc, value, tb)
  400. self.close()
  401. return result
  402. def close(self):
  403. """
  404. Close the temporary file, possibly deleting it.
  405. """
  406. self._closer.close()
  407. # iter() doesn't use __getattr__ to find the __iter__ method
  408. def __iter__(self):
  409. # Don't return iter(self.file), but yield from it to avoid closing
  410. # file as long as it's being used as iterator (see issue #23700). We
  411. # can't use 'yield from' here because iter(file) returns the file
  412. # object itself, which has a close method, and thus the file would get
  413. # closed when the generator is finalized, due to PEP380 semantics.
  414. for line in self.file:
  415. yield line
  416. def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
  417. newline=None, suffix=None, prefix=None,
  418. dir=None, delete=True, *, errors=None):
  419. """Create and return a temporary file.
  420. Arguments:
  421. 'prefix', 'suffix', 'dir' -- as for mkstemp.
  422. 'mode' -- the mode argument to io.open (default "w+b").
  423. 'buffering' -- the buffer size argument to io.open (default -1).
  424. 'encoding' -- the encoding argument to io.open (default None)
  425. 'newline' -- the newline argument to io.open (default None)
  426. 'delete' -- whether the file is deleted on close (default True).
  427. 'errors' -- the errors argument to io.open (default None)
  428. The file is created as mkstemp() would do it.
  429. Returns an object with a file-like interface; the name of the file
  430. is accessible as its 'name' attribute. The file will be automatically
  431. deleted when it is closed unless the 'delete' argument is set to False.
  432. """
  433. prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
  434. flags = _bin_openflags
  435. # Setting O_TEMPORARY in the flags causes the OS to delete
  436. # the file when it is closed. This is only supported by Windows.
  437. if _os.name == 'nt' and delete:
  438. flags |= _os.O_TEMPORARY
  439. (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
  440. try:
  441. file = _io.open(fd, mode, buffering=buffering,
  442. newline=newline, encoding=encoding, errors=errors)
  443. return _TemporaryFileWrapper(file, name, delete)
  444. except BaseException:
  445. _os.unlink(name)
  446. _os.close(fd)
  447. raise
  448. if _os.name != 'posix' or _sys.platform == 'cygwin':
  449. # On non-POSIX and Cygwin systems, assume that we cannot unlink a file
  450. # while it is open.
  451. TemporaryFile = NamedTemporaryFile
  452. else:
  453. # Is the O_TMPFILE flag available and does it work?
  454. # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
  455. # IsADirectoryError exception
  456. _O_TMPFILE_WORKS = hasattr(_os, 'O_TMPFILE')
  457. def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
  458. newline=None, suffix=None, prefix=None,
  459. dir=None, *, errors=None):
  460. """Create and return a temporary file.
  461. Arguments:
  462. 'prefix', 'suffix', 'dir' -- as for mkstemp.
  463. 'mode' -- the mode argument to io.open (default "w+b").
  464. 'buffering' -- the buffer size argument to io.open (default -1).
  465. 'encoding' -- the encoding argument to io.open (default None)
  466. 'newline' -- the newline argument to io.open (default None)
  467. 'errors' -- the errors argument to io.open (default None)
  468. The file is created as mkstemp() would do it.
  469. Returns an object with a file-like interface. The file has no
  470. name, and will cease to exist when it is closed.
  471. """
  472. global _O_TMPFILE_WORKS
  473. prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
  474. flags = _bin_openflags
  475. if _O_TMPFILE_WORKS:
  476. try:
  477. flags2 = (flags | _os.O_TMPFILE) & ~_os.O_CREAT
  478. fd = _os.open(dir, flags2, 0o600)
  479. except IsADirectoryError:
  480. # Linux kernel older than 3.11 ignores the O_TMPFILE flag:
  481. # O_TMPFILE is read as O_DIRECTORY. Trying to open a directory
  482. # with O_RDWR|O_DIRECTORY fails with IsADirectoryError, a
  483. # directory cannot be open to write. Set flag to False to not
  484. # try again.
  485. _O_TMPFILE_WORKS = False
  486. except OSError:
  487. # The filesystem of the directory does not support O_TMPFILE.
  488. # For example, OSError(95, 'Operation not supported').
  489. #
  490. # On Linux kernel older than 3.11, trying to open a regular
  491. # file (or a symbolic link to a regular file) with O_TMPFILE
  492. # fails with NotADirectoryError, because O_TMPFILE is read as
  493. # O_DIRECTORY.
  494. pass
  495. else:
  496. try:
  497. return _io.open(fd, mode, buffering=buffering,
  498. newline=newline, encoding=encoding,
  499. errors=errors)
  500. except:
  501. _os.close(fd)
  502. raise
  503. # Fallback to _mkstemp_inner().
  504. (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
  505. try:
  506. _os.unlink(name)
  507. return _io.open(fd, mode, buffering=buffering,
  508. newline=newline, encoding=encoding, errors=errors)
  509. except:
  510. _os.close(fd)
  511. raise
  512. class SpooledTemporaryFile:
  513. """Temporary file wrapper, specialized to switch from BytesIO
  514. or StringIO to a real file when it exceeds a certain size or
  515. when a fileno is needed.
  516. """
  517. _rolled = False
  518. def __init__(self, max_size=0, mode='w+b', buffering=-1,
  519. encoding=None, newline=None,
  520. suffix=None, prefix=None, dir=None, *, errors=None):
  521. if 'b' in mode:
  522. self._file = _io.BytesIO()
  523. else:
  524. self._file = _io.TextIOWrapper(_io.BytesIO(),
  525. encoding=encoding, errors=errors,
  526. newline=newline)
  527. self._max_size = max_size
  528. self._rolled = False
  529. self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
  530. 'suffix': suffix, 'prefix': prefix,
  531. 'encoding': encoding, 'newline': newline,
  532. 'dir': dir, 'errors': errors}
  533. __class_getitem__ = classmethod(_types.GenericAlias)
  534. def _check(self, file):
  535. if self._rolled: return
  536. max_size = self._max_size
  537. if max_size and file.tell() > max_size:
  538. self.rollover()
  539. def rollover(self):
  540. if self._rolled: return
  541. file = self._file
  542. newfile = self._file = TemporaryFile(**self._TemporaryFileArgs)
  543. del self._TemporaryFileArgs
  544. pos = file.tell()
  545. if hasattr(newfile, 'buffer'):
  546. newfile.buffer.write(file.detach().getvalue())
  547. else:
  548. newfile.write(file.getvalue())
  549. newfile.seek(pos, 0)
  550. self._rolled = True
  551. # The method caching trick from NamedTemporaryFile
  552. # won't work here, because _file may change from a
  553. # BytesIO/StringIO instance to a real file. So we list
  554. # all the methods directly.
  555. # Context management protocol
  556. def __enter__(self):
  557. if self._file.closed:
  558. raise ValueError("Cannot enter context with closed file")
  559. return self
  560. def __exit__(self, exc, value, tb):
  561. self._file.close()
  562. # file protocol
  563. def __iter__(self):
  564. return self._file.__iter__()
  565. def close(self):
  566. self._file.close()
  567. @property
  568. def closed(self):
  569. return self._file.closed
  570. @property
  571. def encoding(self):
  572. return self._file.encoding
  573. @property
  574. def errors(self):
  575. return self._file.errors
  576. def fileno(self):
  577. self.rollover()
  578. return self._file.fileno()
  579. def flush(self):
  580. self._file.flush()
  581. def isatty(self):
  582. return self._file.isatty()
  583. @property
  584. def mode(self):
  585. try:
  586. return self._file.mode
  587. except AttributeError:
  588. return self._TemporaryFileArgs['mode']
  589. @property
  590. def name(self):
  591. try:
  592. return self._file.name
  593. except AttributeError:
  594. return None
  595. @property
  596. def newlines(self):
  597. return self._file.newlines
  598. def read(self, *args):
  599. return self._file.read(*args)
  600. def readline(self, *args):
  601. return self._file.readline(*args)
  602. def readlines(self, *args):
  603. return self._file.readlines(*args)
  604. def seek(self, *args):
  605. return self._file.seek(*args)
  606. def tell(self):
  607. return self._file.tell()
  608. def truncate(self, size=None):
  609. if size is None:
  610. self._file.truncate()
  611. else:
  612. if size > self._max_size:
  613. self.rollover()
  614. self._file.truncate(size)
  615. def write(self, s):
  616. file = self._file
  617. rv = file.write(s)
  618. self._check(file)
  619. return rv
  620. def writelines(self, iterable):
  621. file = self._file
  622. rv = file.writelines(iterable)
  623. self._check(file)
  624. return rv
  625. class TemporaryDirectory(object):
  626. """Create and return a temporary directory. This has the same
  627. behavior as mkdtemp but can be used as a context manager. For
  628. example:
  629. with TemporaryDirectory() as tmpdir:
  630. ...
  631. Upon exiting the context, the directory and everything contained
  632. in it are removed.
  633. """
  634. def __init__(self, suffix=None, prefix=None, dir=None):
  635. self.name = mkdtemp(suffix, prefix, dir)
  636. self._finalizer = _weakref.finalize(
  637. self, self._cleanup, self.name,
  638. warn_message="Implicitly cleaning up {!r}".format(self))
  639. @classmethod
  640. def _rmtree(cls, name):
  641. def onerror(func, path, exc_info):
  642. if issubclass(exc_info[0], PermissionError):
  643. def resetperms(path):
  644. try:
  645. _os.chflags(path, 0)
  646. except AttributeError:
  647. pass
  648. _os.chmod(path, 0o700)
  649. try:
  650. if path != name:
  651. resetperms(_os.path.dirname(path))
  652. resetperms(path)
  653. try:
  654. _os.unlink(path)
  655. # PermissionError is raised on FreeBSD for directories
  656. except (IsADirectoryError, PermissionError):
  657. cls._rmtree(path)
  658. except FileNotFoundError:
  659. pass
  660. elif issubclass(exc_info[0], FileNotFoundError):
  661. pass
  662. else:
  663. raise
  664. _shutil.rmtree(name, onerror=onerror)
  665. @classmethod
  666. def _cleanup(cls, name, warn_message):
  667. cls._rmtree(name)
  668. _warnings.warn(warn_message, ResourceWarning)
  669. def __repr__(self):
  670. return "<{} {!r}>".format(self.__class__.__name__, self.name)
  671. def __enter__(self):
  672. return self.name
  673. def __exit__(self, exc, value, tb):
  674. self.cleanup()
  675. def cleanup(self):
  676. if self._finalizer.detach():
  677. self._rmtree(self.name)
  678. __class_getitem__ = classmethod(_types.GenericAlias)