tempfile.py 26 KB

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