##// END OF EJS Templates
Ran black, reverted changes on utils/io.py.
Justin Palmer -
Show More
@@ -1,249 +1,248 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 IO related utilities.
3 IO related utilities.
4 """
4 """
5
5
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9
9
10
10
11 import atexit
11 import atexit
12 import os
12 import os
13 import sys
13 import sys
14 import tempfile
14 import tempfile
15 import warnings
15 import warnings
16 from warnings import warn
16 from warnings import warn
17 from pathlib import Path
18
17
19 from IPython.utils.decorators import undoc
18 from IPython.utils.decorators import undoc
20 from .capture import CapturedIO, capture_output
19 from .capture import CapturedIO, capture_output
21
20
22 @undoc
21 @undoc
23 class IOStream:
22 class IOStream:
24
23
25 def __init__(self, stream, fallback=None):
24 def __init__(self, stream, fallback=None):
26 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
25 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
27 DeprecationWarning, stacklevel=2)
26 DeprecationWarning, stacklevel=2)
28 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
27 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
29 if fallback is not None:
28 if fallback is not None:
30 stream = fallback
29 stream = fallback
31 else:
30 else:
32 raise ValueError("fallback required, but not specified")
31 raise ValueError("fallback required, but not specified")
33 self.stream = stream
32 self.stream = stream
34 self._swrite = stream.write
33 self._swrite = stream.write
35
34
36 # clone all methods not overridden:
35 # clone all methods not overridden:
37 def clone(meth):
36 def clone(meth):
38 return not hasattr(self, meth) and not meth.startswith('_')
37 return not hasattr(self, meth) and not meth.startswith('_')
39 for meth in filter(clone, dir(stream)):
38 for meth in filter(clone, dir(stream)):
40 try:
39 try:
41 val = getattr(stream, meth)
40 val = getattr(stream, meth)
42 except AttributeError:
41 except AttributeError:
43 pass
42 pass
44 else:
43 else:
45 setattr(self, meth, val)
44 setattr(self, meth, val)
46
45
47 def __repr__(self):
46 def __repr__(self):
48 cls = self.__class__
47 cls = self.__class__
49 tpl = '{mod}.{cls}({args})'
48 tpl = '{mod}.{cls}({args})'
50 return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
49 return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
51
50
52 def write(self,data):
51 def write(self,data):
53 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
52 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
54 DeprecationWarning, stacklevel=2)
53 DeprecationWarning, stacklevel=2)
55 try:
54 try:
56 self._swrite(data)
55 self._swrite(data)
57 except:
56 except:
58 try:
57 try:
59 # print handles some unicode issues which may trip a plain
58 # print handles some unicode issues which may trip a plain
60 # write() call. Emulate write() by using an empty end
59 # write() call. Emulate write() by using an empty end
61 # argument.
60 # argument.
62 print(data, end='', file=self.stream)
61 print(data, end='', file=self.stream)
63 except:
62 except:
64 # if we get here, something is seriously broken.
63 # if we get here, something is seriously broken.
65 print('ERROR - failed to write data to stream:', self.stream,
64 print('ERROR - failed to write data to stream:', self.stream,
66 file=sys.stderr)
65 file=sys.stderr)
67
66
68 def writelines(self, lines):
67 def writelines(self, lines):
69 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
68 warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
70 DeprecationWarning, stacklevel=2)
69 DeprecationWarning, stacklevel=2)
71 if isinstance(lines, str):
70 if isinstance(lines, str):
72 lines = [lines]
71 lines = [lines]
73 for line in lines:
72 for line in lines:
74 self.write(line)
73 self.write(line)
75
74
76 # This class used to have a writeln method, but regular files and streams
75 # This class used to have a writeln method, but regular files and streams
77 # in Python don't have this method. We need to keep this completely
76 # in Python don't have this method. We need to keep this completely
78 # compatible so we removed it.
77 # compatible so we removed it.
79
78
80 @property
79 @property
81 def closed(self):
80 def closed(self):
82 return self.stream.closed
81 return self.stream.closed
83
82
84 def close(self):
83 def close(self):
85 pass
84 pass
86
85
87 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
86 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
88 devnull = open(os.devnull, 'w')
87 devnull = open(os.devnull, 'w')
89 atexit.register(devnull.close)
88 atexit.register(devnull.close)
90
89
91 # io.std* are deprecated, but don't show our own deprecation warnings
90 # io.std* are deprecated, but don't show our own deprecation warnings
92 # during initialization of the deprecated API.
91 # during initialization of the deprecated API.
93 with warnings.catch_warnings():
92 with warnings.catch_warnings():
94 warnings.simplefilter('ignore', DeprecationWarning)
93 warnings.simplefilter('ignore', DeprecationWarning)
95 stdin = IOStream(sys.stdin, fallback=devnull)
94 stdin = IOStream(sys.stdin, fallback=devnull)
96 stdout = IOStream(sys.stdout, fallback=devnull)
95 stdout = IOStream(sys.stdout, fallback=devnull)
97 stderr = IOStream(sys.stderr, fallback=devnull)
96 stderr = IOStream(sys.stderr, fallback=devnull)
98
97
99 class Tee(object):
98 class Tee(object):
100 """A class to duplicate an output stream to stdout/err.
99 """A class to duplicate an output stream to stdout/err.
101
100
102 This works in a manner very similar to the Unix 'tee' command.
101 This works in a manner very similar to the Unix 'tee' command.
103
102
104 When the object is closed or deleted, it closes the original file given to
103 When the object is closed or deleted, it closes the original file given to
105 it for duplication.
104 it for duplication.
106 """
105 """
107 # Inspired by:
106 # Inspired by:
108 # http://mail.python.org/pipermail/python-list/2007-May/442737.html
107 # http://mail.python.org/pipermail/python-list/2007-May/442737.html
109
108
110 def __init__(self, file_or_name, mode="w", channel='stdout'):
109 def __init__(self, file_or_name, mode="w", channel='stdout'):
111 """Construct a new Tee object.
110 """Construct a new Tee object.
112
111
113 Parameters
112 Parameters
114 ----------
113 ----------
115 file_or_name : filename or open filehandle (writable)
114 file_or_name : filename or open filehandle (writable)
116 File that will be duplicated
115 File that will be duplicated
117
116
118 mode : optional, valid mode for open().
117 mode : optional, valid mode for open().
119 If a filename was give, open with this mode.
118 If a filename was give, open with this mode.
120
119
121 channel : str, one of ['stdout', 'stderr']
120 channel : str, one of ['stdout', 'stderr']
122 """
121 """
123 if channel not in ['stdout', 'stderr']:
122 if channel not in ['stdout', 'stderr']:
124 raise ValueError('Invalid channel spec %s' % channel)
123 raise ValueError('Invalid channel spec %s' % channel)
125
124
126 if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
125 if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
127 self.file = file_or_name
126 self.file = file_or_name
128 else:
127 else:
129 self.file = open(file_or_name, mode)
128 self.file = open(file_or_name, mode)
130 self.channel = channel
129 self.channel = channel
131 self.ostream = getattr(sys, channel)
130 self.ostream = getattr(sys, channel)
132 setattr(sys, channel, self)
131 setattr(sys, channel, self)
133 self._closed = False
132 self._closed = False
134
133
135 def close(self):
134 def close(self):
136 """Close the file and restore the channel."""
135 """Close the file and restore the channel."""
137 self.flush()
136 self.flush()
138 setattr(sys, self.channel, self.ostream)
137 setattr(sys, self.channel, self.ostream)
139 self.file.close()
138 self.file.close()
140 self._closed = True
139 self._closed = True
141
140
142 def write(self, data):
141 def write(self, data):
143 """Write data to both channels."""
142 """Write data to both channels."""
144 self.file.write(data)
143 self.file.write(data)
145 self.ostream.write(data)
144 self.ostream.write(data)
146 self.ostream.flush()
145 self.ostream.flush()
147
146
148 def flush(self):
147 def flush(self):
149 """Flush both channels."""
148 """Flush both channels."""
150 self.file.flush()
149 self.file.flush()
151 self.ostream.flush()
150 self.ostream.flush()
152
151
153 def __del__(self):
152 def __del__(self):
154 if not self._closed:
153 if not self._closed:
155 self.close()
154 self.close()
156
155
157
156
158 def ask_yes_no(prompt, default=None, interrupt=None):
157 def ask_yes_no(prompt, default=None, interrupt=None):
159 """Asks a question and returns a boolean (y/n) answer.
158 """Asks a question and returns a boolean (y/n) answer.
160
159
161 If default is given (one of 'y','n'), it is used if the user input is
160 If default is given (one of 'y','n'), it is used if the user input is
162 empty. If interrupt is given (one of 'y','n'), it is used if the user
161 empty. If interrupt is given (one of 'y','n'), it is used if the user
163 presses Ctrl-C. Otherwise the question is repeated until an answer is
162 presses Ctrl-C. Otherwise the question is repeated until an answer is
164 given.
163 given.
165
164
166 An EOF is treated as the default answer. If there is no default, an
165 An EOF is treated as the default answer. If there is no default, an
167 exception is raised to prevent infinite loops.
166 exception is raised to prevent infinite loops.
168
167
169 Valid answers are: y/yes/n/no (match is not case sensitive)."""
168 Valid answers are: y/yes/n/no (match is not case sensitive)."""
170
169
171 answers = {'y':True,'n':False,'yes':True,'no':False}
170 answers = {'y':True,'n':False,'yes':True,'no':False}
172 ans = None
171 ans = None
173 while ans not in answers.keys():
172 while ans not in answers.keys():
174 try:
173 try:
175 ans = input(prompt+' ').lower()
174 ans = input(prompt+' ').lower()
176 if not ans: # response was an empty string
175 if not ans: # response was an empty string
177 ans = default
176 ans = default
178 except KeyboardInterrupt:
177 except KeyboardInterrupt:
179 if interrupt:
178 if interrupt:
180 ans = interrupt
179 ans = interrupt
181 print("\r")
180 print("\r")
182 except EOFError:
181 except EOFError:
183 if default in answers.keys():
182 if default in answers.keys():
184 ans = default
183 ans = default
185 print()
184 print()
186 else:
185 else:
187 raise
186 raise
188
187
189 return answers[ans]
188 return answers[ans]
190
189
191
190
192 def temp_pyfile(src, ext='.py'):
191 def temp_pyfile(src, ext='.py'):
193 """Make a temporary python file, return filename and filehandle.
192 """Make a temporary python file, return filename and filehandle.
194
193
195 Parameters
194 Parameters
196 ----------
195 ----------
197 src : string or list of strings (no need for ending newlines if list)
196 src : string or list of strings (no need for ending newlines if list)
198 Source code to be written to the file.
197 Source code to be written to the file.
199
198
200 ext : optional, string
199 ext : optional, string
201 Extension for the generated file.
200 Extension for the generated file.
202
201
203 Returns
202 Returns
204 -------
203 -------
205 (filename, open filehandle)
204 (filename, open filehandle)
206 It is the caller's responsibility to close the open file and unlink it.
205 It is the caller's responsibility to close the open file and unlink it.
207 """
206 """
208 fname = Path(tempfile.mkstemp(ext)[1])
207 fname = tempfile.mkstemp(ext)[1]
209 with fname.open('w') as f:
208 with open(fname,'w') as f:
210 f.write(src)
209 f.write(src)
211 f.flush()
210 f.flush()
212 return str(fname)
211 return fname
213
212
214 @undoc
213 @undoc
215 def atomic_writing(*args, **kwargs):
214 def atomic_writing(*args, **kwargs):
216 """DEPRECATED: moved to notebook.services.contents.fileio"""
215 """DEPRECATED: moved to notebook.services.contents.fileio"""
217 warn("IPython.utils.io.atomic_writing has moved to notebook.services.contents.fileio since IPython 4.0", DeprecationWarning, stacklevel=2)
216 warn("IPython.utils.io.atomic_writing has moved to notebook.services.contents.fileio since IPython 4.0", DeprecationWarning, stacklevel=2)
218 from notebook.services.contents.fileio import atomic_writing
217 from notebook.services.contents.fileio import atomic_writing
219 return atomic_writing(*args, **kwargs)
218 return atomic_writing(*args, **kwargs)
220
219
221 @undoc
220 @undoc
222 def raw_print(*args, **kw):
221 def raw_print(*args, **kw):
223 """DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print()."""
222 """DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print()."""
224 warn("IPython.utils.io.raw_print has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
223 warn("IPython.utils.io.raw_print has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
225
224
226 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
225 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
227 file=sys.__stdout__)
226 file=sys.__stdout__)
228 sys.__stdout__.flush()
227 sys.__stdout__.flush()
229
228
230 @undoc
229 @undoc
231 def raw_print_err(*args, **kw):
230 def raw_print_err(*args, **kw):
232 """DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print()."""
231 """DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print()."""
233 warn("IPython.utils.io.raw_print_err has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
232 warn("IPython.utils.io.raw_print_err has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
234
233
235 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
234 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
236 file=sys.__stderr__)
235 file=sys.__stderr__)
237 sys.__stderr__.flush()
236 sys.__stderr__.flush()
238
237
239 # used by IPykernel <- 4.9. Removed during IPython 7-dev period and re-added
238 # used by IPykernel <- 4.9. Removed during IPython 7-dev period and re-added
240 # Keep for a version or two then should remove
239 # Keep for a version or two then should remove
241 rprint = raw_print
240 rprint = raw_print
242 rprinte = raw_print_err
241 rprinte = raw_print_err
243
242
244 @undoc
243 @undoc
245 def unicode_std_stream(stream='stdout'):
244 def unicode_std_stream(stream='stdout'):
246 """DEPRECATED, moved to nbconvert.utils.io"""
245 """DEPRECATED, moved to nbconvert.utils.io"""
247 warn("IPython.utils.io.unicode_std_stream has moved to nbconvert.utils.io since IPython 4.0", DeprecationWarning, stacklevel=2)
246 warn("IPython.utils.io.unicode_std_stream has moved to nbconvert.utils.io since IPython 4.0", DeprecationWarning, stacklevel=2)
248 from nbconvert.utils.io import unicode_std_stream
247 from nbconvert.utils.io import unicode_std_stream
249 return unicode_std_stream(stream)
248 return unicode_std_stream(stream)
General Comments 0
You need to be logged in to leave comments. Login now