9
9
"""Contexts for *with* statement providing temporary directories
10
10
"""
11
11
import os
12
- import shutil
13
- from tempfile import mkdtemp , template
12
+ import tempfile
14
13
14
+ from .deprecated import deprecate_with_version
15
15
16
- class TemporaryDirectory :
16
+
17
+ class TemporaryDirectory (tempfile .TemporaryDirectory ):
17
18
"""Create and return a temporary directory. This has the same
18
19
behavior as mkdtemp but can be used as a context manager.
19
20
20
21
Upon exiting the context, the directory and everything contained
21
22
in it are removed.
22
-
23
- Examples
24
- --------
25
- >>> import os
26
- >>> with TemporaryDirectory() as tmpdir:
27
- ... fname = os.path.join(tmpdir, 'example_file.txt')
28
- ... with open(fname, 'wt') as fobj:
29
- ... _ = fobj.write('a string\\ n')
30
- >>> os.path.exists(tmpdir)
31
- False
32
23
"""
33
24
34
- def __init__ (self , suffix = '' , prefix = template , dir = None ):
35
- self .name = mkdtemp (suffix , prefix , dir )
36
- self ._closed = False
37
-
38
- def __enter__ (self ):
39
- return self .name
40
-
41
- def cleanup (self ):
42
- if not self ._closed :
43
- shutil .rmtree (self .name )
44
- self ._closed = True
45
-
46
- def __exit__ (self , exc , value , tb ):
47
- self .cleanup ()
48
- return False
25
+ @deprecate_with_version (
26
+ 'Please use the standard library tempfile.TemporaryDirectory' ,
27
+ '5.0' ,
28
+ '7.0' ,
29
+ )
30
+ def __init__ (self , suffix = '' , prefix = tempfile .template , dir = None ):
31
+ """
32
+ Examples
33
+ --------
34
+ >>> import os
35
+ >>> with TemporaryDirectory() as tmpdir:
36
+ ... fname = os.path.join(tmpdir, 'example_file.txt')
37
+ ... with open(fname, 'wt') as fobj:
38
+ ... _ = fobj.write('a string\\ n')
39
+ >>> os.path.exists(tmpdir)
40
+ False
41
+ """
42
+ return super ().__init__ (suffix , prefix , dir )
49
43
50
44
51
- class InTemporaryDirectory (TemporaryDirectory ):
45
+ class InTemporaryDirectory (tempfile . TemporaryDirectory ):
52
46
"""Create, return, and change directory to a temporary directory
53
47
54
48
Notes
@@ -60,9 +54,10 @@ class InTemporaryDirectory(TemporaryDirectory):
60
54
Examples
61
55
--------
62
56
>>> import os
57
+ >>> from pathlib import Path
63
58
>>> my_cwd = os.getcwd()
64
59
>>> with InTemporaryDirectory() as tmpdir:
65
- ... _ = open ('test.txt', 'wt').write ('some text')
60
+ ... _ = Path ('test.txt').write_text ('some text')
66
61
... assert os.path.isfile('test.txt')
67
62
... assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
68
63
>>> os.path.exists(tmpdir)
0 commit comments