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