tempfile.py 27 KB

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