##// END OF EJS Templates
Turn warning into error as marked in the warning message.
Matthias Bussonnier -
Show More
@@ -1,329 +1,328 b''
1 1 # encoding: utf-8
2 2 """
3 3 An embedded IPython shell.
4 4 """
5 5 # Copyright (c) IPython Development Team.
6 6 # Distributed under the terms of the Modified BSD License.
7 7
8 8 from __future__ import with_statement
9 9 from __future__ import print_function
10 10
11 11 import sys
12 12 import warnings
13 13
14 14 from IPython.core import ultratb, compilerop
15 15 from IPython.core.magic import Magics, magics_class, line_magic
16 16 from IPython.core.interactiveshell import DummyMod
17 17 from IPython.core.interactiveshell import InteractiveShell
18 18 from IPython.terminal.ptshell import TerminalInteractiveShell
19 19 from IPython.terminal.ipapp import load_default_config
20 20
21 21 from traitlets import Bool, CBool, Unicode
22 22 from IPython.utils.io import ask_yes_no
23 23
24 24 class KillEmbeded(Exception):pass
25 25
26 26 # This is an additional magic that is exposed in embedded shells.
27 27 @magics_class
28 28 class EmbeddedMagics(Magics):
29 29
30 30 @line_magic
31 31 def kill_embedded(self, parameter_s=''):
32 32 """%kill_embedded : deactivate for good the current embedded IPython.
33 33
34 34 This function (after asking for confirmation) sets an internal flag so
35 35 that an embedded IPython will never activate again. This is useful to
36 36 permanently disable a shell that is being called inside a loop: once
37 37 you've figured out what you needed from it, you may then kill it and
38 38 the program will then continue to run without the interactive shell
39 39 interfering again.
40 40 """
41 41
42 42 kill = ask_yes_no("Are you sure you want to kill this embedded instance? [y/N] ",'n')
43 43 if kill:
44 44 self.shell.embedded_active = False
45 45 print ("This embedded IPython will not reactivate anymore "
46 46 "once you exit.")
47 47
48 48
49 49 @line_magic
50 50 def exit_raise(self, parameter_s=''):
51 51 """%exit_raise Make the current embedded kernel exit and raise and exception.
52 52
53 53 This function sets an internal flag so that an embedded IPython will
54 54 raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
55 55 useful to permanently exit a loop that create IPython embed instance.
56 56 """
57 57
58 58 self.shell.should_raise = True
59 59 self.shell.ask_exit()
60 60
61 61
62 62
63 63 class InteractiveShellEmbed(TerminalInteractiveShell):
64 64
65 65 dummy_mode = Bool(False)
66 66 exit_msg = Unicode('')
67 67 embedded = CBool(True)
68 68 should_raise = CBool(False)
69 69 # Like the base class display_banner is not configurable, but here it
70 70 # is True by default.
71 71 display_banner = CBool(True)
72 72 exit_msg = Unicode()
73 73
74 74 _inactive_locations = set()
75 75
76 76 @property
77 77 def embedded_active(self):
78 78 return self._call_location_id not in InteractiveShellEmbed._inactive_locations
79 79
80 80 @embedded_active.setter
81 81 def embedded_active(self, value):
82 82 if value :
83 83 if self._call_location_id in InteractiveShellEmbed._inactive_locations:
84 84 InteractiveShellEmbed._inactive_locations.remove(self._call_location_id)
85 85 else:
86 86 InteractiveShellEmbed._inactive_locations.add(self._call_location_id)
87 87
88 88 def __init__(self, **kw):
89 89
90 90
91 91 if kw.get('user_global_ns', None) is not None:
92 warnings.warn("user_global_ns has been replaced by user_module. The\
93 parameter will be ignored, and removed in IPython 5.0", DeprecationWarning)
92 raise DeprecationWarning("Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
94 93
95 94 self._call_location_id = kw.pop('_call_location_id', None)
96 95
97 96 super(InteractiveShellEmbed,self).__init__(**kw)
98 97
99 98 if not self._call_location_id:
100 99 frame = sys._getframe(1)
101 100 self._call_location_id = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
102 101 # don't use the ipython crash handler so that user exceptions aren't
103 102 # trapped
104 103 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
105 104 mode=self.xmode,
106 105 call_pdb=self.pdb)
107 106
108 107 def init_sys_modules(self):
109 108 pass
110 109
111 110 def init_magics(self):
112 111 super(InteractiveShellEmbed, self).init_magics()
113 112 self.register_magics(EmbeddedMagics)
114 113
115 114 def __call__(self, header='', local_ns=None, module=None, dummy=None,
116 115 stack_depth=1, global_ns=None, compile_flags=None):
117 116 """Activate the interactive interpreter.
118 117
119 118 __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
120 119 the interpreter shell with the given local and global namespaces, and
121 120 optionally print a header string at startup.
122 121
123 122 The shell can be globally activated/deactivated using the
124 123 dummy_mode attribute. This allows you to turn off a shell used
125 124 for debugging globally.
126 125
127 126 However, *each* time you call the shell you can override the current
128 127 state of dummy_mode with the optional keyword parameter 'dummy'. For
129 128 example, if you set dummy mode on with IPShell.dummy_mode = True, you
130 129 can still have a specific call work by making it as IPShell(dummy=False).
131 130 """
132 131
133 132 # If the user has turned it off, go away
134 133 if not self.embedded_active:
135 134 return
136 135
137 136 # Normal exits from interactive mode set this flag, so the shell can't
138 137 # re-enter (it checks this variable at the start of interactive mode).
139 138 self.exit_now = False
140 139
141 140 # Allow the dummy parameter to override the global __dummy_mode
142 141 if dummy or (dummy != 0 and self.dummy_mode):
143 142 return
144 143
145 144 if self.has_readline:
146 145 self.set_readline_completer()
147 146
148 147 # self.banner is auto computed
149 148 if header:
150 149 self.old_banner2 = self.banner2
151 150 self.banner2 = self.banner2 + '\n' + header + '\n'
152 151 else:
153 152 self.old_banner2 = ''
154 153
155 154 if self.display_banner:
156 155 self.show_banner()
157 156
158 157 # Call the embedding code with a stack depth of 1 so it can skip over
159 158 # our call and get the original caller's namespaces.
160 159 self.mainloop(local_ns, module, stack_depth=stack_depth,
161 160 global_ns=global_ns, compile_flags=compile_flags)
162 161
163 162 self.banner2 = self.old_banner2
164 163
165 164 if self.exit_msg is not None:
166 165 print(self.exit_msg)
167 166
168 167 if self.should_raise:
169 168 raise KillEmbeded('Embedded IPython raising error, as user requested.')
170 169
171 170
172 171 def mainloop(self, local_ns=None, module=None, stack_depth=0,
173 172 display_banner=None, global_ns=None, compile_flags=None):
174 173 """Embeds IPython into a running python program.
175 174
176 175 Parameters
177 176 ----------
178 177
179 178 local_ns, module
180 179 Working local namespace (a dict) and module (a module or similar
181 180 object). If given as None, they are automatically taken from the scope
182 181 where the shell was called, so that program variables become visible.
183 182
184 183 stack_depth : int
185 184 How many levels in the stack to go to looking for namespaces (when
186 185 local_ns or module is None). This allows an intermediate caller to
187 186 make sure that this function gets the namespace from the intended
188 187 level in the stack. By default (0) it will get its locals and globals
189 188 from the immediate caller.
190 189
191 190 compile_flags
192 191 A bit field identifying the __future__ features
193 192 that are enabled, as passed to the builtin :func:`compile` function.
194 193 If given as None, they are automatically taken from the scope where
195 194 the shell was called.
196 195
197 196 """
198 197
199 198 if (global_ns is not None) and (module is None):
200 199 warnings.warn("global_ns is deprecated, and will be removed in IPython 5.0 use module instead.", DeprecationWarning)
201 200 module = DummyMod()
202 201 module.__dict__ = global_ns
203 202
204 203 if (display_banner is not None):
205 204 warnings.warn("The display_banner parameter is deprecated.", DeprecationWarning)
206 205
207 206 # Get locals and globals from caller
208 207 if ((local_ns is None or module is None or compile_flags is None)
209 208 and self.default_user_namespaces):
210 209 call_frame = sys._getframe(stack_depth).f_back
211 210
212 211 if local_ns is None:
213 212 local_ns = call_frame.f_locals
214 213 if module is None:
215 214 global_ns = call_frame.f_globals
216 215 try:
217 216 module = sys.modules[global_ns['__name__']]
218 217 except KeyError:
219 218 warnings.warn("Failed to get module %s" % \
220 219 global_ns.get('__name__', 'unknown module')
221 220 )
222 221 module = DummyMod()
223 222 module.__dict__ = global_ns
224 223 if compile_flags is None:
225 224 compile_flags = (call_frame.f_code.co_flags &
226 225 compilerop.PyCF_MASK)
227 226
228 227 # Save original namespace and module so we can restore them after
229 228 # embedding; otherwise the shell doesn't shut down correctly.
230 229 orig_user_module = self.user_module
231 230 orig_user_ns = self.user_ns
232 231 orig_compile_flags = self.compile.flags
233 232
234 233 # Update namespaces and fire up interpreter
235 234
236 235 # The global one is easy, we can just throw it in
237 236 if module is not None:
238 237 self.user_module = module
239 238
240 239 # But the user/local one is tricky: ipython needs it to store internal
241 240 # data, but we also need the locals. We'll throw our hidden variables
242 241 # like _ih and get_ipython() into the local namespace, but delete them
243 242 # later.
244 243 if local_ns is not None:
245 244 reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
246 245 self.user_ns = reentrant_local_ns
247 246 self.init_user_ns()
248 247
249 248 # Compiler flags
250 249 if compile_flags is not None:
251 250 self.compile.flags = compile_flags
252 251
253 252 # make sure the tab-completer has the correct frame information, so it
254 253 # actually completes using the frame's locals/globals
255 254 self.set_completer_frame()
256 255
257 256 with self.builtin_trap, self.display_trap:
258 257 self.interact()
259 258
260 259 # now, purge out the local namespace of IPython's hidden variables.
261 260 if local_ns is not None:
262 261 local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
263 262
264 263
265 264 # Restore original namespace so shell can shut down when we exit.
266 265 self.user_module = orig_user_module
267 266 self.user_ns = orig_user_ns
268 267 self.compile.flags = orig_compile_flags
269 268
270 269
271 270 def embed(**kwargs):
272 271 """Call this to embed IPython at the current point in your program.
273 272
274 273 The first invocation of this will create an :class:`InteractiveShellEmbed`
275 274 instance and then call it. Consecutive calls just call the already
276 275 created instance.
277 276
278 277 If you don't want the kernel to initialize the namespace
279 278 from the scope of the surrounding function,
280 279 and/or you want to load full IPython configuration,
281 280 you probably want `IPython.start_ipython()` instead.
282 281
283 282 Here is a simple example::
284 283
285 284 from IPython import embed
286 285 a = 10
287 286 b = 20
288 287 embed(header='First time')
289 288 c = 30
290 289 d = 40
291 290 embed()
292 291
293 292 Full customization can be done by passing a :class:`Config` in as the
294 293 config argument.
295 294 """
296 295 config = kwargs.get('config')
297 296 header = kwargs.pop('header', u'')
298 297 compile_flags = kwargs.pop('compile_flags', None)
299 298 if config is None:
300 299 config = load_default_config()
301 300 config.InteractiveShellEmbed = config.TerminalInteractiveShell
302 301 config.InteractiveShellEmbed.colors='nocolor'
303 302 kwargs['config'] = config
304 303 #save ps1/ps2 if defined
305 304 ps1 = None
306 305 ps2 = None
307 306 try:
308 307 ps1 = sys.ps1
309 308 ps2 = sys.ps2
310 309 except AttributeError:
311 310 pass
312 311 #save previous instance
313 312 saved_shell_instance = InteractiveShell._instance
314 313 if saved_shell_instance is not None:
315 314 cls = type(saved_shell_instance)
316 315 cls.clear_instance()
317 316 frame = sys._getframe(1)
318 317 shell = InteractiveShellEmbed.instance(_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno), **kwargs)
319 318 shell(header=header, stack_depth=2, compile_flags=compile_flags)
320 319 InteractiveShellEmbed.clear_instance()
321 320 #restore previous instance
322 321 if saved_shell_instance is not None:
323 322 cls = type(saved_shell_instance)
324 323 cls.clear_instance()
325 324 for subclass in cls._walk_mro():
326 325 subclass._instance = saved_shell_instance
327 326 if ps1 is not None:
328 327 sys.ps1 = ps1
329 328 sys.ps2 = ps2
@@ -1,57 +1,57 b''
1 1 # encoding: utf-8
2 2 """
3 3 Utilities for warnings. Shoudn't we just use the built in warnings module.
4 4 """
5 5
6 6 # Copyright (c) IPython Development Team.
7 7 # Distributed under the terms of the Modified BSD License.
8 8
9 9 from __future__ import print_function
10 10
11 11 import sys
12 12 import warnings
13 13
14 warnings.warn("The module IPython.utils.warn is deprecated, use the standard warnings module instead", DeprecationWarning)
14 warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
15 15
16 16 def warn(msg,level=2,exit_val=1):
17 17 """Standard warning printer. Gives formatting consistency.
18 18
19 19 Output is sent to io.stderr (sys.stderr by default).
20 20
21 21 Options:
22 22
23 23 -level(2): allows finer control:
24 24 0 -> Do nothing, dummy function.
25 25 1 -> Print message.
26 26 2 -> Print 'WARNING:' + message. (Default level).
27 27 3 -> Print 'ERROR:' + message.
28 28 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
29 29
30 30 -exit_val (1): exit value returned by sys.exit() for a level 4
31 31 warning. Ignored for all other levels."""
32 32
33 warnings.warn("The module IPython.utils.warn is deprecated, use the standard warnings module instead", DeprecationWarning)
33 warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
34 34 if level>0:
35 35 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
36 36 print(header[level], msg, sep='', file=sys.stderr)
37 37 if level == 4:
38 38 print('Exiting.\n', file=sys.stderr)
39 39 sys.exit(exit_val)
40 40
41 41
42 42 def info(msg):
43 43 """Equivalent to warn(msg,level=1)."""
44 44
45 45 warn(msg,level=1)
46 46
47 47
48 48 def error(msg):
49 49 """Equivalent to warn(msg,level=3)."""
50 50
51 51 warn(msg,level=3)
52 52
53 53
54 54 def fatal(msg,exit_val=1):
55 55 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
56 56
57 57 warn(msg,exit_val=exit_val,level=4)
General Comments 0
You need to be logged in to leave comments. Login now