@@ -850,17 +850,26 @@ class TemporaryDirectory:
850850 ...
851851
852852 Upon exiting the context, the directory and everything contained
853- in it are removed.
853+ in it are removed (unless delete=False is passed or an exception
854+ is raised during cleanup and ignore_cleanup_errors is not True).
855+
856+ Optional Arguments:
857+ suffix - A str suffix for the directory name. (see mkdtemp)
858+ prefix - A str prefix for the directory name. (see mkdtemp)
859+ dir - A directory to create this temp dir in. (see mkdtemp)
860+ ignore_cleanup_errors - False; ignore exceptions during cleanup?
861+ delete - True; whether the directory is automatically deleted.
854862 """
855863
856864 def __init__ (self , suffix = None , prefix = None , dir = None ,
857- ignore_cleanup_errors = False ):
865+ ignore_cleanup_errors = False , * , delete = True ):
858866 self .name = mkdtemp (suffix , prefix , dir )
859867 self ._ignore_cleanup_errors = ignore_cleanup_errors
868+ self ._delete = delete
860869 self ._finalizer = _weakref .finalize (
861870 self , self ._cleanup , self .name ,
862871 warn_message = "Implicitly cleaning up {!r}" .format (self ),
863- ignore_errors = self ._ignore_cleanup_errors )
872+ ignore_errors = self ._ignore_cleanup_errors , delete = self . _delete )
864873
865874 @classmethod
866875 def _rmtree (cls , name , ignore_errors = False ):
@@ -894,9 +903,10 @@ def resetperms(path):
894903 _shutil .rmtree (name , onexc = onexc )
895904
896905 @classmethod
897- def _cleanup (cls , name , warn_message , ignore_errors = False ):
898- cls ._rmtree (name , ignore_errors = ignore_errors )
899- _warnings .warn (warn_message , ResourceWarning )
906+ def _cleanup (cls , name , warn_message , ignore_errors = False , delete = True ):
907+ if delete :
908+ cls ._rmtree (name , ignore_errors = ignore_errors )
909+ _warnings .warn (warn_message , ResourceWarning )
900910
901911 def __repr__ (self ):
902912 return "<{} {!r}>" .format (self .__class__ .__name__ , self .name )
@@ -905,7 +915,8 @@ def __enter__(self):
905915 return self .name
906916
907917 def __exit__ (self , exc , value , tb ):
908- self .cleanup ()
918+ if self ._delete :
919+ self .cleanup ()
909920
910921 def cleanup (self ):
911922 if self ._finalizer .detach () or _os .path .exists (self .name ):
0 commit comments