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
13
+ from contextlib import contextmanager
14
14
15
+ try :
16
+ from contextlib import chdir as _chdir
17
+ except ImportError : # PY310
15
18
16
- class TemporaryDirectory :
19
+ @contextmanager
20
+ def _chdir (path ):
21
+ cwd = os .getcwd ()
22
+ os .chdir (path )
23
+ yield
24
+ os .chdir (cwd )
25
+
26
+
27
+ from .deprecated import deprecate_with_version
28
+
29
+
30
+ class TemporaryDirectory (tempfile .TemporaryDirectory ):
17
31
"""Create and return a temporary directory. This has the same
18
32
behavior as mkdtemp but can be used as a context manager.
19
33
20
34
Upon exiting the context, the directory and everything contained
21
35
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
36
"""
33
37
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
38
+ @deprecate_with_version (
39
+ 'Please use the standard library tempfile.TemporaryDirectory' ,
40
+ '5.0' ,
41
+ '7.0' ,
42
+ )
43
+ def __init__ (self , suffix = '' , prefix = tempfile .template , dir = None ):
44
+ """
45
+ Examples
46
+ --------
47
+ >>> import os
48
+ >>> with TemporaryDirectory() as tmpdir:
49
+ ... fname = os.path.join(tmpdir, 'example_file.txt')
50
+ ... with open(fname, 'wt') as fobj:
51
+ ... _ = fobj.write('a string\\ n')
52
+ >>> os.path.exists(tmpdir)
53
+ False
54
+ """
55
+ return super ().__init__ (suffix , prefix , dir )
49
56
50
57
51
- class InTemporaryDirectory (TemporaryDirectory ):
58
+ @contextmanager
59
+ def InTemporaryDirectory ():
52
60
"""Create, return, and change directory to a temporary directory
53
61
54
62
Notes
@@ -60,28 +68,23 @@ class InTemporaryDirectory(TemporaryDirectory):
60
68
Examples
61
69
--------
62
70
>>> import os
71
+ >>> from pathlib import Path
63
72
>>> my_cwd = os.getcwd()
64
73
>>> with InTemporaryDirectory() as tmpdir:
65
- ... _ = open ('test.txt', 'wt').write ('some text')
74
+ ... _ = Path ('test.txt').write_text ('some text')
66
75
... assert os.path.isfile('test.txt')
67
76
... assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
68
77
>>> os.path.exists(tmpdir)
69
78
False
70
79
>>> os.getcwd() == my_cwd
71
80
True
72
81
"""
82
+ with tempfile .TemporaryDirectory () as tmpdir , _chdir (tmpdir ):
83
+ yield tmpdir
73
84
74
- def __enter__ (self ):
75
- self ._pwd = os .getcwd ()
76
- os .chdir (self .name )
77
- return super ().__enter__ ()
78
-
79
- def __exit__ (self , exc , value , tb ):
80
- os .chdir (self ._pwd )
81
- return super ().__exit__ (exc , value , tb )
82
85
83
-
84
- class InGivenDirectory :
86
+ @ contextmanager
87
+ def InGivenDirectory ( path = None ) :
85
88
"""Change directory to given directory for duration of ``with`` block
86
89
87
90
Useful when you want to use `InTemporaryDirectory` for the final test, but
@@ -103,27 +106,15 @@ class InGivenDirectory:
103
106
You can then look at the temporary file outputs to debug what is happening,
104
107
fix, and finally replace ``InGivenDirectory`` with ``InTemporaryDirectory``
105
108
again.
106
- """
107
-
108
- def __init__ (self , path = None ):
109
- """Initialize directory context manager
110
109
111
- Parameters
112
- ----------
113
- path : None or str, optional
114
- path to change directory to, for duration of ``with`` block.
115
- Defaults to ``os.getcwd()`` if None
116
- """
117
- if path is None :
118
- path = os .getcwd ()
119
- self .path = os .path .abspath (path )
120
-
121
- def __enter__ (self ):
122
- self ._pwd = os .path .abspath (os .getcwd ())
123
- if not os .path .isdir (self .path ):
124
- os .mkdir (self .path )
125
- os .chdir (self .path )
126
- return self .path
127
-
128
- def __exit__ (self , exc , value , tb ):
129
- os .chdir (self ._pwd )
110
+ Parameters
111
+ ----------
112
+ path : None or str, optional
113
+ path to change directory to, for duration of ``with`` block.
114
+ Defaults to ``os.getcwd()`` if None
115
+ """
116
+ if path is None :
117
+ path = os .getcwd ()
118
+ os .makedirs (path , exist_ok = True )
119
+ with _chdir (path ):
120
+ yield os .path .abspath (path )
0 commit comments