Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example: with TemporaryDirectory() as tmpdir: ... Upon exiting the context, the directory and everything contained in it are removed (unles
| 883 | |
| 884 | |
| 885 | class TemporaryDirectory: |
| 886 | """Create and return a temporary directory. This has the same |
| 887 | behavior as mkdtemp but can be used as a context manager. For |
| 888 | example: |
| 889 | |
| 890 | with TemporaryDirectory() as tmpdir: |
| 891 | ... |
| 892 | |
| 893 | Upon exiting the context, the directory and everything contained |
| 894 | in it are removed (unless delete=False is passed or an exception |
| 895 | is raised during cleanup and ignore_cleanup_errors is not True). |
| 896 | |
| 897 | Optional Arguments: |
| 898 | suffix - A str suffix for the directory name. (see mkdtemp) |
| 899 | prefix - A str prefix for the directory name. (see mkdtemp) |
| 900 | dir - A directory to create this temp dir in. (see mkdtemp) |
| 901 | ignore_cleanup_errors - False; ignore exceptions during cleanup? |
| 902 | delete - True; whether the directory is automatically deleted. |
| 903 | """ |
| 904 | |
| 905 | def __init__(self, suffix=None, prefix=None, dir=None, |
| 906 | ignore_cleanup_errors=False, *, delete=True): |
| 907 | self.name = mkdtemp(suffix, prefix, dir) |
| 908 | self._ignore_cleanup_errors = ignore_cleanup_errors |
| 909 | self._delete = delete |
| 910 | self._finalizer = _weakref.finalize( |
| 911 | self, self._cleanup, self.name, |
| 912 | warn_message="Implicitly cleaning up {!r}".format(self), |
| 913 | ignore_errors=self._ignore_cleanup_errors, delete=self._delete) |
| 914 | |
| 915 | @classmethod |
| 916 | def _rmtree(cls, name, ignore_errors=False, repeated=False): |
| 917 | def onexc(func, path, exc): |
| 918 | if isinstance(exc, PermissionError): |
| 919 | if repeated and path == name: |
| 920 | if ignore_errors: |
| 921 | return |
| 922 | raise |
| 923 | |
| 924 | try: |
| 925 | if path != name: |
| 926 | _resetperms(_os.path.dirname(path)) |
| 927 | _resetperms(path) |
| 928 | |
| 929 | try: |
| 930 | _os.unlink(path) |
| 931 | except IsADirectoryError: |
| 932 | cls._rmtree(path, ignore_errors=ignore_errors) |
| 933 | except PermissionError: |
| 934 | # The PermissionError handler was originally added for |
| 935 | # FreeBSD in directories, but it seems that it is raised |
| 936 | # on Windows too. |
| 937 | # bpo-43153: Calling _rmtree again may |
| 938 | # raise NotADirectoryError and mask the PermissionError. |
| 939 | # So we must re-raise the current PermissionError if |
| 940 | # path is not a directory. |
| 941 | if not _os.path.isdir(path) or _os.path.isjunction(path): |
| 942 | if ignore_errors: |