tempfile.py 26 KB

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