Show More
@@ -1,3108 +1,3079 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import absolute_import |
|
17 | from __future__ import absolute_import | |
18 | from __future__ import print_function |
|
18 | from __future__ import print_function | |
19 |
|
19 | |||
20 | import __builtin__ as builtin_mod |
|
20 | import __builtin__ as builtin_mod | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import ast |
|
23 | import ast | |
24 | import atexit |
|
24 | import atexit | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
27 | import runpy |
|
27 | import runpy | |
28 | import sys |
|
28 | import sys | |
29 | import tempfile |
|
29 | import tempfile | |
30 | import types |
|
30 | import types | |
31 | from io import open as io_open |
|
31 | from io import open as io_open | |
32 |
|
32 | |||
33 | from IPython.config.configurable import SingletonConfigurable |
|
33 | from IPython.config.configurable import SingletonConfigurable | |
34 | from IPython.core import debugger, oinspect |
|
34 | from IPython.core import debugger, oinspect | |
35 | from IPython.core import magic |
|
35 | from IPython.core import magic | |
36 | from IPython.core import page |
|
36 | from IPython.core import page | |
37 | from IPython.core import prefilter |
|
37 | from IPython.core import prefilter | |
38 | from IPython.core import shadowns |
|
38 | from IPython.core import shadowns | |
39 | from IPython.core import ultratb |
|
39 | from IPython.core import ultratb | |
40 | from IPython.core.alias import AliasManager, AliasError |
|
40 | from IPython.core.alias import AliasManager, AliasError | |
41 | from IPython.core.autocall import ExitAutocall |
|
41 | from IPython.core.autocall import ExitAutocall | |
42 | from IPython.core.builtin_trap import BuiltinTrap |
|
42 | from IPython.core.builtin_trap import BuiltinTrap | |
43 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
43 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython | |
44 | from IPython.core.display_trap import DisplayTrap |
|
44 | from IPython.core.display_trap import DisplayTrap | |
45 | from IPython.core.displayhook import DisplayHook |
|
45 | from IPython.core.displayhook import DisplayHook | |
46 | from IPython.core.displaypub import DisplayPublisher |
|
46 | from IPython.core.displaypub import DisplayPublisher | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.extensions import ExtensionManager |
|
48 | from IPython.core.extensions import ExtensionManager | |
49 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
49 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
50 | from IPython.core.formatters import DisplayFormatter |
|
50 | from IPython.core.formatters import DisplayFormatter | |
51 | from IPython.core.history import HistoryManager |
|
51 | from IPython.core.history import HistoryManager | |
52 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 |
|
52 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 | |
53 | from IPython.core.logger import Logger |
|
53 | from IPython.core.logger import Logger | |
54 | from IPython.core.macro import Macro |
|
54 | from IPython.core.macro import Macro | |
55 | from IPython.core.payload import PayloadManager |
|
55 | from IPython.core.payload import PayloadManager | |
56 | from IPython.core.prefilter import PrefilterManager |
|
56 | from IPython.core.prefilter import PrefilterManager | |
57 | from IPython.core.profiledir import ProfileDir |
|
57 | from IPython.core.profiledir import ProfileDir | |
58 | from IPython.core.pylabtools import pylab_activate |
|
58 | from IPython.core.pylabtools import pylab_activate | |
59 | from IPython.core.prompts import PromptManager |
|
59 | from IPython.core.prompts import PromptManager | |
60 | from IPython.lib.latextools import LaTeXTool |
|
60 | from IPython.lib.latextools import LaTeXTool | |
61 | from IPython.testing.skipdoctest import skip_doctest |
|
61 | from IPython.testing.skipdoctest import skip_doctest | |
62 | from IPython.utils import PyColorize |
|
62 | from IPython.utils import PyColorize | |
63 | from IPython.utils import io |
|
63 | from IPython.utils import io | |
64 | from IPython.utils import py3compat |
|
64 | from IPython.utils import py3compat | |
65 | from IPython.utils import openpy |
|
65 | from IPython.utils import openpy | |
66 | from IPython.utils.decorators import undoc |
|
66 | from IPython.utils.decorators import undoc | |
67 | from IPython.utils.io import ask_yes_no |
|
67 | from IPython.utils.io import ask_yes_no | |
68 | from IPython.utils.ipstruct import Struct |
|
68 | from IPython.utils.ipstruct import Struct | |
69 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename |
|
69 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename | |
70 | from IPython.utils.pickleshare import PickleShareDB |
|
70 | from IPython.utils.pickleshare import PickleShareDB | |
71 | from IPython.utils.process import system, getoutput |
|
71 | from IPython.utils.process import system, getoutput | |
72 | from IPython.utils.strdispatch import StrDispatch |
|
72 | from IPython.utils.strdispatch import StrDispatch | |
73 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
73 | from IPython.utils.syspathcontext import prepended_to_syspath | |
74 | from IPython.utils.text import (format_screen, LSString, SList, |
|
74 | from IPython.utils.text import (format_screen, LSString, SList, | |
75 | DollarFormatter) |
|
75 | DollarFormatter) | |
76 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, |
|
76 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, | |
77 | List, Unicode, Instance, Type) |
|
77 | List, Unicode, Instance, Type) | |
78 | from IPython.utils.warn import warn, error |
|
78 | from IPython.utils.warn import warn, error | |
79 | import IPython.core.hooks |
|
79 | import IPython.core.hooks | |
80 |
|
80 | |||
81 | #----------------------------------------------------------------------------- |
|
81 | #----------------------------------------------------------------------------- | |
82 | # Globals |
|
82 | # Globals | |
83 | #----------------------------------------------------------------------------- |
|
83 | #----------------------------------------------------------------------------- | |
84 |
|
84 | |||
85 | # compiled regexps for autoindent management |
|
85 | # compiled regexps for autoindent management | |
86 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
86 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
87 |
|
87 | |||
88 | #----------------------------------------------------------------------------- |
|
88 | #----------------------------------------------------------------------------- | |
89 | # Utilities |
|
89 | # Utilities | |
90 | #----------------------------------------------------------------------------- |
|
90 | #----------------------------------------------------------------------------- | |
91 |
|
91 | |||
92 | @undoc |
|
92 | @undoc | |
93 | def softspace(file, newvalue): |
|
93 | def softspace(file, newvalue): | |
94 | """Copied from code.py, to remove the dependency""" |
|
94 | """Copied from code.py, to remove the dependency""" | |
95 |
|
95 | |||
96 | oldvalue = 0 |
|
96 | oldvalue = 0 | |
97 | try: |
|
97 | try: | |
98 | oldvalue = file.softspace |
|
98 | oldvalue = file.softspace | |
99 | except AttributeError: |
|
99 | except AttributeError: | |
100 | pass |
|
100 | pass | |
101 | try: |
|
101 | try: | |
102 | file.softspace = newvalue |
|
102 | file.softspace = newvalue | |
103 | except (AttributeError, TypeError): |
|
103 | except (AttributeError, TypeError): | |
104 | # "attribute-less object" or "read-only attributes" |
|
104 | # "attribute-less object" or "read-only attributes" | |
105 | pass |
|
105 | pass | |
106 | return oldvalue |
|
106 | return oldvalue | |
107 |
|
107 | |||
108 | @undoc |
|
108 | @undoc | |
109 | def no_op(*a, **kw): pass |
|
109 | def no_op(*a, **kw): pass | |
110 |
|
110 | |||
111 | @undoc |
|
111 | @undoc | |
112 | class NoOpContext(object): |
|
112 | class NoOpContext(object): | |
113 | def __enter__(self): pass |
|
113 | def __enter__(self): pass | |
114 | def __exit__(self, type, value, traceback): pass |
|
114 | def __exit__(self, type, value, traceback): pass | |
115 | no_op_context = NoOpContext() |
|
115 | no_op_context = NoOpContext() | |
116 |
|
116 | |||
117 | class SpaceInInput(Exception): pass |
|
117 | class SpaceInInput(Exception): pass | |
118 |
|
118 | |||
119 | @undoc |
|
119 | @undoc | |
120 | class Bunch: pass |
|
120 | class Bunch: pass | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | def get_default_colors(): |
|
123 | def get_default_colors(): | |
124 | if sys.platform=='darwin': |
|
124 | if sys.platform=='darwin': | |
125 | return "LightBG" |
|
125 | return "LightBG" | |
126 | elif os.name=='nt': |
|
126 | elif os.name=='nt': | |
127 | return 'Linux' |
|
127 | return 'Linux' | |
128 | else: |
|
128 | else: | |
129 | return 'Linux' |
|
129 | return 'Linux' | |
130 |
|
130 | |||
131 |
|
131 | |||
132 | class SeparateUnicode(Unicode): |
|
132 | class SeparateUnicode(Unicode): | |
133 | """A Unicode subclass to validate separate_in, separate_out, etc. |
|
133 | """A Unicode subclass to validate separate_in, separate_out, etc. | |
134 |
|
134 | |||
135 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. |
|
135 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. | |
136 | """ |
|
136 | """ | |
137 |
|
137 | |||
138 | def validate(self, obj, value): |
|
138 | def validate(self, obj, value): | |
139 | if value == '0': value = '' |
|
139 | if value == '0': value = '' | |
140 | value = value.replace('\\n','\n') |
|
140 | value = value.replace('\\n','\n') | |
141 | return super(SeparateUnicode, self).validate(obj, value) |
|
141 | return super(SeparateUnicode, self).validate(obj, value) | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | class ReadlineNoRecord(object): |
|
144 | class ReadlineNoRecord(object): | |
145 | """Context manager to execute some code, then reload readline history |
|
145 | """Context manager to execute some code, then reload readline history | |
146 | so that interactive input to the code doesn't appear when pressing up.""" |
|
146 | so that interactive input to the code doesn't appear when pressing up.""" | |
147 | def __init__(self, shell): |
|
147 | def __init__(self, shell): | |
148 | self.shell = shell |
|
148 | self.shell = shell | |
149 | self._nested_level = 0 |
|
149 | self._nested_level = 0 | |
150 |
|
150 | |||
151 | def __enter__(self): |
|
151 | def __enter__(self): | |
152 | if self._nested_level == 0: |
|
152 | if self._nested_level == 0: | |
153 | try: |
|
153 | try: | |
154 | self.orig_length = self.current_length() |
|
154 | self.orig_length = self.current_length() | |
155 | self.readline_tail = self.get_readline_tail() |
|
155 | self.readline_tail = self.get_readline_tail() | |
156 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
156 | except (AttributeError, IndexError): # Can fail with pyreadline | |
157 | self.orig_length, self.readline_tail = 999999, [] |
|
157 | self.orig_length, self.readline_tail = 999999, [] | |
158 | self._nested_level += 1 |
|
158 | self._nested_level += 1 | |
159 |
|
159 | |||
160 | def __exit__(self, type, value, traceback): |
|
160 | def __exit__(self, type, value, traceback): | |
161 | self._nested_level -= 1 |
|
161 | self._nested_level -= 1 | |
162 | if self._nested_level == 0: |
|
162 | if self._nested_level == 0: | |
163 | # Try clipping the end if it's got longer |
|
163 | # Try clipping the end if it's got longer | |
164 | try: |
|
164 | try: | |
165 | e = self.current_length() - self.orig_length |
|
165 | e = self.current_length() - self.orig_length | |
166 | if e > 0: |
|
166 | if e > 0: | |
167 | for _ in range(e): |
|
167 | for _ in range(e): | |
168 | self.shell.readline.remove_history_item(self.orig_length) |
|
168 | self.shell.readline.remove_history_item(self.orig_length) | |
169 |
|
169 | |||
170 | # If it still doesn't match, just reload readline history. |
|
170 | # If it still doesn't match, just reload readline history. | |
171 | if self.current_length() != self.orig_length \ |
|
171 | if self.current_length() != self.orig_length \ | |
172 | or self.get_readline_tail() != self.readline_tail: |
|
172 | or self.get_readline_tail() != self.readline_tail: | |
173 | self.shell.refill_readline_hist() |
|
173 | self.shell.refill_readline_hist() | |
174 | except (AttributeError, IndexError): |
|
174 | except (AttributeError, IndexError): | |
175 | pass |
|
175 | pass | |
176 | # Returning False will cause exceptions to propagate |
|
176 | # Returning False will cause exceptions to propagate | |
177 | return False |
|
177 | return False | |
178 |
|
178 | |||
179 | def current_length(self): |
|
179 | def current_length(self): | |
180 | return self.shell.readline.get_current_history_length() |
|
180 | return self.shell.readline.get_current_history_length() | |
181 |
|
181 | |||
182 | def get_readline_tail(self, n=10): |
|
182 | def get_readline_tail(self, n=10): | |
183 | """Get the last n items in readline history.""" |
|
183 | """Get the last n items in readline history.""" | |
184 | end = self.shell.readline.get_current_history_length() + 1 |
|
184 | end = self.shell.readline.get_current_history_length() + 1 | |
185 | start = max(end-n, 1) |
|
185 | start = max(end-n, 1) | |
186 | ghi = self.shell.readline.get_history_item |
|
186 | ghi = self.shell.readline.get_history_item | |
187 | return [ghi(x) for x in range(start, end)] |
|
187 | return [ghi(x) for x in range(start, end)] | |
188 |
|
188 | |||
189 | #----------------------------------------------------------------------------- |
|
189 | #----------------------------------------------------------------------------- | |
190 | # Main IPython class |
|
190 | # Main IPython class | |
191 | #----------------------------------------------------------------------------- |
|
191 | #----------------------------------------------------------------------------- | |
192 |
|
192 | |||
193 | class InteractiveShell(SingletonConfigurable): |
|
193 | class InteractiveShell(SingletonConfigurable): | |
194 | """An enhanced, interactive shell for Python.""" |
|
194 | """An enhanced, interactive shell for Python.""" | |
195 |
|
195 | |||
196 | _instance = None |
|
196 | _instance = None | |
197 |
|
197 | |||
198 | ast_transformers = List([], config=True, help= |
|
198 | ast_transformers = List([], config=True, help= | |
199 | """ |
|
199 | """ | |
200 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
200 | A list of ast.NodeTransformer subclass instances, which will be applied | |
201 | to user input before code is run. |
|
201 | to user input before code is run. | |
202 | """ |
|
202 | """ | |
203 | ) |
|
203 | ) | |
204 |
|
204 | |||
205 | autocall = Enum((0,1,2), default_value=0, config=True, help= |
|
205 | autocall = Enum((0,1,2), default_value=0, config=True, help= | |
206 | """ |
|
206 | """ | |
207 | Make IPython automatically call any callable object even if you didn't |
|
207 | Make IPython automatically call any callable object even if you didn't | |
208 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
208 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
209 | automatically. The value can be '0' to disable the feature, '1' for |
|
209 | automatically. The value can be '0' to disable the feature, '1' for | |
210 | 'smart' autocall, where it is not applied if there are no more |
|
210 | 'smart' autocall, where it is not applied if there are no more | |
211 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
211 | arguments on the line, and '2' for 'full' autocall, where all callable | |
212 | objects are automatically called (even if no arguments are present). |
|
212 | objects are automatically called (even if no arguments are present). | |
213 | """ |
|
213 | """ | |
214 | ) |
|
214 | ) | |
215 | # TODO: remove all autoindent logic and put into frontends. |
|
215 | # TODO: remove all autoindent logic and put into frontends. | |
216 | # We can't do this yet because even runlines uses the autoindent. |
|
216 | # We can't do this yet because even runlines uses the autoindent. | |
217 | autoindent = CBool(True, config=True, help= |
|
217 | autoindent = CBool(True, config=True, help= | |
218 | """ |
|
218 | """ | |
219 | Autoindent IPython code entered interactively. |
|
219 | Autoindent IPython code entered interactively. | |
220 | """ |
|
220 | """ | |
221 | ) |
|
221 | ) | |
222 | automagic = CBool(True, config=True, help= |
|
222 | automagic = CBool(True, config=True, help= | |
223 | """ |
|
223 | """ | |
224 | Enable magic commands to be called without the leading %. |
|
224 | Enable magic commands to be called without the leading %. | |
225 | """ |
|
225 | """ | |
226 | ) |
|
226 | ) | |
227 | cache_size = Integer(1000, config=True, help= |
|
227 | cache_size = Integer(1000, config=True, help= | |
228 | """ |
|
228 | """ | |
229 | Set the size of the output cache. The default is 1000, you can |
|
229 | Set the size of the output cache. The default is 1000, you can | |
230 | change it permanently in your config file. Setting it to 0 completely |
|
230 | change it permanently in your config file. Setting it to 0 completely | |
231 | disables the caching system, and the minimum value accepted is 20 (if |
|
231 | disables the caching system, and the minimum value accepted is 20 (if | |
232 | you provide a value less than 20, it is reset to 0 and a warning is |
|
232 | you provide a value less than 20, it is reset to 0 and a warning is | |
233 | issued). This limit is defined because otherwise you'll spend more |
|
233 | issued). This limit is defined because otherwise you'll spend more | |
234 | time re-flushing a too small cache than working |
|
234 | time re-flushing a too small cache than working | |
235 | """ |
|
235 | """ | |
236 | ) |
|
236 | ) | |
237 | color_info = CBool(True, config=True, help= |
|
237 | color_info = CBool(True, config=True, help= | |
238 | """ |
|
238 | """ | |
239 | Use colors for displaying information about objects. Because this |
|
239 | Use colors for displaying information about objects. Because this | |
240 | information is passed through a pager (like 'less'), and some pagers |
|
240 | information is passed through a pager (like 'less'), and some pagers | |
241 | get confused with color codes, this capability can be turned off. |
|
241 | get confused with color codes, this capability can be turned off. | |
242 | """ |
|
242 | """ | |
243 | ) |
|
243 | ) | |
244 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
244 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
245 | default_value=get_default_colors(), config=True, |
|
245 | default_value=get_default_colors(), config=True, | |
246 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
246 | help="Set the color scheme (NoColor, Linux, or LightBG)." | |
247 | ) |
|
247 | ) | |
248 | colors_force = CBool(False, help= |
|
248 | colors_force = CBool(False, help= | |
249 | """ |
|
249 | """ | |
250 | Force use of ANSI color codes, regardless of OS and readline |
|
250 | Force use of ANSI color codes, regardless of OS and readline | |
251 | availability. |
|
251 | availability. | |
252 | """ |
|
252 | """ | |
253 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
253 | # FIXME: This is essentially a hack to allow ZMQShell to show colors | |
254 | # without readline on Win32. When the ZMQ formatting system is |
|
254 | # without readline on Win32. When the ZMQ formatting system is | |
255 | # refactored, this should be removed. |
|
255 | # refactored, this should be removed. | |
256 | ) |
|
256 | ) | |
257 | debug = CBool(False, config=True) |
|
257 | debug = CBool(False, config=True) | |
258 | deep_reload = CBool(False, config=True, help= |
|
258 | deep_reload = CBool(False, config=True, help= | |
259 | """ |
|
259 | """ | |
260 | Enable deep (recursive) reloading by default. IPython can use the |
|
260 | Enable deep (recursive) reloading by default. IPython can use the | |
261 | deep_reload module which reloads changes in modules recursively (it |
|
261 | deep_reload module which reloads changes in modules recursively (it | |
262 | replaces the reload() function, so you don't need to change anything to |
|
262 | replaces the reload() function, so you don't need to change anything to | |
263 | use it). deep_reload() forces a full reload of modules whose code may |
|
263 | use it). deep_reload() forces a full reload of modules whose code may | |
264 | have changed, which the default reload() function does not. When |
|
264 | have changed, which the default reload() function does not. When | |
265 | deep_reload is off, IPython will use the normal reload(), but |
|
265 | deep_reload is off, IPython will use the normal reload(), but | |
266 | deep_reload will still be available as dreload(). |
|
266 | deep_reload will still be available as dreload(). | |
267 | """ |
|
267 | """ | |
268 | ) |
|
268 | ) | |
269 | disable_failing_post_execute = CBool(False, config=True, |
|
269 | disable_failing_post_execute = CBool(False, config=True, | |
270 | help="Don't call post-execute functions that have failed in the past." |
|
270 | help="Don't call post-execute functions that have failed in the past." | |
271 | ) |
|
271 | ) | |
272 | display_formatter = Instance(DisplayFormatter) |
|
272 | display_formatter = Instance(DisplayFormatter) | |
273 | displayhook_class = Type(DisplayHook) |
|
273 | displayhook_class = Type(DisplayHook) | |
274 | display_pub_class = Type(DisplayPublisher) |
|
274 | display_pub_class = Type(DisplayPublisher) | |
275 | data_pub_class = None |
|
275 | data_pub_class = None | |
276 |
|
276 | |||
277 | exit_now = CBool(False) |
|
277 | exit_now = CBool(False) | |
278 | exiter = Instance(ExitAutocall) |
|
278 | exiter = Instance(ExitAutocall) | |
279 | def _exiter_default(self): |
|
279 | def _exiter_default(self): | |
280 | return ExitAutocall(self) |
|
280 | return ExitAutocall(self) | |
281 | # Monotonically increasing execution counter |
|
281 | # Monotonically increasing execution counter | |
282 | execution_count = Integer(1) |
|
282 | execution_count = Integer(1) | |
283 | filename = Unicode("<ipython console>") |
|
283 | filename = Unicode("<ipython console>") | |
284 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
284 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
285 |
|
285 | |||
286 | # Input splitter, to transform input line by line and detect when a block |
|
286 | # Input splitter, to transform input line by line and detect when a block | |
287 | # is ready to be executed. |
|
287 | # is ready to be executed. | |
288 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
288 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
289 | (), {'line_input_checker': True}) |
|
289 | (), {'line_input_checker': True}) | |
290 |
|
290 | |||
291 | # This InputSplitter instance is used to transform completed cells before |
|
291 | # This InputSplitter instance is used to transform completed cells before | |
292 | # running them. It allows cell magics to contain blank lines. |
|
292 | # running them. It allows cell magics to contain blank lines. | |
293 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
293 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
294 | (), {'line_input_checker': False}) |
|
294 | (), {'line_input_checker': False}) | |
295 |
|
295 | |||
296 | logstart = CBool(False, config=True, help= |
|
296 | logstart = CBool(False, config=True, help= | |
297 | """ |
|
297 | """ | |
298 | Start logging to the default log file. |
|
298 | Start logging to the default log file. | |
299 | """ |
|
299 | """ | |
300 | ) |
|
300 | ) | |
301 | logfile = Unicode('', config=True, help= |
|
301 | logfile = Unicode('', config=True, help= | |
302 | """ |
|
302 | """ | |
303 | The name of the logfile to use. |
|
303 | The name of the logfile to use. | |
304 | """ |
|
304 | """ | |
305 | ) |
|
305 | ) | |
306 | logappend = Unicode('', config=True, help= |
|
306 | logappend = Unicode('', config=True, help= | |
307 | """ |
|
307 | """ | |
308 | Start logging to the given file in append mode. |
|
308 | Start logging to the given file in append mode. | |
309 | """ |
|
309 | """ | |
310 | ) |
|
310 | ) | |
311 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
311 | object_info_string_level = Enum((0,1,2), default_value=0, | |
312 | config=True) |
|
312 | config=True) | |
313 | pdb = CBool(False, config=True, help= |
|
313 | pdb = CBool(False, config=True, help= | |
314 | """ |
|
314 | """ | |
315 | Automatically call the pdb debugger after every exception. |
|
315 | Automatically call the pdb debugger after every exception. | |
316 | """ |
|
316 | """ | |
317 | ) |
|
317 | ) | |
318 | multiline_history = CBool(sys.platform != 'win32', config=True, |
|
318 | multiline_history = CBool(sys.platform != 'win32', config=True, | |
319 | help="Save multi-line entries as one entry in readline history" |
|
319 | help="Save multi-line entries as one entry in readline history" | |
320 | ) |
|
320 | ) | |
321 |
|
321 | |||
322 | # deprecated prompt traits: |
|
322 | # deprecated prompt traits: | |
323 |
|
323 | |||
324 | prompt_in1 = Unicode('In [\\#]: ', config=True, |
|
324 | prompt_in1 = Unicode('In [\\#]: ', config=True, | |
325 | help="Deprecated, use PromptManager.in_template") |
|
325 | help="Deprecated, use PromptManager.in_template") | |
326 | prompt_in2 = Unicode(' .\\D.: ', config=True, |
|
326 | prompt_in2 = Unicode(' .\\D.: ', config=True, | |
327 | help="Deprecated, use PromptManager.in2_template") |
|
327 | help="Deprecated, use PromptManager.in2_template") | |
328 | prompt_out = Unicode('Out[\\#]: ', config=True, |
|
328 | prompt_out = Unicode('Out[\\#]: ', config=True, | |
329 | help="Deprecated, use PromptManager.out_template") |
|
329 | help="Deprecated, use PromptManager.out_template") | |
330 | prompts_pad_left = CBool(True, config=True, |
|
330 | prompts_pad_left = CBool(True, config=True, | |
331 | help="Deprecated, use PromptManager.justify") |
|
331 | help="Deprecated, use PromptManager.justify") | |
332 |
|
332 | |||
333 | def _prompt_trait_changed(self, name, old, new): |
|
333 | def _prompt_trait_changed(self, name, old, new): | |
334 | table = { |
|
334 | table = { | |
335 | 'prompt_in1' : 'in_template', |
|
335 | 'prompt_in1' : 'in_template', | |
336 | 'prompt_in2' : 'in2_template', |
|
336 | 'prompt_in2' : 'in2_template', | |
337 | 'prompt_out' : 'out_template', |
|
337 | 'prompt_out' : 'out_template', | |
338 | 'prompts_pad_left' : 'justify', |
|
338 | 'prompts_pad_left' : 'justify', | |
339 | } |
|
339 | } | |
340 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format( |
|
340 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format( | |
341 | name=name, newname=table[name]) |
|
341 | name=name, newname=table[name]) | |
342 | ) |
|
342 | ) | |
343 | # protect against weird cases where self.config may not exist: |
|
343 | # protect against weird cases where self.config may not exist: | |
344 | if self.config is not None: |
|
344 | if self.config is not None: | |
345 | # propagate to corresponding PromptManager trait |
|
345 | # propagate to corresponding PromptManager trait | |
346 | setattr(self.config.PromptManager, table[name], new) |
|
346 | setattr(self.config.PromptManager, table[name], new) | |
347 |
|
347 | |||
348 | _prompt_in1_changed = _prompt_trait_changed |
|
348 | _prompt_in1_changed = _prompt_trait_changed | |
349 | _prompt_in2_changed = _prompt_trait_changed |
|
349 | _prompt_in2_changed = _prompt_trait_changed | |
350 | _prompt_out_changed = _prompt_trait_changed |
|
350 | _prompt_out_changed = _prompt_trait_changed | |
351 | _prompt_pad_left_changed = _prompt_trait_changed |
|
351 | _prompt_pad_left_changed = _prompt_trait_changed | |
352 |
|
352 | |||
353 | show_rewritten_input = CBool(True, config=True, |
|
353 | show_rewritten_input = CBool(True, config=True, | |
354 | help="Show rewritten input, e.g. for autocall." |
|
354 | help="Show rewritten input, e.g. for autocall." | |
355 | ) |
|
355 | ) | |
356 |
|
356 | |||
357 | quiet = CBool(False, config=True) |
|
357 | quiet = CBool(False, config=True) | |
358 |
|
358 | |||
359 | history_length = Integer(10000, config=True) |
|
359 | history_length = Integer(10000, config=True) | |
360 |
|
360 | |||
361 | # The readline stuff will eventually be moved to the terminal subclass |
|
361 | # The readline stuff will eventually be moved to the terminal subclass | |
362 | # but for now, we can't do that as readline is welded in everywhere. |
|
362 | # but for now, we can't do that as readline is welded in everywhere. | |
363 | readline_use = CBool(True, config=True) |
|
363 | readline_use = CBool(True, config=True) | |
364 | readline_remove_delims = Unicode('-/~', config=True) |
|
364 | readline_remove_delims = Unicode('-/~', config=True) | |
365 | readline_delims = Unicode() # set by init_readline() |
|
365 | readline_delims = Unicode() # set by init_readline() | |
366 | # don't use \M- bindings by default, because they |
|
366 | # don't use \M- bindings by default, because they | |
367 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
367 | # conflict with 8-bit encodings. See gh-58,gh-88 | |
368 | readline_parse_and_bind = List([ |
|
368 | readline_parse_and_bind = List([ | |
369 | 'tab: complete', |
|
369 | 'tab: complete', | |
370 | '"\C-l": clear-screen', |
|
370 | '"\C-l": clear-screen', | |
371 | 'set show-all-if-ambiguous on', |
|
371 | 'set show-all-if-ambiguous on', | |
372 | '"\C-o": tab-insert', |
|
372 | '"\C-o": tab-insert', | |
373 | '"\C-r": reverse-search-history', |
|
373 | '"\C-r": reverse-search-history', | |
374 | '"\C-s": forward-search-history', |
|
374 | '"\C-s": forward-search-history', | |
375 | '"\C-p": history-search-backward', |
|
375 | '"\C-p": history-search-backward', | |
376 | '"\C-n": history-search-forward', |
|
376 | '"\C-n": history-search-forward', | |
377 | '"\e[A": history-search-backward', |
|
377 | '"\e[A": history-search-backward', | |
378 | '"\e[B": history-search-forward', |
|
378 | '"\e[B": history-search-forward', | |
379 | '"\C-k": kill-line', |
|
379 | '"\C-k": kill-line', | |
380 | '"\C-u": unix-line-discard', |
|
380 | '"\C-u": unix-line-discard', | |
381 | ], allow_none=False, config=True) |
|
381 | ], allow_none=False, config=True) | |
382 |
|
382 | |||
383 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
383 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], | |
384 | default_value='last_expr', config=True, |
|
384 | default_value='last_expr', config=True, | |
385 | help=""" |
|
385 | help=""" | |
386 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
386 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
387 | run interactively (displaying output from expressions).""") |
|
387 | run interactively (displaying output from expressions).""") | |
388 |
|
388 | |||
389 | # TODO: this part of prompt management should be moved to the frontends. |
|
389 | # TODO: this part of prompt management should be moved to the frontends. | |
390 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
390 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
391 | separate_in = SeparateUnicode('\n', config=True) |
|
391 | separate_in = SeparateUnicode('\n', config=True) | |
392 | separate_out = SeparateUnicode('', config=True) |
|
392 | separate_out = SeparateUnicode('', config=True) | |
393 | separate_out2 = SeparateUnicode('', config=True) |
|
393 | separate_out2 = SeparateUnicode('', config=True) | |
394 | wildcards_case_sensitive = CBool(True, config=True) |
|
394 | wildcards_case_sensitive = CBool(True, config=True) | |
395 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
395 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
396 | default_value='Context', config=True) |
|
396 | default_value='Context', config=True) | |
397 |
|
397 | |||
398 | # Subcomponents of InteractiveShell |
|
398 | # Subcomponents of InteractiveShell | |
399 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
399 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
400 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
400 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
401 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
401 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
402 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
402 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
403 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
403 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
404 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
404 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
405 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
405 | history_manager = Instance('IPython.core.history.HistoryManager') | |
406 | magics_manager = Instance('IPython.core.magic.MagicsManager') |
|
406 | magics_manager = Instance('IPython.core.magic.MagicsManager') | |
407 |
|
407 | |||
408 | profile_dir = Instance('IPython.core.application.ProfileDir') |
|
408 | profile_dir = Instance('IPython.core.application.ProfileDir') | |
409 | @property |
|
409 | @property | |
410 | def profile(self): |
|
410 | def profile(self): | |
411 | if self.profile_dir is not None: |
|
411 | if self.profile_dir is not None: | |
412 | name = os.path.basename(self.profile_dir.location) |
|
412 | name = os.path.basename(self.profile_dir.location) | |
413 | return name.replace('profile_','') |
|
413 | return name.replace('profile_','') | |
414 |
|
414 | |||
415 |
|
415 | |||
416 | # Private interface |
|
416 | # Private interface | |
417 | _post_execute = Instance(dict) |
|
417 | _post_execute = Instance(dict) | |
418 |
|
418 | |||
419 | # Tracks any GUI loop loaded for pylab |
|
419 | # Tracks any GUI loop loaded for pylab | |
420 | pylab_gui_select = None |
|
420 | pylab_gui_select = None | |
421 |
|
421 | |||
422 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
422 | def __init__(self, ipython_dir=None, profile_dir=None, | |
423 | user_module=None, user_ns=None, |
|
423 | user_module=None, user_ns=None, | |
424 | custom_exceptions=((), None), **kwargs): |
|
424 | custom_exceptions=((), None), **kwargs): | |
425 |
|
425 | |||
426 | # This is where traits with a config_key argument are updated |
|
426 | # This is where traits with a config_key argument are updated | |
427 | # from the values on config. |
|
427 | # from the values on config. | |
428 | super(InteractiveShell, self).__init__(**kwargs) |
|
428 | super(InteractiveShell, self).__init__(**kwargs) | |
429 | self.configurables = [self] |
|
429 | self.configurables = [self] | |
430 |
|
430 | |||
431 | # These are relatively independent and stateless |
|
431 | # These are relatively independent and stateless | |
432 | self.init_ipython_dir(ipython_dir) |
|
432 | self.init_ipython_dir(ipython_dir) | |
433 | self.init_profile_dir(profile_dir) |
|
433 | self.init_profile_dir(profile_dir) | |
434 | self.init_instance_attrs() |
|
434 | self.init_instance_attrs() | |
435 | self.init_environment() |
|
435 | self.init_environment() | |
436 |
|
436 | |||
437 | # Check if we're in a virtualenv, and set up sys.path. |
|
437 | # Check if we're in a virtualenv, and set up sys.path. | |
438 | self.init_virtualenv() |
|
438 | self.init_virtualenv() | |
439 |
|
439 | |||
440 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
440 | # Create namespaces (user_ns, user_global_ns, etc.) | |
441 | self.init_create_namespaces(user_module, user_ns) |
|
441 | self.init_create_namespaces(user_module, user_ns) | |
442 | # This has to be done after init_create_namespaces because it uses |
|
442 | # This has to be done after init_create_namespaces because it uses | |
443 | # something in self.user_ns, but before init_sys_modules, which |
|
443 | # something in self.user_ns, but before init_sys_modules, which | |
444 | # is the first thing to modify sys. |
|
444 | # is the first thing to modify sys. | |
445 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
445 | # TODO: When we override sys.stdout and sys.stderr before this class | |
446 | # is created, we are saving the overridden ones here. Not sure if this |
|
446 | # is created, we are saving the overridden ones here. Not sure if this | |
447 | # is what we want to do. |
|
447 | # is what we want to do. | |
448 | self.save_sys_module_state() |
|
448 | self.save_sys_module_state() | |
449 | self.init_sys_modules() |
|
449 | self.init_sys_modules() | |
450 |
|
450 | |||
451 | # While we're trying to have each part of the code directly access what |
|
451 | # While we're trying to have each part of the code directly access what | |
452 | # it needs without keeping redundant references to objects, we have too |
|
452 | # it needs without keeping redundant references to objects, we have too | |
453 | # much legacy code that expects ip.db to exist. |
|
453 | # much legacy code that expects ip.db to exist. | |
454 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
454 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) | |
455 |
|
455 | |||
456 | self.init_history() |
|
456 | self.init_history() | |
457 | self.init_encoding() |
|
457 | self.init_encoding() | |
458 | self.init_prefilter() |
|
458 | self.init_prefilter() | |
459 |
|
459 | |||
460 | self.init_syntax_highlighting() |
|
460 | self.init_syntax_highlighting() | |
461 | self.init_hooks() |
|
461 | self.init_hooks() | |
462 | self.init_pushd_popd_magic() |
|
462 | self.init_pushd_popd_magic() | |
463 | # self.init_traceback_handlers use to be here, but we moved it below |
|
463 | # self.init_traceback_handlers use to be here, but we moved it below | |
464 | # because it and init_io have to come after init_readline. |
|
464 | # because it and init_io have to come after init_readline. | |
465 | self.init_user_ns() |
|
465 | self.init_user_ns() | |
466 | self.init_logger() |
|
466 | self.init_logger() | |
467 | self.init_alias() |
|
467 | self.init_alias() | |
468 | self.init_builtins() |
|
468 | self.init_builtins() | |
469 |
|
469 | |||
470 | # The following was in post_config_initialization |
|
470 | # The following was in post_config_initialization | |
471 | self.init_inspector() |
|
471 | self.init_inspector() | |
472 | # init_readline() must come before init_io(), because init_io uses |
|
472 | # init_readline() must come before init_io(), because init_io uses | |
473 | # readline related things. |
|
473 | # readline related things. | |
474 | self.init_readline() |
|
474 | self.init_readline() | |
475 | # We save this here in case user code replaces raw_input, but it needs |
|
475 | # We save this here in case user code replaces raw_input, but it needs | |
476 | # to be after init_readline(), because PyPy's readline works by replacing |
|
476 | # to be after init_readline(), because PyPy's readline works by replacing | |
477 | # raw_input. |
|
477 | # raw_input. | |
478 | if py3compat.PY3: |
|
478 | if py3compat.PY3: | |
479 | self.raw_input_original = input |
|
479 | self.raw_input_original = input | |
480 | else: |
|
480 | else: | |
481 | self.raw_input_original = raw_input |
|
481 | self.raw_input_original = raw_input | |
482 | # init_completer must come after init_readline, because it needs to |
|
482 | # init_completer must come after init_readline, because it needs to | |
483 | # know whether readline is present or not system-wide to configure the |
|
483 | # know whether readline is present or not system-wide to configure the | |
484 | # completers, since the completion machinery can now operate |
|
484 | # completers, since the completion machinery can now operate | |
485 | # independently of readline (e.g. over the network) |
|
485 | # independently of readline (e.g. over the network) | |
486 | self.init_completer() |
|
486 | self.init_completer() | |
487 | # TODO: init_io() needs to happen before init_traceback handlers |
|
487 | # TODO: init_io() needs to happen before init_traceback handlers | |
488 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
488 | # because the traceback handlers hardcode the stdout/stderr streams. | |
489 | # This logic in in debugger.Pdb and should eventually be changed. |
|
489 | # This logic in in debugger.Pdb and should eventually be changed. | |
490 | self.init_io() |
|
490 | self.init_io() | |
491 | self.init_traceback_handlers(custom_exceptions) |
|
491 | self.init_traceback_handlers(custom_exceptions) | |
492 | self.init_prompts() |
|
492 | self.init_prompts() | |
493 | self.init_display_formatter() |
|
493 | self.init_display_formatter() | |
494 | self.init_display_pub() |
|
494 | self.init_display_pub() | |
495 | self.init_data_pub() |
|
495 | self.init_data_pub() | |
496 | self.init_displayhook() |
|
496 | self.init_displayhook() | |
497 | self.init_latextool() |
|
497 | self.init_latextool() | |
498 | self.init_magics() |
|
498 | self.init_magics() | |
499 | self.init_logstart() |
|
499 | self.init_logstart() | |
500 | self.init_pdb() |
|
500 | self.init_pdb() | |
501 | self.init_extension_manager() |
|
501 | self.init_extension_manager() | |
502 | self.init_payload() |
|
502 | self.init_payload() | |
503 | self.hooks.late_startup_hook() |
|
503 | self.hooks.late_startup_hook() | |
504 | atexit.register(self.atexit_operations) |
|
504 | atexit.register(self.atexit_operations) | |
505 |
|
505 | |||
506 | def get_ipython(self): |
|
506 | def get_ipython(self): | |
507 | """Return the currently running IPython instance.""" |
|
507 | """Return the currently running IPython instance.""" | |
508 | return self |
|
508 | return self | |
509 |
|
509 | |||
510 | #------------------------------------------------------------------------- |
|
510 | #------------------------------------------------------------------------- | |
511 | # Trait changed handlers |
|
511 | # Trait changed handlers | |
512 | #------------------------------------------------------------------------- |
|
512 | #------------------------------------------------------------------------- | |
513 |
|
513 | |||
514 | def _ipython_dir_changed(self, name, new): |
|
514 | def _ipython_dir_changed(self, name, new): | |
515 | if not os.path.isdir(new): |
|
515 | if not os.path.isdir(new): | |
516 | os.makedirs(new, mode = 0o777) |
|
516 | os.makedirs(new, mode = 0o777) | |
517 |
|
517 | |||
518 | def set_autoindent(self,value=None): |
|
518 | def set_autoindent(self,value=None): | |
519 | """Set the autoindent flag, checking for readline support. |
|
519 | """Set the autoindent flag, checking for readline support. | |
520 |
|
520 | |||
521 | If called with no arguments, it acts as a toggle.""" |
|
521 | If called with no arguments, it acts as a toggle.""" | |
522 |
|
522 | |||
523 | if value != 0 and not self.has_readline: |
|
523 | if value != 0 and not self.has_readline: | |
524 | if os.name == 'posix': |
|
524 | if os.name == 'posix': | |
525 | warn("The auto-indent feature requires the readline library") |
|
525 | warn("The auto-indent feature requires the readline library") | |
526 | self.autoindent = 0 |
|
526 | self.autoindent = 0 | |
527 | return |
|
527 | return | |
528 | if value is None: |
|
528 | if value is None: | |
529 | self.autoindent = not self.autoindent |
|
529 | self.autoindent = not self.autoindent | |
530 | else: |
|
530 | else: | |
531 | self.autoindent = value |
|
531 | self.autoindent = value | |
532 |
|
532 | |||
533 | #------------------------------------------------------------------------- |
|
533 | #------------------------------------------------------------------------- | |
534 | # init_* methods called by __init__ |
|
534 | # init_* methods called by __init__ | |
535 | #------------------------------------------------------------------------- |
|
535 | #------------------------------------------------------------------------- | |
536 |
|
536 | |||
537 | def init_ipython_dir(self, ipython_dir): |
|
537 | def init_ipython_dir(self, ipython_dir): | |
538 | if ipython_dir is not None: |
|
538 | if ipython_dir is not None: | |
539 | self.ipython_dir = ipython_dir |
|
539 | self.ipython_dir = ipython_dir | |
540 | return |
|
540 | return | |
541 |
|
541 | |||
542 | self.ipython_dir = get_ipython_dir() |
|
542 | self.ipython_dir = get_ipython_dir() | |
543 |
|
543 | |||
544 | def init_profile_dir(self, profile_dir): |
|
544 | def init_profile_dir(self, profile_dir): | |
545 | if profile_dir is not None: |
|
545 | if profile_dir is not None: | |
546 | self.profile_dir = profile_dir |
|
546 | self.profile_dir = profile_dir | |
547 | return |
|
547 | return | |
548 | self.profile_dir =\ |
|
548 | self.profile_dir =\ | |
549 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
549 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') | |
550 |
|
550 | |||
551 | def init_instance_attrs(self): |
|
551 | def init_instance_attrs(self): | |
552 | self.more = False |
|
552 | self.more = False | |
553 |
|
553 | |||
554 | # command compiler |
|
554 | # command compiler | |
555 | self.compile = CachingCompiler() |
|
555 | self.compile = CachingCompiler() | |
556 |
|
556 | |||
557 | # Make an empty namespace, which extension writers can rely on both |
|
557 | # Make an empty namespace, which extension writers can rely on both | |
558 | # existing and NEVER being used by ipython itself. This gives them a |
|
558 | # existing and NEVER being used by ipython itself. This gives them a | |
559 | # convenient location for storing additional information and state |
|
559 | # convenient location for storing additional information and state | |
560 | # their extensions may require, without fear of collisions with other |
|
560 | # their extensions may require, without fear of collisions with other | |
561 | # ipython names that may develop later. |
|
561 | # ipython names that may develop later. | |
562 | self.meta = Struct() |
|
562 | self.meta = Struct() | |
563 |
|
563 | |||
564 | # Temporary files used for various purposes. Deleted at exit. |
|
564 | # Temporary files used for various purposes. Deleted at exit. | |
565 | self.tempfiles = [] |
|
565 | self.tempfiles = [] | |
566 |
|
566 | |||
567 | # Keep track of readline usage (later set by init_readline) |
|
567 | # Keep track of readline usage (later set by init_readline) | |
568 | self.has_readline = False |
|
568 | self.has_readline = False | |
569 |
|
569 | |||
570 | # keep track of where we started running (mainly for crash post-mortem) |
|
570 | # keep track of where we started running (mainly for crash post-mortem) | |
571 | # This is not being used anywhere currently. |
|
571 | # This is not being used anywhere currently. | |
572 | self.starting_dir = os.getcwdu() |
|
572 | self.starting_dir = os.getcwdu() | |
573 |
|
573 | |||
574 | # Indentation management |
|
574 | # Indentation management | |
575 | self.indent_current_nsp = 0 |
|
575 | self.indent_current_nsp = 0 | |
576 |
|
576 | |||
577 | # Dict to track post-execution functions that have been registered |
|
577 | # Dict to track post-execution functions that have been registered | |
578 | self._post_execute = {} |
|
578 | self._post_execute = {} | |
579 |
|
579 | |||
580 | def init_environment(self): |
|
580 | def init_environment(self): | |
581 | """Any changes we need to make to the user's environment.""" |
|
581 | """Any changes we need to make to the user's environment.""" | |
582 | pass |
|
582 | pass | |
583 |
|
583 | |||
584 | def init_encoding(self): |
|
584 | def init_encoding(self): | |
585 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
585 | # Get system encoding at startup time. Certain terminals (like Emacs | |
586 | # under Win32 have it set to None, and we need to have a known valid |
|
586 | # under Win32 have it set to None, and we need to have a known valid | |
587 | # encoding to use in the raw_input() method |
|
587 | # encoding to use in the raw_input() method | |
588 | try: |
|
588 | try: | |
589 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
589 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
590 | except AttributeError: |
|
590 | except AttributeError: | |
591 | self.stdin_encoding = 'ascii' |
|
591 | self.stdin_encoding = 'ascii' | |
592 |
|
592 | |||
593 | def init_syntax_highlighting(self): |
|
593 | def init_syntax_highlighting(self): | |
594 | # Python source parser/formatter for syntax highlighting |
|
594 | # Python source parser/formatter for syntax highlighting | |
595 | pyformat = PyColorize.Parser().format |
|
595 | pyformat = PyColorize.Parser().format | |
596 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
596 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
597 |
|
597 | |||
598 | def init_pushd_popd_magic(self): |
|
598 | def init_pushd_popd_magic(self): | |
599 | # for pushd/popd management |
|
599 | # for pushd/popd management | |
600 | self.home_dir = get_home_dir() |
|
600 | self.home_dir = get_home_dir() | |
601 |
|
601 | |||
602 | self.dir_stack = [] |
|
602 | self.dir_stack = [] | |
603 |
|
603 | |||
604 | def init_logger(self): |
|
604 | def init_logger(self): | |
605 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
605 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
606 | logmode='rotate') |
|
606 | logmode='rotate') | |
607 |
|
607 | |||
608 | def init_logstart(self): |
|
608 | def init_logstart(self): | |
609 | """Initialize logging in case it was requested at the command line. |
|
609 | """Initialize logging in case it was requested at the command line. | |
610 | """ |
|
610 | """ | |
611 | if self.logappend: |
|
611 | if self.logappend: | |
612 | self.magic('logstart %s append' % self.logappend) |
|
612 | self.magic('logstart %s append' % self.logappend) | |
613 | elif self.logfile: |
|
613 | elif self.logfile: | |
614 | self.magic('logstart %s' % self.logfile) |
|
614 | self.magic('logstart %s' % self.logfile) | |
615 | elif self.logstart: |
|
615 | elif self.logstart: | |
616 | self.magic('logstart') |
|
616 | self.magic('logstart') | |
617 |
|
617 | |||
618 | def init_builtins(self): |
|
618 | def init_builtins(self): | |
619 | # A single, static flag that we set to True. Its presence indicates |
|
619 | # A single, static flag that we set to True. Its presence indicates | |
620 | # that an IPython shell has been created, and we make no attempts at |
|
620 | # that an IPython shell has been created, and we make no attempts at | |
621 | # removing on exit or representing the existence of more than one |
|
621 | # removing on exit or representing the existence of more than one | |
622 | # IPython at a time. |
|
622 | # IPython at a time. | |
623 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
623 | builtin_mod.__dict__['__IPYTHON__'] = True | |
624 |
|
624 | |||
625 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to |
|
625 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to | |
626 | # manage on enter/exit, but with all our shells it's virtually |
|
626 | # manage on enter/exit, but with all our shells it's virtually | |
627 | # impossible to get all the cases right. We're leaving the name in for |
|
627 | # impossible to get all the cases right. We're leaving the name in for | |
628 | # those who adapted their codes to check for this flag, but will |
|
628 | # those who adapted their codes to check for this flag, but will | |
629 | # eventually remove it after a few more releases. |
|
629 | # eventually remove it after a few more releases. | |
630 | builtin_mod.__dict__['__IPYTHON__active'] = \ |
|
630 | builtin_mod.__dict__['__IPYTHON__active'] = \ | |
631 | 'Deprecated, check for __IPYTHON__' |
|
631 | 'Deprecated, check for __IPYTHON__' | |
632 |
|
632 | |||
633 | self.builtin_trap = BuiltinTrap(shell=self) |
|
633 | self.builtin_trap = BuiltinTrap(shell=self) | |
634 |
|
634 | |||
635 | def init_inspector(self): |
|
635 | def init_inspector(self): | |
636 | # Object inspector |
|
636 | # Object inspector | |
637 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
637 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
638 | PyColorize.ANSICodeColors, |
|
638 | PyColorize.ANSICodeColors, | |
639 | 'NoColor', |
|
639 | 'NoColor', | |
640 | self.object_info_string_level) |
|
640 | self.object_info_string_level) | |
641 |
|
641 | |||
642 | def init_io(self): |
|
642 | def init_io(self): | |
643 | # This will just use sys.stdout and sys.stderr. If you want to |
|
643 | # This will just use sys.stdout and sys.stderr. If you want to | |
644 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
644 | # override sys.stdout and sys.stderr themselves, you need to do that | |
645 | # *before* instantiating this class, because io holds onto |
|
645 | # *before* instantiating this class, because io holds onto | |
646 | # references to the underlying streams. |
|
646 | # references to the underlying streams. | |
647 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: |
|
647 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: | |
648 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
648 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) | |
649 | else: |
|
649 | else: | |
650 | io.stdout = io.IOStream(sys.stdout) |
|
650 | io.stdout = io.IOStream(sys.stdout) | |
651 | io.stderr = io.IOStream(sys.stderr) |
|
651 | io.stderr = io.IOStream(sys.stderr) | |
652 |
|
652 | |||
653 | def init_prompts(self): |
|
653 | def init_prompts(self): | |
654 | self.prompt_manager = PromptManager(shell=self, parent=self) |
|
654 | self.prompt_manager = PromptManager(shell=self, parent=self) | |
655 | self.configurables.append(self.prompt_manager) |
|
655 | self.configurables.append(self.prompt_manager) | |
656 | # Set system prompts, so that scripts can decide if they are running |
|
656 | # Set system prompts, so that scripts can decide if they are running | |
657 | # interactively. |
|
657 | # interactively. | |
658 | sys.ps1 = 'In : ' |
|
658 | sys.ps1 = 'In : ' | |
659 | sys.ps2 = '...: ' |
|
659 | sys.ps2 = '...: ' | |
660 | sys.ps3 = 'Out: ' |
|
660 | sys.ps3 = 'Out: ' | |
661 |
|
661 | |||
662 | def init_display_formatter(self): |
|
662 | def init_display_formatter(self): | |
663 | self.display_formatter = DisplayFormatter(parent=self) |
|
663 | self.display_formatter = DisplayFormatter(parent=self) | |
664 | self.configurables.append(self.display_formatter) |
|
664 | self.configurables.append(self.display_formatter) | |
665 |
|
665 | |||
666 | def init_display_pub(self): |
|
666 | def init_display_pub(self): | |
667 | self.display_pub = self.display_pub_class(parent=self) |
|
667 | self.display_pub = self.display_pub_class(parent=self) | |
668 | self.configurables.append(self.display_pub) |
|
668 | self.configurables.append(self.display_pub) | |
669 |
|
669 | |||
670 | def init_data_pub(self): |
|
670 | def init_data_pub(self): | |
671 | if not self.data_pub_class: |
|
671 | if not self.data_pub_class: | |
672 | self.data_pub = None |
|
672 | self.data_pub = None | |
673 | return |
|
673 | return | |
674 | self.data_pub = self.data_pub_class(parent=self) |
|
674 | self.data_pub = self.data_pub_class(parent=self) | |
675 | self.configurables.append(self.data_pub) |
|
675 | self.configurables.append(self.data_pub) | |
676 |
|
676 | |||
677 | def init_displayhook(self): |
|
677 | def init_displayhook(self): | |
678 | # Initialize displayhook, set in/out prompts and printing system |
|
678 | # Initialize displayhook, set in/out prompts and printing system | |
679 | self.displayhook = self.displayhook_class( |
|
679 | self.displayhook = self.displayhook_class( | |
680 | parent=self, |
|
680 | parent=self, | |
681 | shell=self, |
|
681 | shell=self, | |
682 | cache_size=self.cache_size, |
|
682 | cache_size=self.cache_size, | |
683 | ) |
|
683 | ) | |
684 | self.configurables.append(self.displayhook) |
|
684 | self.configurables.append(self.displayhook) | |
685 | # This is a context manager that installs/revmoes the displayhook at |
|
685 | # This is a context manager that installs/revmoes the displayhook at | |
686 | # the appropriate time. |
|
686 | # the appropriate time. | |
687 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
687 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
688 |
|
688 | |||
689 | def init_latextool(self): |
|
689 | def init_latextool(self): | |
690 | """Configure LaTeXTool.""" |
|
690 | """Configure LaTeXTool.""" | |
691 | cfg = LaTeXTool.instance(parent=self) |
|
691 | cfg = LaTeXTool.instance(parent=self) | |
692 | if cfg not in self.configurables: |
|
692 | if cfg not in self.configurables: | |
693 | self.configurables.append(cfg) |
|
693 | self.configurables.append(cfg) | |
694 |
|
694 | |||
695 | def init_virtualenv(self): |
|
695 | def init_virtualenv(self): | |
696 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
696 | """Add a virtualenv to sys.path so the user can import modules from it. | |
697 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
697 | This isn't perfect: it doesn't use the Python interpreter with which the | |
698 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
698 | virtualenv was built, and it ignores the --no-site-packages option. A | |
699 | warning will appear suggesting the user installs IPython in the |
|
699 | warning will appear suggesting the user installs IPython in the | |
700 | virtualenv, but for many cases, it probably works well enough. |
|
700 | virtualenv, but for many cases, it probably works well enough. | |
701 |
|
701 | |||
702 | Adapted from code snippets online. |
|
702 | Adapted from code snippets online. | |
703 |
|
703 | |||
704 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
704 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv | |
705 | """ |
|
705 | """ | |
706 | if 'VIRTUAL_ENV' not in os.environ: |
|
706 | if 'VIRTUAL_ENV' not in os.environ: | |
707 | # Not in a virtualenv |
|
707 | # Not in a virtualenv | |
708 | return |
|
708 | return | |
709 |
|
709 | |||
710 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): |
|
710 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): | |
711 | # Running properly in the virtualenv, don't need to do anything |
|
711 | # Running properly in the virtualenv, don't need to do anything | |
712 | return |
|
712 | return | |
713 |
|
713 | |||
714 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
714 | warn("Attempting to work in a virtualenv. If you encounter problems, please " | |
715 | "install IPython inside the virtualenv.") |
|
715 | "install IPython inside the virtualenv.") | |
716 | if sys.platform == "win32": |
|
716 | if sys.platform == "win32": | |
717 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
717 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') | |
718 | else: |
|
718 | else: | |
719 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
719 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', | |
720 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
720 | 'python%d.%d' % sys.version_info[:2], 'site-packages') | |
721 |
|
721 | |||
722 | import site |
|
722 | import site | |
723 | sys.path.insert(0, virtual_env) |
|
723 | sys.path.insert(0, virtual_env) | |
724 | site.addsitedir(virtual_env) |
|
724 | site.addsitedir(virtual_env) | |
725 |
|
725 | |||
726 | #------------------------------------------------------------------------- |
|
726 | #------------------------------------------------------------------------- | |
727 | # Things related to injections into the sys module |
|
727 | # Things related to injections into the sys module | |
728 | #------------------------------------------------------------------------- |
|
728 | #------------------------------------------------------------------------- | |
729 |
|
729 | |||
730 | def save_sys_module_state(self): |
|
730 | def save_sys_module_state(self): | |
731 | """Save the state of hooks in the sys module. |
|
731 | """Save the state of hooks in the sys module. | |
732 |
|
732 | |||
733 | This has to be called after self.user_module is created. |
|
733 | This has to be called after self.user_module is created. | |
734 | """ |
|
734 | """ | |
735 | self._orig_sys_module_state = {} |
|
735 | self._orig_sys_module_state = {} | |
736 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
736 | self._orig_sys_module_state['stdin'] = sys.stdin | |
737 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
737 | self._orig_sys_module_state['stdout'] = sys.stdout | |
738 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
738 | self._orig_sys_module_state['stderr'] = sys.stderr | |
739 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
739 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
740 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
740 | self._orig_sys_modules_main_name = self.user_module.__name__ | |
741 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
741 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) | |
742 |
|
742 | |||
743 | def restore_sys_module_state(self): |
|
743 | def restore_sys_module_state(self): | |
744 | """Restore the state of the sys module.""" |
|
744 | """Restore the state of the sys module.""" | |
745 | try: |
|
745 | try: | |
746 | for k, v in self._orig_sys_module_state.iteritems(): |
|
746 | for k, v in self._orig_sys_module_state.iteritems(): | |
747 | setattr(sys, k, v) |
|
747 | setattr(sys, k, v) | |
748 | except AttributeError: |
|
748 | except AttributeError: | |
749 | pass |
|
749 | pass | |
750 | # Reset what what done in self.init_sys_modules |
|
750 | # Reset what what done in self.init_sys_modules | |
751 | if self._orig_sys_modules_main_mod is not None: |
|
751 | if self._orig_sys_modules_main_mod is not None: | |
752 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
752 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod | |
753 |
|
753 | |||
754 | #------------------------------------------------------------------------- |
|
754 | #------------------------------------------------------------------------- | |
755 | # Things related to hooks |
|
755 | # Things related to hooks | |
756 | #------------------------------------------------------------------------- |
|
756 | #------------------------------------------------------------------------- | |
757 |
|
757 | |||
758 | def init_hooks(self): |
|
758 | def init_hooks(self): | |
759 | # hooks holds pointers used for user-side customizations |
|
759 | # hooks holds pointers used for user-side customizations | |
760 | self.hooks = Struct() |
|
760 | self.hooks = Struct() | |
761 |
|
761 | |||
762 | self.strdispatchers = {} |
|
762 | self.strdispatchers = {} | |
763 |
|
763 | |||
764 | # Set all default hooks, defined in the IPython.hooks module. |
|
764 | # Set all default hooks, defined in the IPython.hooks module. | |
765 | hooks = IPython.core.hooks |
|
765 | hooks = IPython.core.hooks | |
766 | for hook_name in hooks.__all__: |
|
766 | for hook_name in hooks.__all__: | |
767 | # default hooks have priority 100, i.e. low; user hooks should have |
|
767 | # default hooks have priority 100, i.e. low; user hooks should have | |
768 | # 0-100 priority |
|
768 | # 0-100 priority | |
769 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
769 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
770 |
|
770 | |||
771 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
771 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
772 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
772 | """set_hook(name,hook) -> sets an internal IPython hook. | |
773 |
|
773 | |||
774 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
774 | IPython exposes some of its internal API as user-modifiable hooks. By | |
775 | adding your function to one of these hooks, you can modify IPython's |
|
775 | adding your function to one of these hooks, you can modify IPython's | |
776 | behavior to call at runtime your own routines.""" |
|
776 | behavior to call at runtime your own routines.""" | |
777 |
|
777 | |||
778 | # At some point in the future, this should validate the hook before it |
|
778 | # At some point in the future, this should validate the hook before it | |
779 | # accepts it. Probably at least check that the hook takes the number |
|
779 | # accepts it. Probably at least check that the hook takes the number | |
780 | # of args it's supposed to. |
|
780 | # of args it's supposed to. | |
781 |
|
781 | |||
782 | f = types.MethodType(hook,self) |
|
782 | f = types.MethodType(hook,self) | |
783 |
|
783 | |||
784 | # check if the hook is for strdispatcher first |
|
784 | # check if the hook is for strdispatcher first | |
785 | if str_key is not None: |
|
785 | if str_key is not None: | |
786 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
786 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
787 | sdp.add_s(str_key, f, priority ) |
|
787 | sdp.add_s(str_key, f, priority ) | |
788 | self.strdispatchers[name] = sdp |
|
788 | self.strdispatchers[name] = sdp | |
789 | return |
|
789 | return | |
790 | if re_key is not None: |
|
790 | if re_key is not None: | |
791 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
791 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
792 | sdp.add_re(re.compile(re_key), f, priority ) |
|
792 | sdp.add_re(re.compile(re_key), f, priority ) | |
793 | self.strdispatchers[name] = sdp |
|
793 | self.strdispatchers[name] = sdp | |
794 | return |
|
794 | return | |
795 |
|
795 | |||
796 | dp = getattr(self.hooks, name, None) |
|
796 | dp = getattr(self.hooks, name, None) | |
797 | if name not in IPython.core.hooks.__all__: |
|
797 | if name not in IPython.core.hooks.__all__: | |
798 | print("Warning! Hook '%s' is not one of %s" % \ |
|
798 | print("Warning! Hook '%s' is not one of %s" % \ | |
799 | (name, IPython.core.hooks.__all__ )) |
|
799 | (name, IPython.core.hooks.__all__ )) | |
800 | if not dp: |
|
800 | if not dp: | |
801 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
801 | dp = IPython.core.hooks.CommandChainDispatcher() | |
802 |
|
802 | |||
803 | try: |
|
803 | try: | |
804 | dp.add(f,priority) |
|
804 | dp.add(f,priority) | |
805 | except AttributeError: |
|
805 | except AttributeError: | |
806 | # it was not commandchain, plain old func - replace |
|
806 | # it was not commandchain, plain old func - replace | |
807 | dp = f |
|
807 | dp = f | |
808 |
|
808 | |||
809 | setattr(self.hooks,name, dp) |
|
809 | setattr(self.hooks,name, dp) | |
810 |
|
810 | |||
811 | def register_post_execute(self, func): |
|
811 | def register_post_execute(self, func): | |
812 | """Register a function for calling after code execution. |
|
812 | """Register a function for calling after code execution. | |
813 | """ |
|
813 | """ | |
814 | if not callable(func): |
|
814 | if not callable(func): | |
815 | raise ValueError('argument %s must be callable' % func) |
|
815 | raise ValueError('argument %s must be callable' % func) | |
816 | self._post_execute[func] = True |
|
816 | self._post_execute[func] = True | |
817 |
|
817 | |||
818 | #------------------------------------------------------------------------- |
|
818 | #------------------------------------------------------------------------- | |
819 | # Things related to the "main" module |
|
819 | # Things related to the "main" module | |
820 | #------------------------------------------------------------------------- |
|
820 | #------------------------------------------------------------------------- | |
821 |
|
821 | |||
822 |
def new_main_mod(self, |
|
822 | def new_main_mod(self,filename): | |
823 | """Return a new 'main' module object for user code execution. |
|
823 | """Return a new 'main' module object for user code execution. | |
824 |
|
|
824 | ||
825 | main_mod = self._user_main_module |
|
|||
826 | init_fakemod_dict(main_mod,ns) |
|
|||
827 | return main_mod |
|
|||
828 |
|
||||
829 | def cache_main_mod(self,ns,fname): |
|
|||
830 | """Cache a main module's namespace. |
|
|||
831 |
|
||||
832 | When scripts are executed via %run, we must keep a reference to the |
|
825 | When scripts are executed via %run, we must keep a reference to the | |
833 | namespace of their __main__ module (a FakeModule instance) around so |
|
826 | namespace of their __main__ module (a FakeModule instance) around so | |
834 | that Python doesn't clear it, rendering objects defined therein |
|
827 | that Python doesn't clear it, rendering objects defined therein | |
835 | useless. |
|
828 | useless. | |
836 |
|
829 | |||
837 | This method keeps said reference in a private dict, keyed by the |
|
830 | This method keeps said reference in a private dict, keyed by the | |
838 | absolute path of the module object (which corresponds to the script |
|
831 | absolute path of the module object (which corresponds to the script | |
839 | path). This way, for multiple executions of the same script we only |
|
832 | path). This way, for multiple executions of the same script we only | |
840 | keep one copy of the namespace (the last one), thus preventing memory |
|
833 | keep one copy of the namespace (the last one), thus preventing memory | |
841 | leaks from old references while allowing the objects from the last |
|
834 | leaks from old references while allowing the objects from the last | |
842 | execution to be accessible. |
|
835 | execution to be accessible. | |
843 |
|
||||
844 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
|||
845 | because of how Python tears down modules (it hard-sets all their |
|
|||
846 | references to None without regard for reference counts). This method |
|
|||
847 | must therefore make a *copy* of the given namespace, to allow the |
|
|||
848 | original module's __dict__ to be cleared and reused. |
|
|||
849 |
|
||||
850 |
|
||||
851 | Parameters |
|
|||
852 | ---------- |
|
|||
853 | ns : a namespace (a dict, typically) |
|
|||
854 |
|
||||
855 | fname : str |
|
|||
856 | Filename associated with the namespace. |
|
|||
857 |
|
||||
858 | Examples |
|
|||
859 | -------- |
|
|||
860 |
|
||||
861 | In [10]: import IPython |
|
|||
862 |
|
||||
863 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
|||
864 |
|
||||
865 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
|||
866 | Out[12]: True |
|
|||
867 | """ |
|
836 | """ | |
868 |
|
|
837 | filename = os.path.abspath(filename) | |
|
838 | try: | |||
|
839 | main_mod = self._main_mod_cache[filename] | |||
|
840 | except KeyError: | |||
|
841 | main_mod = self._main_mod_cache[filename] = FakeModule() | |||
|
842 | else: | |||
|
843 | init_fakemod_dict(main_mod) | |||
|
844 | ||||
|
845 | return main_mod | |||
869 |
|
846 | |||
870 | def clear_main_mod_cache(self): |
|
847 | def clear_main_mod_cache(self): | |
871 | """Clear the cache of main modules. |
|
848 | """Clear the cache of main modules. | |
872 |
|
849 | |||
873 | Mainly for use by utilities like %reset. |
|
850 | Mainly for use by utilities like %reset. | |
874 |
|
851 | |||
875 | Examples |
|
852 | Examples | |
876 | -------- |
|
853 | -------- | |
877 |
|
854 | |||
878 | In [15]: import IPython |
|
855 | In [15]: import IPython | |
879 |
|
856 | |||
880 |
In [16]: |
|
857 | In [16]: m = _ip.new_main_mod(IPython.__file__) | |
881 |
|
858 | |||
882 |
In [17]: len(_ip._main_ |
|
859 | In [17]: len(_ip._main_mod_cache) > 0 | |
883 | Out[17]: True |
|
860 | Out[17]: True | |
884 |
|
861 | |||
885 | In [18]: _ip.clear_main_mod_cache() |
|
862 | In [18]: _ip.clear_main_mod_cache() | |
886 |
|
863 | |||
887 |
In [19]: len(_ip._main_ |
|
864 | In [19]: len(_ip._main_mod_cache) == 0 | |
888 | Out[19]: True |
|
865 | Out[19]: True | |
889 | """ |
|
866 | """ | |
890 |
self._main_ |
|
867 | self._main_mod_cache.clear() | |
891 |
|
868 | |||
892 | #------------------------------------------------------------------------- |
|
869 | #------------------------------------------------------------------------- | |
893 | # Things related to debugging |
|
870 | # Things related to debugging | |
894 | #------------------------------------------------------------------------- |
|
871 | #------------------------------------------------------------------------- | |
895 |
|
872 | |||
896 | def init_pdb(self): |
|
873 | def init_pdb(self): | |
897 | # Set calling of pdb on exceptions |
|
874 | # Set calling of pdb on exceptions | |
898 | # self.call_pdb is a property |
|
875 | # self.call_pdb is a property | |
899 | self.call_pdb = self.pdb |
|
876 | self.call_pdb = self.pdb | |
900 |
|
877 | |||
901 | def _get_call_pdb(self): |
|
878 | def _get_call_pdb(self): | |
902 | return self._call_pdb |
|
879 | return self._call_pdb | |
903 |
|
880 | |||
904 | def _set_call_pdb(self,val): |
|
881 | def _set_call_pdb(self,val): | |
905 |
|
882 | |||
906 | if val not in (0,1,False,True): |
|
883 | if val not in (0,1,False,True): | |
907 | raise ValueError('new call_pdb value must be boolean') |
|
884 | raise ValueError('new call_pdb value must be boolean') | |
908 |
|
885 | |||
909 | # store value in instance |
|
886 | # store value in instance | |
910 | self._call_pdb = val |
|
887 | self._call_pdb = val | |
911 |
|
888 | |||
912 | # notify the actual exception handlers |
|
889 | # notify the actual exception handlers | |
913 | self.InteractiveTB.call_pdb = val |
|
890 | self.InteractiveTB.call_pdb = val | |
914 |
|
891 | |||
915 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
892 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
916 | 'Control auto-activation of pdb at exceptions') |
|
893 | 'Control auto-activation of pdb at exceptions') | |
917 |
|
894 | |||
918 | def debugger(self,force=False): |
|
895 | def debugger(self,force=False): | |
919 | """Call the pydb/pdb debugger. |
|
896 | """Call the pydb/pdb debugger. | |
920 |
|
897 | |||
921 | Keywords: |
|
898 | Keywords: | |
922 |
|
899 | |||
923 | - force(False): by default, this routine checks the instance call_pdb |
|
900 | - force(False): by default, this routine checks the instance call_pdb | |
924 | flag and does not actually invoke the debugger if the flag is false. |
|
901 | flag and does not actually invoke the debugger if the flag is false. | |
925 | The 'force' option forces the debugger to activate even if the flag |
|
902 | The 'force' option forces the debugger to activate even if the flag | |
926 | is false. |
|
903 | is false. | |
927 | """ |
|
904 | """ | |
928 |
|
905 | |||
929 | if not (force or self.call_pdb): |
|
906 | if not (force or self.call_pdb): | |
930 | return |
|
907 | return | |
931 |
|
908 | |||
932 | if not hasattr(sys,'last_traceback'): |
|
909 | if not hasattr(sys,'last_traceback'): | |
933 | error('No traceback has been produced, nothing to debug.') |
|
910 | error('No traceback has been produced, nothing to debug.') | |
934 | return |
|
911 | return | |
935 |
|
912 | |||
936 | # use pydb if available |
|
913 | # use pydb if available | |
937 | if debugger.has_pydb: |
|
914 | if debugger.has_pydb: | |
938 | from pydb import pm |
|
915 | from pydb import pm | |
939 | else: |
|
916 | else: | |
940 | # fallback to our internal debugger |
|
917 | # fallback to our internal debugger | |
941 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
918 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
942 |
|
919 | |||
943 | with self.readline_no_record: |
|
920 | with self.readline_no_record: | |
944 | pm() |
|
921 | pm() | |
945 |
|
922 | |||
946 | #------------------------------------------------------------------------- |
|
923 | #------------------------------------------------------------------------- | |
947 | # Things related to IPython's various namespaces |
|
924 | # Things related to IPython's various namespaces | |
948 | #------------------------------------------------------------------------- |
|
925 | #------------------------------------------------------------------------- | |
949 | default_user_namespaces = True |
|
926 | default_user_namespaces = True | |
950 |
|
927 | |||
951 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
928 | def init_create_namespaces(self, user_module=None, user_ns=None): | |
952 | # Create the namespace where the user will operate. user_ns is |
|
929 | # Create the namespace where the user will operate. user_ns is | |
953 | # normally the only one used, and it is passed to the exec calls as |
|
930 | # normally the only one used, and it is passed to the exec calls as | |
954 | # the locals argument. But we do carry a user_global_ns namespace |
|
931 | # the locals argument. But we do carry a user_global_ns namespace | |
955 | # given as the exec 'globals' argument, This is useful in embedding |
|
932 | # given as the exec 'globals' argument, This is useful in embedding | |
956 | # situations where the ipython shell opens in a context where the |
|
933 | # situations where the ipython shell opens in a context where the | |
957 | # distinction between locals and globals is meaningful. For |
|
934 | # distinction between locals and globals is meaningful. For | |
958 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
935 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
959 |
|
936 | |||
960 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
937 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
961 | # level as a dict instead of a module. This is a manual fix, but I |
|
938 | # level as a dict instead of a module. This is a manual fix, but I | |
962 | # should really track down where the problem is coming from. Alex |
|
939 | # should really track down where the problem is coming from. Alex | |
963 | # Schmolck reported this problem first. |
|
940 | # Schmolck reported this problem first. | |
964 |
|
941 | |||
965 | # A useful post by Alex Martelli on this topic: |
|
942 | # A useful post by Alex Martelli on this topic: | |
966 | # Re: inconsistent value from __builtins__ |
|
943 | # Re: inconsistent value from __builtins__ | |
967 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
944 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
968 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
945 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
969 | # Gruppen: comp.lang.python |
|
946 | # Gruppen: comp.lang.python | |
970 |
|
947 | |||
971 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
948 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
972 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
949 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
973 | # > <type 'dict'> |
|
950 | # > <type 'dict'> | |
974 | # > >>> print type(__builtins__) |
|
951 | # > >>> print type(__builtins__) | |
975 | # > <type 'module'> |
|
952 | # > <type 'module'> | |
976 | # > Is this difference in return value intentional? |
|
953 | # > Is this difference in return value intentional? | |
977 |
|
954 | |||
978 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
955 | # Well, it's documented that '__builtins__' can be either a dictionary | |
979 | # or a module, and it's been that way for a long time. Whether it's |
|
956 | # or a module, and it's been that way for a long time. Whether it's | |
980 | # intentional (or sensible), I don't know. In any case, the idea is |
|
957 | # intentional (or sensible), I don't know. In any case, the idea is | |
981 | # that if you need to access the built-in namespace directly, you |
|
958 | # that if you need to access the built-in namespace directly, you | |
982 | # should start with "import __builtin__" (note, no 's') which will |
|
959 | # should start with "import __builtin__" (note, no 's') which will | |
983 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
960 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
984 |
|
961 | |||
985 | # These routines return a properly built module and dict as needed by |
|
962 | # These routines return a properly built module and dict as needed by | |
986 | # the rest of the code, and can also be used by extension writers to |
|
963 | # the rest of the code, and can also be used by extension writers to | |
987 | # generate properly initialized namespaces. |
|
964 | # generate properly initialized namespaces. | |
988 | if (user_ns is not None) or (user_module is not None): |
|
965 | if (user_ns is not None) or (user_module is not None): | |
989 | self.default_user_namespaces = False |
|
966 | self.default_user_namespaces = False | |
990 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
967 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) | |
991 |
|
968 | |||
992 | # A record of hidden variables we have added to the user namespace, so |
|
969 | # A record of hidden variables we have added to the user namespace, so | |
993 | # we can list later only variables defined in actual interactive use. |
|
970 | # we can list later only variables defined in actual interactive use. | |
994 | self.user_ns_hidden = set() |
|
971 | self.user_ns_hidden = set() | |
995 |
|
972 | |||
996 | # Now that FakeModule produces a real module, we've run into a nasty |
|
973 | # Now that FakeModule produces a real module, we've run into a nasty | |
997 | # problem: after script execution (via %run), the module where the user |
|
974 | # problem: after script execution (via %run), the module where the user | |
998 | # code ran is deleted. Now that this object is a true module (needed |
|
975 | # code ran is deleted. Now that this object is a true module (needed | |
999 | # so docetst and other tools work correctly), the Python module |
|
976 | # so docetst and other tools work correctly), the Python module | |
1000 | # teardown mechanism runs over it, and sets to None every variable |
|
977 | # teardown mechanism runs over it, and sets to None every variable | |
1001 | # present in that module. Top-level references to objects from the |
|
978 | # present in that module. Top-level references to objects from the | |
1002 | # script survive, because the user_ns is updated with them. However, |
|
979 | # script survive, because the user_ns is updated with them. However, | |
1003 | # calling functions defined in the script that use other things from |
|
980 | # calling functions defined in the script that use other things from | |
1004 | # the script will fail, because the function's closure had references |
|
981 | # the script will fail, because the function's closure had references | |
1005 | # to the original objects, which are now all None. So we must protect |
|
982 | # to the original objects, which are now all None. So we must protect | |
1006 | # these modules from deletion by keeping a cache. |
|
983 | # these modules from deletion by keeping a cache. | |
1007 | # |
|
984 | # | |
1008 | # To avoid keeping stale modules around (we only need the one from the |
|
985 | # To avoid keeping stale modules around (we only need the one from the | |
1009 | # last run), we use a dict keyed with the full path to the script, so |
|
986 | # last run), we use a dict keyed with the full path to the script, so | |
1010 | # only the last version of the module is held in the cache. Note, |
|
987 | # only the last version of the module is held in the cache. Note, | |
1011 | # however, that we must cache the module *namespace contents* (their |
|
988 | # however, that we must cache the module *namespace contents* (their | |
1012 | # __dict__). Because if we try to cache the actual modules, old ones |
|
989 | # __dict__). Because if we try to cache the actual modules, old ones | |
1013 | # (uncached) could be destroyed while still holding references (such as |
|
990 | # (uncached) could be destroyed while still holding references (such as | |
1014 | # those held by GUI objects that tend to be long-lived)> |
|
991 | # those held by GUI objects that tend to be long-lived)> | |
1015 | # |
|
992 | # | |
1016 | # The %reset command will flush this cache. See the cache_main_mod() |
|
993 | # The %reset command will flush this cache. See the cache_main_mod() | |
1017 | # and clear_main_mod_cache() methods for details on use. |
|
994 | # and clear_main_mod_cache() methods for details on use. | |
1018 |
|
995 | |||
1019 | # This is the cache used for 'main' namespaces |
|
996 | # This is the cache used for 'main' namespaces | |
1020 |
self._main_ |
|
997 | self._main_mod_cache = {} | |
1021 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
|||
1022 | # copying and clearing for reuse on each %run |
|
|||
1023 | self._user_main_module = FakeModule() |
|
|||
1024 |
|
998 | |||
1025 | # A table holding all the namespaces IPython deals with, so that |
|
999 | # A table holding all the namespaces IPython deals with, so that | |
1026 | # introspection facilities can search easily. |
|
1000 | # introspection facilities can search easily. | |
1027 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1001 | self.ns_table = {'user_global':self.user_module.__dict__, | |
1028 | 'user_local':self.user_ns, |
|
1002 | 'user_local':self.user_ns, | |
1029 | 'builtin':builtin_mod.__dict__ |
|
1003 | 'builtin':builtin_mod.__dict__ | |
1030 | } |
|
1004 | } | |
1031 |
|
1005 | |||
1032 | @property |
|
1006 | @property | |
1033 | def user_global_ns(self): |
|
1007 | def user_global_ns(self): | |
1034 | return self.user_module.__dict__ |
|
1008 | return self.user_module.__dict__ | |
1035 |
|
1009 | |||
1036 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1010 | def prepare_user_module(self, user_module=None, user_ns=None): | |
1037 | """Prepare the module and namespace in which user code will be run. |
|
1011 | """Prepare the module and namespace in which user code will be run. | |
1038 |
|
1012 | |||
1039 | When IPython is started normally, both parameters are None: a new module |
|
1013 | When IPython is started normally, both parameters are None: a new module | |
1040 | is created automatically, and its __dict__ used as the namespace. |
|
1014 | is created automatically, and its __dict__ used as the namespace. | |
1041 |
|
1015 | |||
1042 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1016 | If only user_module is provided, its __dict__ is used as the namespace. | |
1043 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1017 | If only user_ns is provided, a dummy module is created, and user_ns | |
1044 | becomes the global namespace. If both are provided (as they may be |
|
1018 | becomes the global namespace. If both are provided (as they may be | |
1045 | when embedding), user_ns is the local namespace, and user_module |
|
1019 | when embedding), user_ns is the local namespace, and user_module | |
1046 | provides the global namespace. |
|
1020 | provides the global namespace. | |
1047 |
|
1021 | |||
1048 | Parameters |
|
1022 | Parameters | |
1049 | ---------- |
|
1023 | ---------- | |
1050 | user_module : module, optional |
|
1024 | user_module : module, optional | |
1051 | The current user module in which IPython is being run. If None, |
|
1025 | The current user module in which IPython is being run. If None, | |
1052 | a clean module will be created. |
|
1026 | a clean module will be created. | |
1053 | user_ns : dict, optional |
|
1027 | user_ns : dict, optional | |
1054 | A namespace in which to run interactive commands. |
|
1028 | A namespace in which to run interactive commands. | |
1055 |
|
1029 | |||
1056 | Returns |
|
1030 | Returns | |
1057 | ------- |
|
1031 | ------- | |
1058 | A tuple of user_module and user_ns, each properly initialised. |
|
1032 | A tuple of user_module and user_ns, each properly initialised. | |
1059 | """ |
|
1033 | """ | |
1060 | if user_module is None and user_ns is not None: |
|
1034 | if user_module is None and user_ns is not None: | |
1061 | user_ns.setdefault("__name__", "__main__") |
|
1035 | user_ns.setdefault("__name__", "__main__") | |
1062 | class DummyMod(object): |
|
1036 | class DummyMod(object): | |
1063 | "A dummy module used for IPython's interactive namespace." |
|
1037 | "A dummy module used for IPython's interactive namespace." | |
1064 | pass |
|
1038 | pass | |
1065 | user_module = DummyMod() |
|
1039 | user_module = DummyMod() | |
1066 | user_module.__dict__ = user_ns |
|
1040 | user_module.__dict__ = user_ns | |
1067 |
|
1041 | |||
1068 | if user_module is None: |
|
1042 | if user_module is None: | |
1069 | user_module = types.ModuleType("__main__", |
|
1043 | user_module = types.ModuleType("__main__", | |
1070 | doc="Automatically created module for IPython interactive environment") |
|
1044 | doc="Automatically created module for IPython interactive environment") | |
1071 |
|
1045 | |||
1072 | # We must ensure that __builtin__ (without the final 's') is always |
|
1046 | # We must ensure that __builtin__ (without the final 's') is always | |
1073 | # available and pointing to the __builtin__ *module*. For more details: |
|
1047 | # available and pointing to the __builtin__ *module*. For more details: | |
1074 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1048 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1075 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1049 | user_module.__dict__.setdefault('__builtin__', builtin_mod) | |
1076 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1050 | user_module.__dict__.setdefault('__builtins__', builtin_mod) | |
1077 |
|
1051 | |||
1078 | if user_ns is None: |
|
1052 | if user_ns is None: | |
1079 | user_ns = user_module.__dict__ |
|
1053 | user_ns = user_module.__dict__ | |
1080 |
|
1054 | |||
1081 | return user_module, user_ns |
|
1055 | return user_module, user_ns | |
1082 |
|
1056 | |||
1083 | def init_sys_modules(self): |
|
1057 | def init_sys_modules(self): | |
1084 | # We need to insert into sys.modules something that looks like a |
|
1058 | # We need to insert into sys.modules something that looks like a | |
1085 | # module but which accesses the IPython namespace, for shelve and |
|
1059 | # module but which accesses the IPython namespace, for shelve and | |
1086 | # pickle to work interactively. Normally they rely on getting |
|
1060 | # pickle to work interactively. Normally they rely on getting | |
1087 | # everything out of __main__, but for embedding purposes each IPython |
|
1061 | # everything out of __main__, but for embedding purposes each IPython | |
1088 | # instance has its own private namespace, so we can't go shoving |
|
1062 | # instance has its own private namespace, so we can't go shoving | |
1089 | # everything into __main__. |
|
1063 | # everything into __main__. | |
1090 |
|
1064 | |||
1091 | # note, however, that we should only do this for non-embedded |
|
1065 | # note, however, that we should only do this for non-embedded | |
1092 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1066 | # ipythons, which really mimic the __main__.__dict__ with their own | |
1093 | # namespace. Embedded instances, on the other hand, should not do |
|
1067 | # namespace. Embedded instances, on the other hand, should not do | |
1094 | # this because they need to manage the user local/global namespaces |
|
1068 | # this because they need to manage the user local/global namespaces | |
1095 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1069 | # only, but they live within a 'normal' __main__ (meaning, they | |
1096 | # shouldn't overtake the execution environment of the script they're |
|
1070 | # shouldn't overtake the execution environment of the script they're | |
1097 | # embedded in). |
|
1071 | # embedded in). | |
1098 |
|
1072 | |||
1099 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1073 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
1100 | main_name = self.user_module.__name__ |
|
1074 | main_name = self.user_module.__name__ | |
1101 | sys.modules[main_name] = self.user_module |
|
1075 | sys.modules[main_name] = self.user_module | |
1102 |
|
1076 | |||
1103 | def init_user_ns(self): |
|
1077 | def init_user_ns(self): | |
1104 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1078 | """Initialize all user-visible namespaces to their minimum defaults. | |
1105 |
|
1079 | |||
1106 | Certain history lists are also initialized here, as they effectively |
|
1080 | Certain history lists are also initialized here, as they effectively | |
1107 | act as user namespaces. |
|
1081 | act as user namespaces. | |
1108 |
|
1082 | |||
1109 | Notes |
|
1083 | Notes | |
1110 | ----- |
|
1084 | ----- | |
1111 | All data structures here are only filled in, they are NOT reset by this |
|
1085 | All data structures here are only filled in, they are NOT reset by this | |
1112 | method. If they were not empty before, data will simply be added to |
|
1086 | method. If they were not empty before, data will simply be added to | |
1113 | therm. |
|
1087 | therm. | |
1114 | """ |
|
1088 | """ | |
1115 | # This function works in two parts: first we put a few things in |
|
1089 | # This function works in two parts: first we put a few things in | |
1116 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1090 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
1117 | # initial variables aren't shown by %who. After the sync, we add the |
|
1091 | # initial variables aren't shown by %who. After the sync, we add the | |
1118 | # rest of what we *do* want the user to see with %who even on a new |
|
1092 | # rest of what we *do* want the user to see with %who even on a new | |
1119 | # session (probably nothing, so theye really only see their own stuff) |
|
1093 | # session (probably nothing, so theye really only see their own stuff) | |
1120 |
|
1094 | |||
1121 | # The user dict must *always* have a __builtin__ reference to the |
|
1095 | # The user dict must *always* have a __builtin__ reference to the | |
1122 | # Python standard __builtin__ namespace, which must be imported. |
|
1096 | # Python standard __builtin__ namespace, which must be imported. | |
1123 | # This is so that certain operations in prompt evaluation can be |
|
1097 | # This is so that certain operations in prompt evaluation can be | |
1124 | # reliably executed with builtins. Note that we can NOT use |
|
1098 | # reliably executed with builtins. Note that we can NOT use | |
1125 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1099 | # __builtins__ (note the 's'), because that can either be a dict or a | |
1126 | # module, and can even mutate at runtime, depending on the context |
|
1100 | # module, and can even mutate at runtime, depending on the context | |
1127 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1101 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1128 | # always a module object, though it must be explicitly imported. |
|
1102 | # always a module object, though it must be explicitly imported. | |
1129 |
|
1103 | |||
1130 | # For more details: |
|
1104 | # For more details: | |
1131 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1105 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1132 | ns = dict() |
|
1106 | ns = dict() | |
1133 |
|
1107 | |||
1134 | # Put 'help' in the user namespace |
|
1108 | # Put 'help' in the user namespace | |
1135 | try: |
|
1109 | try: | |
1136 | from site import _Helper |
|
1110 | from site import _Helper | |
1137 | ns['help'] = _Helper() |
|
1111 | ns['help'] = _Helper() | |
1138 | except ImportError: |
|
1112 | except ImportError: | |
1139 | warn('help() not available - check site.py') |
|
1113 | warn('help() not available - check site.py') | |
1140 |
|
1114 | |||
1141 | # make global variables for user access to the histories |
|
1115 | # make global variables for user access to the histories | |
1142 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1116 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1143 | ns['_oh'] = self.history_manager.output_hist |
|
1117 | ns['_oh'] = self.history_manager.output_hist | |
1144 | ns['_dh'] = self.history_manager.dir_hist |
|
1118 | ns['_dh'] = self.history_manager.dir_hist | |
1145 |
|
1119 | |||
1146 | ns['_sh'] = shadowns |
|
1120 | ns['_sh'] = shadowns | |
1147 |
|
1121 | |||
1148 | # user aliases to input and output histories. These shouldn't show up |
|
1122 | # user aliases to input and output histories. These shouldn't show up | |
1149 | # in %who, as they can have very large reprs. |
|
1123 | # in %who, as they can have very large reprs. | |
1150 | ns['In'] = self.history_manager.input_hist_parsed |
|
1124 | ns['In'] = self.history_manager.input_hist_parsed | |
1151 | ns['Out'] = self.history_manager.output_hist |
|
1125 | ns['Out'] = self.history_manager.output_hist | |
1152 |
|
1126 | |||
1153 | # Store myself as the public api!!! |
|
1127 | # Store myself as the public api!!! | |
1154 | ns['get_ipython'] = self.get_ipython |
|
1128 | ns['get_ipython'] = self.get_ipython | |
1155 |
|
1129 | |||
1156 | ns['exit'] = self.exiter |
|
1130 | ns['exit'] = self.exiter | |
1157 | ns['quit'] = self.exiter |
|
1131 | ns['quit'] = self.exiter | |
1158 |
|
1132 | |||
1159 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1133 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1160 | # by %who |
|
1134 | # by %who | |
1161 | self.user_ns_hidden.update(ns) |
|
1135 | self.user_ns_hidden.update(ns) | |
1162 |
|
1136 | |||
1163 | # Anything put into ns now would show up in %who. Think twice before |
|
1137 | # Anything put into ns now would show up in %who. Think twice before | |
1164 | # putting anything here, as we really want %who to show the user their |
|
1138 | # putting anything here, as we really want %who to show the user their | |
1165 | # stuff, not our variables. |
|
1139 | # stuff, not our variables. | |
1166 |
|
1140 | |||
1167 | # Finally, update the real user's namespace |
|
1141 | # Finally, update the real user's namespace | |
1168 | self.user_ns.update(ns) |
|
1142 | self.user_ns.update(ns) | |
1169 |
|
1143 | |||
1170 | @property |
|
1144 | @property | |
1171 | def all_ns_refs(self): |
|
1145 | def all_ns_refs(self): | |
1172 | """Get a list of references to all the namespace dictionaries in which |
|
1146 | """Get a list of references to all the namespace dictionaries in which | |
1173 | IPython might store a user-created object. |
|
1147 | IPython might store a user-created object. | |
1174 |
|
1148 | |||
1175 | Note that this does not include the displayhook, which also caches |
|
1149 | Note that this does not include the displayhook, which also caches | |
1176 | objects from the output.""" |
|
1150 | objects from the output.""" | |
1177 |
return [self.user_ns, self.user_global_ns |
|
1151 | return [self.user_ns, self.user_global_ns] + \ | |
1178 |
|
|
1152 | [m.__dict__ for m in self._main_mod_cache.values()] | |
1179 |
|
1153 | |||
1180 | def reset(self, new_session=True): |
|
1154 | def reset(self, new_session=True): | |
1181 | """Clear all internal namespaces, and attempt to release references to |
|
1155 | """Clear all internal namespaces, and attempt to release references to | |
1182 | user objects. |
|
1156 | user objects. | |
1183 |
|
1157 | |||
1184 | If new_session is True, a new history session will be opened. |
|
1158 | If new_session is True, a new history session will be opened. | |
1185 | """ |
|
1159 | """ | |
1186 | # Clear histories |
|
1160 | # Clear histories | |
1187 | self.history_manager.reset(new_session) |
|
1161 | self.history_manager.reset(new_session) | |
1188 | # Reset counter used to index all histories |
|
1162 | # Reset counter used to index all histories | |
1189 | if new_session: |
|
1163 | if new_session: | |
1190 | self.execution_count = 1 |
|
1164 | self.execution_count = 1 | |
1191 |
|
1165 | |||
1192 | # Flush cached output items |
|
1166 | # Flush cached output items | |
1193 | if self.displayhook.do_full_cache: |
|
1167 | if self.displayhook.do_full_cache: | |
1194 | self.displayhook.flush() |
|
1168 | self.displayhook.flush() | |
1195 |
|
1169 | |||
1196 | # The main execution namespaces must be cleared very carefully, |
|
1170 | # The main execution namespaces must be cleared very carefully, | |
1197 | # skipping the deletion of the builtin-related keys, because doing so |
|
1171 | # skipping the deletion of the builtin-related keys, because doing so | |
1198 | # would cause errors in many object's __del__ methods. |
|
1172 | # would cause errors in many object's __del__ methods. | |
1199 | if self.user_ns is not self.user_global_ns: |
|
1173 | if self.user_ns is not self.user_global_ns: | |
1200 | self.user_ns.clear() |
|
1174 | self.user_ns.clear() | |
1201 | ns = self.user_global_ns |
|
1175 | ns = self.user_global_ns | |
1202 | drop_keys = set(ns.keys()) |
|
1176 | drop_keys = set(ns.keys()) | |
1203 | drop_keys.discard('__builtin__') |
|
1177 | drop_keys.discard('__builtin__') | |
1204 | drop_keys.discard('__builtins__') |
|
1178 | drop_keys.discard('__builtins__') | |
1205 | drop_keys.discard('__name__') |
|
1179 | drop_keys.discard('__name__') | |
1206 | for k in drop_keys: |
|
1180 | for k in drop_keys: | |
1207 | del ns[k] |
|
1181 | del ns[k] | |
1208 |
|
1182 | |||
1209 | self.user_ns_hidden.clear() |
|
1183 | self.user_ns_hidden.clear() | |
1210 |
|
1184 | |||
1211 | # Restore the user namespaces to minimal usability |
|
1185 | # Restore the user namespaces to minimal usability | |
1212 | self.init_user_ns() |
|
1186 | self.init_user_ns() | |
1213 |
|
1187 | |||
1214 | # Restore the default and user aliases |
|
1188 | # Restore the default and user aliases | |
1215 | self.alias_manager.clear_aliases() |
|
1189 | self.alias_manager.clear_aliases() | |
1216 | self.alias_manager.init_aliases() |
|
1190 | self.alias_manager.init_aliases() | |
1217 |
|
1191 | |||
1218 | # Flush the private list of module references kept for script |
|
1192 | # Flush the private list of module references kept for script | |
1219 | # execution protection |
|
1193 | # execution protection | |
1220 | self.clear_main_mod_cache() |
|
1194 | self.clear_main_mod_cache() | |
1221 |
|
1195 | |||
1222 | # Clear out the namespace from the last %run |
|
|||
1223 | self.new_main_mod() |
|
|||
1224 |
|
||||
1225 | def del_var(self, varname, by_name=False): |
|
1196 | def del_var(self, varname, by_name=False): | |
1226 | """Delete a variable from the various namespaces, so that, as |
|
1197 | """Delete a variable from the various namespaces, so that, as | |
1227 | far as possible, we're not keeping any hidden references to it. |
|
1198 | far as possible, we're not keeping any hidden references to it. | |
1228 |
|
1199 | |||
1229 | Parameters |
|
1200 | Parameters | |
1230 | ---------- |
|
1201 | ---------- | |
1231 | varname : str |
|
1202 | varname : str | |
1232 | The name of the variable to delete. |
|
1203 | The name of the variable to delete. | |
1233 | by_name : bool |
|
1204 | by_name : bool | |
1234 | If True, delete variables with the given name in each |
|
1205 | If True, delete variables with the given name in each | |
1235 | namespace. If False (default), find the variable in the user |
|
1206 | namespace. If False (default), find the variable in the user | |
1236 | namespace, and delete references to it. |
|
1207 | namespace, and delete references to it. | |
1237 | """ |
|
1208 | """ | |
1238 | if varname in ('__builtin__', '__builtins__'): |
|
1209 | if varname in ('__builtin__', '__builtins__'): | |
1239 | raise ValueError("Refusing to delete %s" % varname) |
|
1210 | raise ValueError("Refusing to delete %s" % varname) | |
1240 |
|
1211 | |||
1241 | ns_refs = self.all_ns_refs |
|
1212 | ns_refs = self.all_ns_refs | |
1242 |
|
1213 | |||
1243 | if by_name: # Delete by name |
|
1214 | if by_name: # Delete by name | |
1244 | for ns in ns_refs: |
|
1215 | for ns in ns_refs: | |
1245 | try: |
|
1216 | try: | |
1246 | del ns[varname] |
|
1217 | del ns[varname] | |
1247 | except KeyError: |
|
1218 | except KeyError: | |
1248 | pass |
|
1219 | pass | |
1249 | else: # Delete by object |
|
1220 | else: # Delete by object | |
1250 | try: |
|
1221 | try: | |
1251 | obj = self.user_ns[varname] |
|
1222 | obj = self.user_ns[varname] | |
1252 | except KeyError: |
|
1223 | except KeyError: | |
1253 | raise NameError("name '%s' is not defined" % varname) |
|
1224 | raise NameError("name '%s' is not defined" % varname) | |
1254 | # Also check in output history |
|
1225 | # Also check in output history | |
1255 | ns_refs.append(self.history_manager.output_hist) |
|
1226 | ns_refs.append(self.history_manager.output_hist) | |
1256 | for ns in ns_refs: |
|
1227 | for ns in ns_refs: | |
1257 | to_delete = [n for n, o in ns.iteritems() if o is obj] |
|
1228 | to_delete = [n for n, o in ns.iteritems() if o is obj] | |
1258 | for name in to_delete: |
|
1229 | for name in to_delete: | |
1259 | del ns[name] |
|
1230 | del ns[name] | |
1260 |
|
1231 | |||
1261 | # displayhook keeps extra references, but not in a dictionary |
|
1232 | # displayhook keeps extra references, but not in a dictionary | |
1262 | for name in ('_', '__', '___'): |
|
1233 | for name in ('_', '__', '___'): | |
1263 | if getattr(self.displayhook, name) is obj: |
|
1234 | if getattr(self.displayhook, name) is obj: | |
1264 | setattr(self.displayhook, name, None) |
|
1235 | setattr(self.displayhook, name, None) | |
1265 |
|
1236 | |||
1266 | def reset_selective(self, regex=None): |
|
1237 | def reset_selective(self, regex=None): | |
1267 | """Clear selective variables from internal namespaces based on a |
|
1238 | """Clear selective variables from internal namespaces based on a | |
1268 | specified regular expression. |
|
1239 | specified regular expression. | |
1269 |
|
1240 | |||
1270 | Parameters |
|
1241 | Parameters | |
1271 | ---------- |
|
1242 | ---------- | |
1272 | regex : string or compiled pattern, optional |
|
1243 | regex : string or compiled pattern, optional | |
1273 | A regular expression pattern that will be used in searching |
|
1244 | A regular expression pattern that will be used in searching | |
1274 | variable names in the users namespaces. |
|
1245 | variable names in the users namespaces. | |
1275 | """ |
|
1246 | """ | |
1276 | if regex is not None: |
|
1247 | if regex is not None: | |
1277 | try: |
|
1248 | try: | |
1278 | m = re.compile(regex) |
|
1249 | m = re.compile(regex) | |
1279 | except TypeError: |
|
1250 | except TypeError: | |
1280 | raise TypeError('regex must be a string or compiled pattern') |
|
1251 | raise TypeError('regex must be a string or compiled pattern') | |
1281 | # Search for keys in each namespace that match the given regex |
|
1252 | # Search for keys in each namespace that match the given regex | |
1282 | # If a match is found, delete the key/value pair. |
|
1253 | # If a match is found, delete the key/value pair. | |
1283 | for ns in self.all_ns_refs: |
|
1254 | for ns in self.all_ns_refs: | |
1284 | for var in ns: |
|
1255 | for var in ns: | |
1285 | if m.search(var): |
|
1256 | if m.search(var): | |
1286 | del ns[var] |
|
1257 | del ns[var] | |
1287 |
|
1258 | |||
1288 | def push(self, variables, interactive=True): |
|
1259 | def push(self, variables, interactive=True): | |
1289 | """Inject a group of variables into the IPython user namespace. |
|
1260 | """Inject a group of variables into the IPython user namespace. | |
1290 |
|
1261 | |||
1291 | Parameters |
|
1262 | Parameters | |
1292 | ---------- |
|
1263 | ---------- | |
1293 | variables : dict, str or list/tuple of str |
|
1264 | variables : dict, str or list/tuple of str | |
1294 | The variables to inject into the user's namespace. If a dict, a |
|
1265 | The variables to inject into the user's namespace. If a dict, a | |
1295 | simple update is done. If a str, the string is assumed to have |
|
1266 | simple update is done. If a str, the string is assumed to have | |
1296 | variable names separated by spaces. A list/tuple of str can also |
|
1267 | variable names separated by spaces. A list/tuple of str can also | |
1297 | be used to give the variable names. If just the variable names are |
|
1268 | be used to give the variable names. If just the variable names are | |
1298 | give (list/tuple/str) then the variable values looked up in the |
|
1269 | give (list/tuple/str) then the variable values looked up in the | |
1299 | callers frame. |
|
1270 | callers frame. | |
1300 | interactive : bool |
|
1271 | interactive : bool | |
1301 | If True (default), the variables will be listed with the ``who`` |
|
1272 | If True (default), the variables will be listed with the ``who`` | |
1302 | magic. |
|
1273 | magic. | |
1303 | """ |
|
1274 | """ | |
1304 | vdict = None |
|
1275 | vdict = None | |
1305 |
|
1276 | |||
1306 | # We need a dict of name/value pairs to do namespace updates. |
|
1277 | # We need a dict of name/value pairs to do namespace updates. | |
1307 | if isinstance(variables, dict): |
|
1278 | if isinstance(variables, dict): | |
1308 | vdict = variables |
|
1279 | vdict = variables | |
1309 | elif isinstance(variables, (basestring, list, tuple)): |
|
1280 | elif isinstance(variables, (basestring, list, tuple)): | |
1310 | if isinstance(variables, basestring): |
|
1281 | if isinstance(variables, basestring): | |
1311 | vlist = variables.split() |
|
1282 | vlist = variables.split() | |
1312 | else: |
|
1283 | else: | |
1313 | vlist = variables |
|
1284 | vlist = variables | |
1314 | vdict = {} |
|
1285 | vdict = {} | |
1315 | cf = sys._getframe(1) |
|
1286 | cf = sys._getframe(1) | |
1316 | for name in vlist: |
|
1287 | for name in vlist: | |
1317 | try: |
|
1288 | try: | |
1318 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1289 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1319 | except: |
|
1290 | except: | |
1320 | print('Could not get variable %s from %s' % |
|
1291 | print('Could not get variable %s from %s' % | |
1321 | (name,cf.f_code.co_name)) |
|
1292 | (name,cf.f_code.co_name)) | |
1322 | else: |
|
1293 | else: | |
1323 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1294 | raise ValueError('variables must be a dict/str/list/tuple') | |
1324 |
|
1295 | |||
1325 | # Propagate variables to user namespace |
|
1296 | # Propagate variables to user namespace | |
1326 | self.user_ns.update(vdict) |
|
1297 | self.user_ns.update(vdict) | |
1327 |
|
1298 | |||
1328 | # And configure interactive visibility |
|
1299 | # And configure interactive visibility | |
1329 | user_ns_hidden = self.user_ns_hidden |
|
1300 | user_ns_hidden = self.user_ns_hidden | |
1330 | if interactive: |
|
1301 | if interactive: | |
1331 | user_ns_hidden.difference_update(vdict) |
|
1302 | user_ns_hidden.difference_update(vdict) | |
1332 | else: |
|
1303 | else: | |
1333 | user_ns_hidden.update(vdict) |
|
1304 | user_ns_hidden.update(vdict) | |
1334 |
|
1305 | |||
1335 | def drop_by_id(self, variables): |
|
1306 | def drop_by_id(self, variables): | |
1336 | """Remove a dict of variables from the user namespace, if they are the |
|
1307 | """Remove a dict of variables from the user namespace, if they are the | |
1337 | same as the values in the dictionary. |
|
1308 | same as the values in the dictionary. | |
1338 |
|
1309 | |||
1339 | This is intended for use by extensions: variables that they've added can |
|
1310 | This is intended for use by extensions: variables that they've added can | |
1340 | be taken back out if they are unloaded, without removing any that the |
|
1311 | be taken back out if they are unloaded, without removing any that the | |
1341 | user has overwritten. |
|
1312 | user has overwritten. | |
1342 |
|
1313 | |||
1343 | Parameters |
|
1314 | Parameters | |
1344 | ---------- |
|
1315 | ---------- | |
1345 | variables : dict |
|
1316 | variables : dict | |
1346 | A dictionary mapping object names (as strings) to the objects. |
|
1317 | A dictionary mapping object names (as strings) to the objects. | |
1347 | """ |
|
1318 | """ | |
1348 | for name, obj in variables.iteritems(): |
|
1319 | for name, obj in variables.iteritems(): | |
1349 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1320 | if name in self.user_ns and self.user_ns[name] is obj: | |
1350 | del self.user_ns[name] |
|
1321 | del self.user_ns[name] | |
1351 | self.user_ns_hidden.discard(name) |
|
1322 | self.user_ns_hidden.discard(name) | |
1352 |
|
1323 | |||
1353 | #------------------------------------------------------------------------- |
|
1324 | #------------------------------------------------------------------------- | |
1354 | # Things related to object introspection |
|
1325 | # Things related to object introspection | |
1355 | #------------------------------------------------------------------------- |
|
1326 | #------------------------------------------------------------------------- | |
1356 |
|
1327 | |||
1357 | def _ofind(self, oname, namespaces=None): |
|
1328 | def _ofind(self, oname, namespaces=None): | |
1358 | """Find an object in the available namespaces. |
|
1329 | """Find an object in the available namespaces. | |
1359 |
|
1330 | |||
1360 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1331 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1361 |
|
1332 | |||
1362 | Has special code to detect magic functions. |
|
1333 | Has special code to detect magic functions. | |
1363 | """ |
|
1334 | """ | |
1364 | oname = oname.strip() |
|
1335 | oname = oname.strip() | |
1365 | #print '1- oname: <%r>' % oname # dbg |
|
1336 | #print '1- oname: <%r>' % oname # dbg | |
1366 | if not oname.startswith(ESC_MAGIC) and \ |
|
1337 | if not oname.startswith(ESC_MAGIC) and \ | |
1367 | not oname.startswith(ESC_MAGIC2) and \ |
|
1338 | not oname.startswith(ESC_MAGIC2) and \ | |
1368 | not py3compat.isidentifier(oname, dotted=True): |
|
1339 | not py3compat.isidentifier(oname, dotted=True): | |
1369 | return dict(found=False) |
|
1340 | return dict(found=False) | |
1370 |
|
1341 | |||
1371 | alias_ns = None |
|
1342 | alias_ns = None | |
1372 | if namespaces is None: |
|
1343 | if namespaces is None: | |
1373 | # Namespaces to search in: |
|
1344 | # Namespaces to search in: | |
1374 | # Put them in a list. The order is important so that we |
|
1345 | # Put them in a list. The order is important so that we | |
1375 | # find things in the same order that Python finds them. |
|
1346 | # find things in the same order that Python finds them. | |
1376 | namespaces = [ ('Interactive', self.user_ns), |
|
1347 | namespaces = [ ('Interactive', self.user_ns), | |
1377 | ('Interactive (global)', self.user_global_ns), |
|
1348 | ('Interactive (global)', self.user_global_ns), | |
1378 | ('Python builtin', builtin_mod.__dict__), |
|
1349 | ('Python builtin', builtin_mod.__dict__), | |
1379 | ('Alias', self.alias_manager.alias_table), |
|
1350 | ('Alias', self.alias_manager.alias_table), | |
1380 | ] |
|
1351 | ] | |
1381 | alias_ns = self.alias_manager.alias_table |
|
1352 | alias_ns = self.alias_manager.alias_table | |
1382 |
|
1353 | |||
1383 | # initialize results to 'null' |
|
1354 | # initialize results to 'null' | |
1384 | found = False; obj = None; ospace = None; ds = None; |
|
1355 | found = False; obj = None; ospace = None; ds = None; | |
1385 | ismagic = False; isalias = False; parent = None |
|
1356 | ismagic = False; isalias = False; parent = None | |
1386 |
|
1357 | |||
1387 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1358 | # We need to special-case 'print', which as of python2.6 registers as a | |
1388 | # function but should only be treated as one if print_function was |
|
1359 | # function but should only be treated as one if print_function was | |
1389 | # loaded with a future import. In this case, just bail. |
|
1360 | # loaded with a future import. In this case, just bail. | |
1390 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1361 | if (oname == 'print' and not py3compat.PY3 and not \ | |
1391 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1362 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1392 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1363 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1393 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1364 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1394 |
|
1365 | |||
1395 | # Look for the given name by splitting it in parts. If the head is |
|
1366 | # Look for the given name by splitting it in parts. If the head is | |
1396 | # found, then we look for all the remaining parts as members, and only |
|
1367 | # found, then we look for all the remaining parts as members, and only | |
1397 | # declare success if we can find them all. |
|
1368 | # declare success if we can find them all. | |
1398 | oname_parts = oname.split('.') |
|
1369 | oname_parts = oname.split('.') | |
1399 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1370 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1400 | for nsname,ns in namespaces: |
|
1371 | for nsname,ns in namespaces: | |
1401 | try: |
|
1372 | try: | |
1402 | obj = ns[oname_head] |
|
1373 | obj = ns[oname_head] | |
1403 | except KeyError: |
|
1374 | except KeyError: | |
1404 | continue |
|
1375 | continue | |
1405 | else: |
|
1376 | else: | |
1406 | #print 'oname_rest:', oname_rest # dbg |
|
1377 | #print 'oname_rest:', oname_rest # dbg | |
1407 | for part in oname_rest: |
|
1378 | for part in oname_rest: | |
1408 | try: |
|
1379 | try: | |
1409 | parent = obj |
|
1380 | parent = obj | |
1410 | obj = getattr(obj,part) |
|
1381 | obj = getattr(obj,part) | |
1411 | except: |
|
1382 | except: | |
1412 | # Blanket except b/c some badly implemented objects |
|
1383 | # Blanket except b/c some badly implemented objects | |
1413 | # allow __getattr__ to raise exceptions other than |
|
1384 | # allow __getattr__ to raise exceptions other than | |
1414 | # AttributeError, which then crashes IPython. |
|
1385 | # AttributeError, which then crashes IPython. | |
1415 | break |
|
1386 | break | |
1416 | else: |
|
1387 | else: | |
1417 | # If we finish the for loop (no break), we got all members |
|
1388 | # If we finish the for loop (no break), we got all members | |
1418 | found = True |
|
1389 | found = True | |
1419 | ospace = nsname |
|
1390 | ospace = nsname | |
1420 | if ns == alias_ns: |
|
1391 | if ns == alias_ns: | |
1421 | isalias = True |
|
1392 | isalias = True | |
1422 | break # namespace loop |
|
1393 | break # namespace loop | |
1423 |
|
1394 | |||
1424 | # Try to see if it's magic |
|
1395 | # Try to see if it's magic | |
1425 | if not found: |
|
1396 | if not found: | |
1426 | obj = None |
|
1397 | obj = None | |
1427 | if oname.startswith(ESC_MAGIC2): |
|
1398 | if oname.startswith(ESC_MAGIC2): | |
1428 | oname = oname.lstrip(ESC_MAGIC2) |
|
1399 | oname = oname.lstrip(ESC_MAGIC2) | |
1429 | obj = self.find_cell_magic(oname) |
|
1400 | obj = self.find_cell_magic(oname) | |
1430 | elif oname.startswith(ESC_MAGIC): |
|
1401 | elif oname.startswith(ESC_MAGIC): | |
1431 | oname = oname.lstrip(ESC_MAGIC) |
|
1402 | oname = oname.lstrip(ESC_MAGIC) | |
1432 | obj = self.find_line_magic(oname) |
|
1403 | obj = self.find_line_magic(oname) | |
1433 | else: |
|
1404 | else: | |
1434 | # search without prefix, so run? will find %run? |
|
1405 | # search without prefix, so run? will find %run? | |
1435 | obj = self.find_line_magic(oname) |
|
1406 | obj = self.find_line_magic(oname) | |
1436 | if obj is None: |
|
1407 | if obj is None: | |
1437 | obj = self.find_cell_magic(oname) |
|
1408 | obj = self.find_cell_magic(oname) | |
1438 | if obj is not None: |
|
1409 | if obj is not None: | |
1439 | found = True |
|
1410 | found = True | |
1440 | ospace = 'IPython internal' |
|
1411 | ospace = 'IPython internal' | |
1441 | ismagic = True |
|
1412 | ismagic = True | |
1442 |
|
1413 | |||
1443 | # Last try: special-case some literals like '', [], {}, etc: |
|
1414 | # Last try: special-case some literals like '', [], {}, etc: | |
1444 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1415 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1445 | obj = eval(oname_head) |
|
1416 | obj = eval(oname_head) | |
1446 | found = True |
|
1417 | found = True | |
1447 | ospace = 'Interactive' |
|
1418 | ospace = 'Interactive' | |
1448 |
|
1419 | |||
1449 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1420 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1450 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1421 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1451 |
|
1422 | |||
1452 | def _ofind_property(self, oname, info): |
|
1423 | def _ofind_property(self, oname, info): | |
1453 | """Second part of object finding, to look for property details.""" |
|
1424 | """Second part of object finding, to look for property details.""" | |
1454 | if info.found: |
|
1425 | if info.found: | |
1455 | # Get the docstring of the class property if it exists. |
|
1426 | # Get the docstring of the class property if it exists. | |
1456 | path = oname.split('.') |
|
1427 | path = oname.split('.') | |
1457 | root = '.'.join(path[:-1]) |
|
1428 | root = '.'.join(path[:-1]) | |
1458 | if info.parent is not None: |
|
1429 | if info.parent is not None: | |
1459 | try: |
|
1430 | try: | |
1460 | target = getattr(info.parent, '__class__') |
|
1431 | target = getattr(info.parent, '__class__') | |
1461 | # The object belongs to a class instance. |
|
1432 | # The object belongs to a class instance. | |
1462 | try: |
|
1433 | try: | |
1463 | target = getattr(target, path[-1]) |
|
1434 | target = getattr(target, path[-1]) | |
1464 | # The class defines the object. |
|
1435 | # The class defines the object. | |
1465 | if isinstance(target, property): |
|
1436 | if isinstance(target, property): | |
1466 | oname = root + '.__class__.' + path[-1] |
|
1437 | oname = root + '.__class__.' + path[-1] | |
1467 | info = Struct(self._ofind(oname)) |
|
1438 | info = Struct(self._ofind(oname)) | |
1468 | except AttributeError: pass |
|
1439 | except AttributeError: pass | |
1469 | except AttributeError: pass |
|
1440 | except AttributeError: pass | |
1470 |
|
1441 | |||
1471 | # We return either the new info or the unmodified input if the object |
|
1442 | # We return either the new info or the unmodified input if the object | |
1472 | # hadn't been found |
|
1443 | # hadn't been found | |
1473 | return info |
|
1444 | return info | |
1474 |
|
1445 | |||
1475 | def _object_find(self, oname, namespaces=None): |
|
1446 | def _object_find(self, oname, namespaces=None): | |
1476 | """Find an object and return a struct with info about it.""" |
|
1447 | """Find an object and return a struct with info about it.""" | |
1477 | inf = Struct(self._ofind(oname, namespaces)) |
|
1448 | inf = Struct(self._ofind(oname, namespaces)) | |
1478 | return Struct(self._ofind_property(oname, inf)) |
|
1449 | return Struct(self._ofind_property(oname, inf)) | |
1479 |
|
1450 | |||
1480 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1451 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1481 | """Generic interface to the inspector system. |
|
1452 | """Generic interface to the inspector system. | |
1482 |
|
1453 | |||
1483 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1454 | This function is meant to be called by pdef, pdoc & friends.""" | |
1484 | info = self._object_find(oname, namespaces) |
|
1455 | info = self._object_find(oname, namespaces) | |
1485 | if info.found: |
|
1456 | if info.found: | |
1486 | pmethod = getattr(self.inspector, meth) |
|
1457 | pmethod = getattr(self.inspector, meth) | |
1487 | formatter = format_screen if info.ismagic else None |
|
1458 | formatter = format_screen if info.ismagic else None | |
1488 | if meth == 'pdoc': |
|
1459 | if meth == 'pdoc': | |
1489 | pmethod(info.obj, oname, formatter) |
|
1460 | pmethod(info.obj, oname, formatter) | |
1490 | elif meth == 'pinfo': |
|
1461 | elif meth == 'pinfo': | |
1491 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1462 | pmethod(info.obj, oname, formatter, info, **kw) | |
1492 | else: |
|
1463 | else: | |
1493 | pmethod(info.obj, oname) |
|
1464 | pmethod(info.obj, oname) | |
1494 | else: |
|
1465 | else: | |
1495 | print('Object `%s` not found.' % oname) |
|
1466 | print('Object `%s` not found.' % oname) | |
1496 | return 'not found' # so callers can take other action |
|
1467 | return 'not found' # so callers can take other action | |
1497 |
|
1468 | |||
1498 | def object_inspect(self, oname, detail_level=0): |
|
1469 | def object_inspect(self, oname, detail_level=0): | |
1499 | with self.builtin_trap: |
|
1470 | with self.builtin_trap: | |
1500 | info = self._object_find(oname) |
|
1471 | info = self._object_find(oname) | |
1501 | if info.found: |
|
1472 | if info.found: | |
1502 | return self.inspector.info(info.obj, oname, info=info, |
|
1473 | return self.inspector.info(info.obj, oname, info=info, | |
1503 | detail_level=detail_level |
|
1474 | detail_level=detail_level | |
1504 | ) |
|
1475 | ) | |
1505 | else: |
|
1476 | else: | |
1506 | return oinspect.object_info(name=oname, found=False) |
|
1477 | return oinspect.object_info(name=oname, found=False) | |
1507 |
|
1478 | |||
1508 | #------------------------------------------------------------------------- |
|
1479 | #------------------------------------------------------------------------- | |
1509 | # Things related to history management |
|
1480 | # Things related to history management | |
1510 | #------------------------------------------------------------------------- |
|
1481 | #------------------------------------------------------------------------- | |
1511 |
|
1482 | |||
1512 | def init_history(self): |
|
1483 | def init_history(self): | |
1513 | """Sets up the command history, and starts regular autosaves.""" |
|
1484 | """Sets up the command history, and starts regular autosaves.""" | |
1514 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1485 | self.history_manager = HistoryManager(shell=self, parent=self) | |
1515 | self.configurables.append(self.history_manager) |
|
1486 | self.configurables.append(self.history_manager) | |
1516 |
|
1487 | |||
1517 | #------------------------------------------------------------------------- |
|
1488 | #------------------------------------------------------------------------- | |
1518 | # Things related to exception handling and tracebacks (not debugging) |
|
1489 | # Things related to exception handling and tracebacks (not debugging) | |
1519 | #------------------------------------------------------------------------- |
|
1490 | #------------------------------------------------------------------------- | |
1520 |
|
1491 | |||
1521 | def init_traceback_handlers(self, custom_exceptions): |
|
1492 | def init_traceback_handlers(self, custom_exceptions): | |
1522 | # Syntax error handler. |
|
1493 | # Syntax error handler. | |
1523 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1494 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1524 |
|
1495 | |||
1525 | # The interactive one is initialized with an offset, meaning we always |
|
1496 | # The interactive one is initialized with an offset, meaning we always | |
1526 | # want to remove the topmost item in the traceback, which is our own |
|
1497 | # want to remove the topmost item in the traceback, which is our own | |
1527 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1498 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1528 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1499 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1529 | color_scheme='NoColor', |
|
1500 | color_scheme='NoColor', | |
1530 | tb_offset = 1, |
|
1501 | tb_offset = 1, | |
1531 | check_cache=check_linecache_ipython) |
|
1502 | check_cache=check_linecache_ipython) | |
1532 |
|
1503 | |||
1533 | # The instance will store a pointer to the system-wide exception hook, |
|
1504 | # The instance will store a pointer to the system-wide exception hook, | |
1534 | # so that runtime code (such as magics) can access it. This is because |
|
1505 | # so that runtime code (such as magics) can access it. This is because | |
1535 | # during the read-eval loop, it may get temporarily overwritten. |
|
1506 | # during the read-eval loop, it may get temporarily overwritten. | |
1536 | self.sys_excepthook = sys.excepthook |
|
1507 | self.sys_excepthook = sys.excepthook | |
1537 |
|
1508 | |||
1538 | # and add any custom exception handlers the user may have specified |
|
1509 | # and add any custom exception handlers the user may have specified | |
1539 | self.set_custom_exc(*custom_exceptions) |
|
1510 | self.set_custom_exc(*custom_exceptions) | |
1540 |
|
1511 | |||
1541 | # Set the exception mode |
|
1512 | # Set the exception mode | |
1542 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1513 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1543 |
|
1514 | |||
1544 | def set_custom_exc(self, exc_tuple, handler): |
|
1515 | def set_custom_exc(self, exc_tuple, handler): | |
1545 | """set_custom_exc(exc_tuple,handler) |
|
1516 | """set_custom_exc(exc_tuple,handler) | |
1546 |
|
1517 | |||
1547 | Set a custom exception handler, which will be called if any of the |
|
1518 | Set a custom exception handler, which will be called if any of the | |
1548 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1519 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1549 | run_code() method). |
|
1520 | run_code() method). | |
1550 |
|
1521 | |||
1551 | Parameters |
|
1522 | Parameters | |
1552 | ---------- |
|
1523 | ---------- | |
1553 |
|
1524 | |||
1554 | exc_tuple : tuple of exception classes |
|
1525 | exc_tuple : tuple of exception classes | |
1555 | A *tuple* of exception classes, for which to call the defined |
|
1526 | A *tuple* of exception classes, for which to call the defined | |
1556 | handler. It is very important that you use a tuple, and NOT A |
|
1527 | handler. It is very important that you use a tuple, and NOT A | |
1557 | LIST here, because of the way Python's except statement works. If |
|
1528 | LIST here, because of the way Python's except statement works. If | |
1558 | you only want to trap a single exception, use a singleton tuple:: |
|
1529 | you only want to trap a single exception, use a singleton tuple:: | |
1559 |
|
1530 | |||
1560 | exc_tuple == (MyCustomException,) |
|
1531 | exc_tuple == (MyCustomException,) | |
1561 |
|
1532 | |||
1562 | handler : callable |
|
1533 | handler : callable | |
1563 | handler must have the following signature:: |
|
1534 | handler must have the following signature:: | |
1564 |
|
1535 | |||
1565 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1536 | def my_handler(self, etype, value, tb, tb_offset=None): | |
1566 | ... |
|
1537 | ... | |
1567 | return structured_traceback |
|
1538 | return structured_traceback | |
1568 |
|
1539 | |||
1569 | Your handler must return a structured traceback (a list of strings), |
|
1540 | Your handler must return a structured traceback (a list of strings), | |
1570 | or None. |
|
1541 | or None. | |
1571 |
|
1542 | |||
1572 | This will be made into an instance method (via types.MethodType) |
|
1543 | This will be made into an instance method (via types.MethodType) | |
1573 | of IPython itself, and it will be called if any of the exceptions |
|
1544 | of IPython itself, and it will be called if any of the exceptions | |
1574 | listed in the exc_tuple are caught. If the handler is None, an |
|
1545 | listed in the exc_tuple are caught. If the handler is None, an | |
1575 | internal basic one is used, which just prints basic info. |
|
1546 | internal basic one is used, which just prints basic info. | |
1576 |
|
1547 | |||
1577 | To protect IPython from crashes, if your handler ever raises an |
|
1548 | To protect IPython from crashes, if your handler ever raises an | |
1578 | exception or returns an invalid result, it will be immediately |
|
1549 | exception or returns an invalid result, it will be immediately | |
1579 | disabled. |
|
1550 | disabled. | |
1580 |
|
1551 | |||
1581 | WARNING: by putting in your own exception handler into IPython's main |
|
1552 | WARNING: by putting in your own exception handler into IPython's main | |
1582 | execution loop, you run a very good chance of nasty crashes. This |
|
1553 | execution loop, you run a very good chance of nasty crashes. This | |
1583 | facility should only be used if you really know what you are doing.""" |
|
1554 | facility should only be used if you really know what you are doing.""" | |
1584 |
|
1555 | |||
1585 | assert type(exc_tuple)==type(()) , \ |
|
1556 | assert type(exc_tuple)==type(()) , \ | |
1586 | "The custom exceptions must be given AS A TUPLE." |
|
1557 | "The custom exceptions must be given AS A TUPLE." | |
1587 |
|
1558 | |||
1588 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1559 | def dummy_handler(self,etype,value,tb,tb_offset=None): | |
1589 | print('*** Simple custom exception handler ***') |
|
1560 | print('*** Simple custom exception handler ***') | |
1590 | print('Exception type :',etype) |
|
1561 | print('Exception type :',etype) | |
1591 | print('Exception value:',value) |
|
1562 | print('Exception value:',value) | |
1592 | print('Traceback :',tb) |
|
1563 | print('Traceback :',tb) | |
1593 | #print 'Source code :','\n'.join(self.buffer) |
|
1564 | #print 'Source code :','\n'.join(self.buffer) | |
1594 |
|
1565 | |||
1595 | def validate_stb(stb): |
|
1566 | def validate_stb(stb): | |
1596 | """validate structured traceback return type |
|
1567 | """validate structured traceback return type | |
1597 |
|
1568 | |||
1598 | return type of CustomTB *should* be a list of strings, but allow |
|
1569 | return type of CustomTB *should* be a list of strings, but allow | |
1599 | single strings or None, which are harmless. |
|
1570 | single strings or None, which are harmless. | |
1600 |
|
1571 | |||
1601 | This function will *always* return a list of strings, |
|
1572 | This function will *always* return a list of strings, | |
1602 | and will raise a TypeError if stb is inappropriate. |
|
1573 | and will raise a TypeError if stb is inappropriate. | |
1603 | """ |
|
1574 | """ | |
1604 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1575 | msg = "CustomTB must return list of strings, not %r" % stb | |
1605 | if stb is None: |
|
1576 | if stb is None: | |
1606 | return [] |
|
1577 | return [] | |
1607 | elif isinstance(stb, basestring): |
|
1578 | elif isinstance(stb, basestring): | |
1608 | return [stb] |
|
1579 | return [stb] | |
1609 | elif not isinstance(stb, list): |
|
1580 | elif not isinstance(stb, list): | |
1610 | raise TypeError(msg) |
|
1581 | raise TypeError(msg) | |
1611 | # it's a list |
|
1582 | # it's a list | |
1612 | for line in stb: |
|
1583 | for line in stb: | |
1613 | # check every element |
|
1584 | # check every element | |
1614 | if not isinstance(line, basestring): |
|
1585 | if not isinstance(line, basestring): | |
1615 | raise TypeError(msg) |
|
1586 | raise TypeError(msg) | |
1616 | return stb |
|
1587 | return stb | |
1617 |
|
1588 | |||
1618 | if handler is None: |
|
1589 | if handler is None: | |
1619 | wrapped = dummy_handler |
|
1590 | wrapped = dummy_handler | |
1620 | else: |
|
1591 | else: | |
1621 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1592 | def wrapped(self,etype,value,tb,tb_offset=None): | |
1622 | """wrap CustomTB handler, to protect IPython from user code |
|
1593 | """wrap CustomTB handler, to protect IPython from user code | |
1623 |
|
1594 | |||
1624 | This makes it harder (but not impossible) for custom exception |
|
1595 | This makes it harder (but not impossible) for custom exception | |
1625 | handlers to crash IPython. |
|
1596 | handlers to crash IPython. | |
1626 | """ |
|
1597 | """ | |
1627 | try: |
|
1598 | try: | |
1628 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1599 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) | |
1629 | return validate_stb(stb) |
|
1600 | return validate_stb(stb) | |
1630 | except: |
|
1601 | except: | |
1631 | # clear custom handler immediately |
|
1602 | # clear custom handler immediately | |
1632 | self.set_custom_exc((), None) |
|
1603 | self.set_custom_exc((), None) | |
1633 | print("Custom TB Handler failed, unregistering", file=io.stderr) |
|
1604 | print("Custom TB Handler failed, unregistering", file=io.stderr) | |
1634 | # show the exception in handler first |
|
1605 | # show the exception in handler first | |
1635 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1606 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) | |
1636 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1607 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) | |
1637 | print("The original exception:", file=io.stdout) |
|
1608 | print("The original exception:", file=io.stdout) | |
1638 | stb = self.InteractiveTB.structured_traceback( |
|
1609 | stb = self.InteractiveTB.structured_traceback( | |
1639 | (etype,value,tb), tb_offset=tb_offset |
|
1610 | (etype,value,tb), tb_offset=tb_offset | |
1640 | ) |
|
1611 | ) | |
1641 | return stb |
|
1612 | return stb | |
1642 |
|
1613 | |||
1643 | self.CustomTB = types.MethodType(wrapped,self) |
|
1614 | self.CustomTB = types.MethodType(wrapped,self) | |
1644 | self.custom_exceptions = exc_tuple |
|
1615 | self.custom_exceptions = exc_tuple | |
1645 |
|
1616 | |||
1646 | def excepthook(self, etype, value, tb): |
|
1617 | def excepthook(self, etype, value, tb): | |
1647 | """One more defense for GUI apps that call sys.excepthook. |
|
1618 | """One more defense for GUI apps that call sys.excepthook. | |
1648 |
|
1619 | |||
1649 | GUI frameworks like wxPython trap exceptions and call |
|
1620 | GUI frameworks like wxPython trap exceptions and call | |
1650 | sys.excepthook themselves. I guess this is a feature that |
|
1621 | sys.excepthook themselves. I guess this is a feature that | |
1651 | enables them to keep running after exceptions that would |
|
1622 | enables them to keep running after exceptions that would | |
1652 | otherwise kill their mainloop. This is a bother for IPython |
|
1623 | otherwise kill their mainloop. This is a bother for IPython | |
1653 | which excepts to catch all of the program exceptions with a try: |
|
1624 | which excepts to catch all of the program exceptions with a try: | |
1654 | except: statement. |
|
1625 | except: statement. | |
1655 |
|
1626 | |||
1656 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1627 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1657 | any app directly invokes sys.excepthook, it will look to the user like |
|
1628 | any app directly invokes sys.excepthook, it will look to the user like | |
1658 | IPython crashed. In order to work around this, we can disable the |
|
1629 | IPython crashed. In order to work around this, we can disable the | |
1659 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1630 | CrashHandler and replace it with this excepthook instead, which prints a | |
1660 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1631 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1661 | call sys.excepthook will generate a regular-looking exception from |
|
1632 | call sys.excepthook will generate a regular-looking exception from | |
1662 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1633 | IPython, and the CrashHandler will only be triggered by real IPython | |
1663 | crashes. |
|
1634 | crashes. | |
1664 |
|
1635 | |||
1665 | This hook should be used sparingly, only in places which are not likely |
|
1636 | This hook should be used sparingly, only in places which are not likely | |
1666 | to be true IPython errors. |
|
1637 | to be true IPython errors. | |
1667 | """ |
|
1638 | """ | |
1668 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1639 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1669 |
|
1640 | |||
1670 | def _get_exc_info(self, exc_tuple=None): |
|
1641 | def _get_exc_info(self, exc_tuple=None): | |
1671 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1642 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. | |
1672 |
|
1643 | |||
1673 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1644 | Ensures sys.last_type,value,traceback hold the exc_info we found, | |
1674 | from whichever source. |
|
1645 | from whichever source. | |
1675 |
|
1646 | |||
1676 | raises ValueError if none of these contain any information |
|
1647 | raises ValueError if none of these contain any information | |
1677 | """ |
|
1648 | """ | |
1678 | if exc_tuple is None: |
|
1649 | if exc_tuple is None: | |
1679 | etype, value, tb = sys.exc_info() |
|
1650 | etype, value, tb = sys.exc_info() | |
1680 | else: |
|
1651 | else: | |
1681 | etype, value, tb = exc_tuple |
|
1652 | etype, value, tb = exc_tuple | |
1682 |
|
1653 | |||
1683 | if etype is None: |
|
1654 | if etype is None: | |
1684 | if hasattr(sys, 'last_type'): |
|
1655 | if hasattr(sys, 'last_type'): | |
1685 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1656 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1686 | sys.last_traceback |
|
1657 | sys.last_traceback | |
1687 |
|
1658 | |||
1688 | if etype is None: |
|
1659 | if etype is None: | |
1689 | raise ValueError("No exception to find") |
|
1660 | raise ValueError("No exception to find") | |
1690 |
|
1661 | |||
1691 | # Now store the exception info in sys.last_type etc. |
|
1662 | # Now store the exception info in sys.last_type etc. | |
1692 | # WARNING: these variables are somewhat deprecated and not |
|
1663 | # WARNING: these variables are somewhat deprecated and not | |
1693 | # necessarily safe to use in a threaded environment, but tools |
|
1664 | # necessarily safe to use in a threaded environment, but tools | |
1694 | # like pdb depend on their existence, so let's set them. If we |
|
1665 | # like pdb depend on their existence, so let's set them. If we | |
1695 | # find problems in the field, we'll need to revisit their use. |
|
1666 | # find problems in the field, we'll need to revisit their use. | |
1696 | sys.last_type = etype |
|
1667 | sys.last_type = etype | |
1697 | sys.last_value = value |
|
1668 | sys.last_value = value | |
1698 | sys.last_traceback = tb |
|
1669 | sys.last_traceback = tb | |
1699 |
|
1670 | |||
1700 | return etype, value, tb |
|
1671 | return etype, value, tb | |
1701 |
|
1672 | |||
1702 |
|
1673 | |||
1703 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1674 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1704 | exception_only=False): |
|
1675 | exception_only=False): | |
1705 | """Display the exception that just occurred. |
|
1676 | """Display the exception that just occurred. | |
1706 |
|
1677 | |||
1707 | If nothing is known about the exception, this is the method which |
|
1678 | If nothing is known about the exception, this is the method which | |
1708 | should be used throughout the code for presenting user tracebacks, |
|
1679 | should be used throughout the code for presenting user tracebacks, | |
1709 | rather than directly invoking the InteractiveTB object. |
|
1680 | rather than directly invoking the InteractiveTB object. | |
1710 |
|
1681 | |||
1711 | A specific showsyntaxerror() also exists, but this method can take |
|
1682 | A specific showsyntaxerror() also exists, but this method can take | |
1712 | care of calling it if needed, so unless you are explicitly catching a |
|
1683 | care of calling it if needed, so unless you are explicitly catching a | |
1713 | SyntaxError exception, don't try to analyze the stack manually and |
|
1684 | SyntaxError exception, don't try to analyze the stack manually and | |
1714 | simply call this method.""" |
|
1685 | simply call this method.""" | |
1715 |
|
1686 | |||
1716 | try: |
|
1687 | try: | |
1717 | try: |
|
1688 | try: | |
1718 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1689 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1719 | except ValueError: |
|
1690 | except ValueError: | |
1720 | self.write_err('No traceback available to show.\n') |
|
1691 | self.write_err('No traceback available to show.\n') | |
1721 | return |
|
1692 | return | |
1722 |
|
1693 | |||
1723 | if issubclass(etype, SyntaxError): |
|
1694 | if issubclass(etype, SyntaxError): | |
1724 | # Though this won't be called by syntax errors in the input |
|
1695 | # Though this won't be called by syntax errors in the input | |
1725 | # line, there may be SyntaxError cases with imported code. |
|
1696 | # line, there may be SyntaxError cases with imported code. | |
1726 | self.showsyntaxerror(filename) |
|
1697 | self.showsyntaxerror(filename) | |
1727 | elif etype is UsageError: |
|
1698 | elif etype is UsageError: | |
1728 | self.write_err("UsageError: %s" % value) |
|
1699 | self.write_err("UsageError: %s" % value) | |
1729 | else: |
|
1700 | else: | |
1730 | if exception_only: |
|
1701 | if exception_only: | |
1731 | stb = ['An exception has occurred, use %tb to see ' |
|
1702 | stb = ['An exception has occurred, use %tb to see ' | |
1732 | 'the full traceback.\n'] |
|
1703 | 'the full traceback.\n'] | |
1733 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1704 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1734 | value)) |
|
1705 | value)) | |
1735 | else: |
|
1706 | else: | |
1736 | try: |
|
1707 | try: | |
1737 | # Exception classes can customise their traceback - we |
|
1708 | # Exception classes can customise their traceback - we | |
1738 | # use this in IPython.parallel for exceptions occurring |
|
1709 | # use this in IPython.parallel for exceptions occurring | |
1739 | # in the engines. This should return a list of strings. |
|
1710 | # in the engines. This should return a list of strings. | |
1740 | stb = value._render_traceback_() |
|
1711 | stb = value._render_traceback_() | |
1741 | except Exception: |
|
1712 | except Exception: | |
1742 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1713 | stb = self.InteractiveTB.structured_traceback(etype, | |
1743 | value, tb, tb_offset=tb_offset) |
|
1714 | value, tb, tb_offset=tb_offset) | |
1744 |
|
1715 | |||
1745 | self._showtraceback(etype, value, stb) |
|
1716 | self._showtraceback(etype, value, stb) | |
1746 | if self.call_pdb: |
|
1717 | if self.call_pdb: | |
1747 | # drop into debugger |
|
1718 | # drop into debugger | |
1748 | self.debugger(force=True) |
|
1719 | self.debugger(force=True) | |
1749 | return |
|
1720 | return | |
1750 |
|
1721 | |||
1751 | # Actually show the traceback |
|
1722 | # Actually show the traceback | |
1752 | self._showtraceback(etype, value, stb) |
|
1723 | self._showtraceback(etype, value, stb) | |
1753 |
|
1724 | |||
1754 | except KeyboardInterrupt: |
|
1725 | except KeyboardInterrupt: | |
1755 | self.write_err("\nKeyboardInterrupt\n") |
|
1726 | self.write_err("\nKeyboardInterrupt\n") | |
1756 |
|
1727 | |||
1757 | def _showtraceback(self, etype, evalue, stb): |
|
1728 | def _showtraceback(self, etype, evalue, stb): | |
1758 | """Actually show a traceback. |
|
1729 | """Actually show a traceback. | |
1759 |
|
1730 | |||
1760 | Subclasses may override this method to put the traceback on a different |
|
1731 | Subclasses may override this method to put the traceback on a different | |
1761 | place, like a side channel. |
|
1732 | place, like a side channel. | |
1762 | """ |
|
1733 | """ | |
1763 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1734 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) | |
1764 |
|
1735 | |||
1765 | def showsyntaxerror(self, filename=None): |
|
1736 | def showsyntaxerror(self, filename=None): | |
1766 | """Display the syntax error that just occurred. |
|
1737 | """Display the syntax error that just occurred. | |
1767 |
|
1738 | |||
1768 | This doesn't display a stack trace because there isn't one. |
|
1739 | This doesn't display a stack trace because there isn't one. | |
1769 |
|
1740 | |||
1770 | If a filename is given, it is stuffed in the exception instead |
|
1741 | If a filename is given, it is stuffed in the exception instead | |
1771 | of what was there before (because Python's parser always uses |
|
1742 | of what was there before (because Python's parser always uses | |
1772 | "<string>" when reading from a string). |
|
1743 | "<string>" when reading from a string). | |
1773 | """ |
|
1744 | """ | |
1774 | etype, value, last_traceback = self._get_exc_info() |
|
1745 | etype, value, last_traceback = self._get_exc_info() | |
1775 |
|
1746 | |||
1776 | if filename and issubclass(etype, SyntaxError): |
|
1747 | if filename and issubclass(etype, SyntaxError): | |
1777 | try: |
|
1748 | try: | |
1778 | value.filename = filename |
|
1749 | value.filename = filename | |
1779 | except: |
|
1750 | except: | |
1780 | # Not the format we expect; leave it alone |
|
1751 | # Not the format we expect; leave it alone | |
1781 | pass |
|
1752 | pass | |
1782 |
|
1753 | |||
1783 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1754 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1784 | self._showtraceback(etype, value, stb) |
|
1755 | self._showtraceback(etype, value, stb) | |
1785 |
|
1756 | |||
1786 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1757 | # This is overridden in TerminalInteractiveShell to show a message about | |
1787 | # the %paste magic. |
|
1758 | # the %paste magic. | |
1788 | def showindentationerror(self): |
|
1759 | def showindentationerror(self): | |
1789 | """Called by run_cell when there's an IndentationError in code entered |
|
1760 | """Called by run_cell when there's an IndentationError in code entered | |
1790 | at the prompt. |
|
1761 | at the prompt. | |
1791 |
|
1762 | |||
1792 | This is overridden in TerminalInteractiveShell to show a message about |
|
1763 | This is overridden in TerminalInteractiveShell to show a message about | |
1793 | the %paste magic.""" |
|
1764 | the %paste magic.""" | |
1794 | self.showsyntaxerror() |
|
1765 | self.showsyntaxerror() | |
1795 |
|
1766 | |||
1796 | #------------------------------------------------------------------------- |
|
1767 | #------------------------------------------------------------------------- | |
1797 | # Things related to readline |
|
1768 | # Things related to readline | |
1798 | #------------------------------------------------------------------------- |
|
1769 | #------------------------------------------------------------------------- | |
1799 |
|
1770 | |||
1800 | def init_readline(self): |
|
1771 | def init_readline(self): | |
1801 | """Command history completion/saving/reloading.""" |
|
1772 | """Command history completion/saving/reloading.""" | |
1802 |
|
1773 | |||
1803 | if self.readline_use: |
|
1774 | if self.readline_use: | |
1804 | import IPython.utils.rlineimpl as readline |
|
1775 | import IPython.utils.rlineimpl as readline | |
1805 |
|
1776 | |||
1806 | self.rl_next_input = None |
|
1777 | self.rl_next_input = None | |
1807 | self.rl_do_indent = False |
|
1778 | self.rl_do_indent = False | |
1808 |
|
1779 | |||
1809 | if not self.readline_use or not readline.have_readline: |
|
1780 | if not self.readline_use or not readline.have_readline: | |
1810 | self.has_readline = False |
|
1781 | self.has_readline = False | |
1811 | self.readline = None |
|
1782 | self.readline = None | |
1812 | # Set a number of methods that depend on readline to be no-op |
|
1783 | # Set a number of methods that depend on readline to be no-op | |
1813 | self.readline_no_record = no_op_context |
|
1784 | self.readline_no_record = no_op_context | |
1814 | self.set_readline_completer = no_op |
|
1785 | self.set_readline_completer = no_op | |
1815 | self.set_custom_completer = no_op |
|
1786 | self.set_custom_completer = no_op | |
1816 | if self.readline_use: |
|
1787 | if self.readline_use: | |
1817 | warn('Readline services not available or not loaded.') |
|
1788 | warn('Readline services not available or not loaded.') | |
1818 | else: |
|
1789 | else: | |
1819 | self.has_readline = True |
|
1790 | self.has_readline = True | |
1820 | self.readline = readline |
|
1791 | self.readline = readline | |
1821 | sys.modules['readline'] = readline |
|
1792 | sys.modules['readline'] = readline | |
1822 |
|
1793 | |||
1823 | # Platform-specific configuration |
|
1794 | # Platform-specific configuration | |
1824 | if os.name == 'nt': |
|
1795 | if os.name == 'nt': | |
1825 | # FIXME - check with Frederick to see if we can harmonize |
|
1796 | # FIXME - check with Frederick to see if we can harmonize | |
1826 | # naming conventions with pyreadline to avoid this |
|
1797 | # naming conventions with pyreadline to avoid this | |
1827 | # platform-dependent check |
|
1798 | # platform-dependent check | |
1828 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1799 | self.readline_startup_hook = readline.set_pre_input_hook | |
1829 | else: |
|
1800 | else: | |
1830 | self.readline_startup_hook = readline.set_startup_hook |
|
1801 | self.readline_startup_hook = readline.set_startup_hook | |
1831 |
|
1802 | |||
1832 | # Load user's initrc file (readline config) |
|
1803 | # Load user's initrc file (readline config) | |
1833 | # Or if libedit is used, load editrc. |
|
1804 | # Or if libedit is used, load editrc. | |
1834 | inputrc_name = os.environ.get('INPUTRC') |
|
1805 | inputrc_name = os.environ.get('INPUTRC') | |
1835 | if inputrc_name is None: |
|
1806 | if inputrc_name is None: | |
1836 | inputrc_name = '.inputrc' |
|
1807 | inputrc_name = '.inputrc' | |
1837 | if readline.uses_libedit: |
|
1808 | if readline.uses_libedit: | |
1838 | inputrc_name = '.editrc' |
|
1809 | inputrc_name = '.editrc' | |
1839 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1810 | inputrc_name = os.path.join(self.home_dir, inputrc_name) | |
1840 | if os.path.isfile(inputrc_name): |
|
1811 | if os.path.isfile(inputrc_name): | |
1841 | try: |
|
1812 | try: | |
1842 | readline.read_init_file(inputrc_name) |
|
1813 | readline.read_init_file(inputrc_name) | |
1843 | except: |
|
1814 | except: | |
1844 | warn('Problems reading readline initialization file <%s>' |
|
1815 | warn('Problems reading readline initialization file <%s>' | |
1845 | % inputrc_name) |
|
1816 | % inputrc_name) | |
1846 |
|
1817 | |||
1847 | # Configure readline according to user's prefs |
|
1818 | # Configure readline according to user's prefs | |
1848 | # This is only done if GNU readline is being used. If libedit |
|
1819 | # This is only done if GNU readline is being used. If libedit | |
1849 | # is being used (as on Leopard) the readline config is |
|
1820 | # is being used (as on Leopard) the readline config is | |
1850 | # not run as the syntax for libedit is different. |
|
1821 | # not run as the syntax for libedit is different. | |
1851 | if not readline.uses_libedit: |
|
1822 | if not readline.uses_libedit: | |
1852 | for rlcommand in self.readline_parse_and_bind: |
|
1823 | for rlcommand in self.readline_parse_and_bind: | |
1853 | #print "loading rl:",rlcommand # dbg |
|
1824 | #print "loading rl:",rlcommand # dbg | |
1854 | readline.parse_and_bind(rlcommand) |
|
1825 | readline.parse_and_bind(rlcommand) | |
1855 |
|
1826 | |||
1856 | # Remove some chars from the delimiters list. If we encounter |
|
1827 | # Remove some chars from the delimiters list. If we encounter | |
1857 | # unicode chars, discard them. |
|
1828 | # unicode chars, discard them. | |
1858 | delims = readline.get_completer_delims() |
|
1829 | delims = readline.get_completer_delims() | |
1859 | if not py3compat.PY3: |
|
1830 | if not py3compat.PY3: | |
1860 | delims = delims.encode("ascii", "ignore") |
|
1831 | delims = delims.encode("ascii", "ignore") | |
1861 | for d in self.readline_remove_delims: |
|
1832 | for d in self.readline_remove_delims: | |
1862 | delims = delims.replace(d, "") |
|
1833 | delims = delims.replace(d, "") | |
1863 | delims = delims.replace(ESC_MAGIC, '') |
|
1834 | delims = delims.replace(ESC_MAGIC, '') | |
1864 | readline.set_completer_delims(delims) |
|
1835 | readline.set_completer_delims(delims) | |
1865 | # Store these so we can restore them if something like rpy2 modifies |
|
1836 | # Store these so we can restore them if something like rpy2 modifies | |
1866 | # them. |
|
1837 | # them. | |
1867 | self.readline_delims = delims |
|
1838 | self.readline_delims = delims | |
1868 | # otherwise we end up with a monster history after a while: |
|
1839 | # otherwise we end up with a monster history after a while: | |
1869 | readline.set_history_length(self.history_length) |
|
1840 | readline.set_history_length(self.history_length) | |
1870 |
|
1841 | |||
1871 | self.refill_readline_hist() |
|
1842 | self.refill_readline_hist() | |
1872 | self.readline_no_record = ReadlineNoRecord(self) |
|
1843 | self.readline_no_record = ReadlineNoRecord(self) | |
1873 |
|
1844 | |||
1874 | # Configure auto-indent for all platforms |
|
1845 | # Configure auto-indent for all platforms | |
1875 | self.set_autoindent(self.autoindent) |
|
1846 | self.set_autoindent(self.autoindent) | |
1876 |
|
1847 | |||
1877 | def refill_readline_hist(self): |
|
1848 | def refill_readline_hist(self): | |
1878 | # Load the last 1000 lines from history |
|
1849 | # Load the last 1000 lines from history | |
1879 | self.readline.clear_history() |
|
1850 | self.readline.clear_history() | |
1880 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1851 | stdin_encoding = sys.stdin.encoding or "utf-8" | |
1881 | last_cell = u"" |
|
1852 | last_cell = u"" | |
1882 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1853 | for _, _, cell in self.history_manager.get_tail(1000, | |
1883 | include_latest=True): |
|
1854 | include_latest=True): | |
1884 | # Ignore blank lines and consecutive duplicates |
|
1855 | # Ignore blank lines and consecutive duplicates | |
1885 | cell = cell.rstrip() |
|
1856 | cell = cell.rstrip() | |
1886 | if cell and (cell != last_cell): |
|
1857 | if cell and (cell != last_cell): | |
1887 | if self.multiline_history: |
|
1858 | if self.multiline_history: | |
1888 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
1859 | self.readline.add_history(py3compat.unicode_to_str(cell, | |
1889 | stdin_encoding)) |
|
1860 | stdin_encoding)) | |
1890 | else: |
|
1861 | else: | |
1891 | for line in cell.splitlines(): |
|
1862 | for line in cell.splitlines(): | |
1892 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
1863 | self.readline.add_history(py3compat.unicode_to_str(line, | |
1893 | stdin_encoding)) |
|
1864 | stdin_encoding)) | |
1894 | last_cell = cell |
|
1865 | last_cell = cell | |
1895 |
|
1866 | |||
1896 | @skip_doctest |
|
1867 | @skip_doctest | |
1897 | def set_next_input(self, s): |
|
1868 | def set_next_input(self, s): | |
1898 | """ Sets the 'default' input string for the next command line. |
|
1869 | """ Sets the 'default' input string for the next command line. | |
1899 |
|
1870 | |||
1900 | Requires readline. |
|
1871 | Requires readline. | |
1901 |
|
1872 | |||
1902 | Example:: |
|
1873 | Example:: | |
1903 |
|
1874 | |||
1904 | In [1]: _ip.set_next_input("Hello Word") |
|
1875 | In [1]: _ip.set_next_input("Hello Word") | |
1905 | In [2]: Hello Word_ # cursor is here |
|
1876 | In [2]: Hello Word_ # cursor is here | |
1906 | """ |
|
1877 | """ | |
1907 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1878 | self.rl_next_input = py3compat.cast_bytes_py2(s) | |
1908 |
|
1879 | |||
1909 | # Maybe move this to the terminal subclass? |
|
1880 | # Maybe move this to the terminal subclass? | |
1910 | def pre_readline(self): |
|
1881 | def pre_readline(self): | |
1911 | """readline hook to be used at the start of each line. |
|
1882 | """readline hook to be used at the start of each line. | |
1912 |
|
1883 | |||
1913 | Currently it handles auto-indent only.""" |
|
1884 | Currently it handles auto-indent only.""" | |
1914 |
|
1885 | |||
1915 | if self.rl_do_indent: |
|
1886 | if self.rl_do_indent: | |
1916 | self.readline.insert_text(self._indent_current_str()) |
|
1887 | self.readline.insert_text(self._indent_current_str()) | |
1917 | if self.rl_next_input is not None: |
|
1888 | if self.rl_next_input is not None: | |
1918 | self.readline.insert_text(self.rl_next_input) |
|
1889 | self.readline.insert_text(self.rl_next_input) | |
1919 | self.rl_next_input = None |
|
1890 | self.rl_next_input = None | |
1920 |
|
1891 | |||
1921 | def _indent_current_str(self): |
|
1892 | def _indent_current_str(self): | |
1922 | """return the current level of indentation as a string""" |
|
1893 | """return the current level of indentation as a string""" | |
1923 | return self.input_splitter.indent_spaces * ' ' |
|
1894 | return self.input_splitter.indent_spaces * ' ' | |
1924 |
|
1895 | |||
1925 | #------------------------------------------------------------------------- |
|
1896 | #------------------------------------------------------------------------- | |
1926 | # Things related to text completion |
|
1897 | # Things related to text completion | |
1927 | #------------------------------------------------------------------------- |
|
1898 | #------------------------------------------------------------------------- | |
1928 |
|
1899 | |||
1929 | def init_completer(self): |
|
1900 | def init_completer(self): | |
1930 | """Initialize the completion machinery. |
|
1901 | """Initialize the completion machinery. | |
1931 |
|
1902 | |||
1932 | This creates completion machinery that can be used by client code, |
|
1903 | This creates completion machinery that can be used by client code, | |
1933 | either interactively in-process (typically triggered by the readline |
|
1904 | either interactively in-process (typically triggered by the readline | |
1934 | library), programatically (such as in test suites) or out-of-prcess |
|
1905 | library), programatically (such as in test suites) or out-of-prcess | |
1935 | (typically over the network by remote frontends). |
|
1906 | (typically over the network by remote frontends). | |
1936 | """ |
|
1907 | """ | |
1937 | from IPython.core.completer import IPCompleter |
|
1908 | from IPython.core.completer import IPCompleter | |
1938 | from IPython.core.completerlib import (module_completer, |
|
1909 | from IPython.core.completerlib import (module_completer, | |
1939 | magic_run_completer, cd_completer, reset_completer) |
|
1910 | magic_run_completer, cd_completer, reset_completer) | |
1940 |
|
1911 | |||
1941 | self.Completer = IPCompleter(shell=self, |
|
1912 | self.Completer = IPCompleter(shell=self, | |
1942 | namespace=self.user_ns, |
|
1913 | namespace=self.user_ns, | |
1943 | global_namespace=self.user_global_ns, |
|
1914 | global_namespace=self.user_global_ns, | |
1944 | alias_table=self.alias_manager.alias_table, |
|
1915 | alias_table=self.alias_manager.alias_table, | |
1945 | use_readline=self.has_readline, |
|
1916 | use_readline=self.has_readline, | |
1946 | parent=self, |
|
1917 | parent=self, | |
1947 | ) |
|
1918 | ) | |
1948 | self.configurables.append(self.Completer) |
|
1919 | self.configurables.append(self.Completer) | |
1949 |
|
1920 | |||
1950 | # Add custom completers to the basic ones built into IPCompleter |
|
1921 | # Add custom completers to the basic ones built into IPCompleter | |
1951 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1922 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1952 | self.strdispatchers['complete_command'] = sdisp |
|
1923 | self.strdispatchers['complete_command'] = sdisp | |
1953 | self.Completer.custom_completers = sdisp |
|
1924 | self.Completer.custom_completers = sdisp | |
1954 |
|
1925 | |||
1955 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1926 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1956 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1927 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1957 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1928 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1958 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1929 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1959 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1930 | self.set_hook('complete_command', reset_completer, str_key = '%reset') | |
1960 |
|
1931 | |||
1961 | # Only configure readline if we truly are using readline. IPython can |
|
1932 | # Only configure readline if we truly are using readline. IPython can | |
1962 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1933 | # do tab-completion over the network, in GUIs, etc, where readline | |
1963 | # itself may be absent |
|
1934 | # itself may be absent | |
1964 | if self.has_readline: |
|
1935 | if self.has_readline: | |
1965 | self.set_readline_completer() |
|
1936 | self.set_readline_completer() | |
1966 |
|
1937 | |||
1967 | def complete(self, text, line=None, cursor_pos=None): |
|
1938 | def complete(self, text, line=None, cursor_pos=None): | |
1968 | """Return the completed text and a list of completions. |
|
1939 | """Return the completed text and a list of completions. | |
1969 |
|
1940 | |||
1970 | Parameters |
|
1941 | Parameters | |
1971 | ---------- |
|
1942 | ---------- | |
1972 |
|
1943 | |||
1973 | text : string |
|
1944 | text : string | |
1974 | A string of text to be completed on. It can be given as empty and |
|
1945 | A string of text to be completed on. It can be given as empty and | |
1975 | instead a line/position pair are given. In this case, the |
|
1946 | instead a line/position pair are given. In this case, the | |
1976 | completer itself will split the line like readline does. |
|
1947 | completer itself will split the line like readline does. | |
1977 |
|
1948 | |||
1978 | line : string, optional |
|
1949 | line : string, optional | |
1979 | The complete line that text is part of. |
|
1950 | The complete line that text is part of. | |
1980 |
|
1951 | |||
1981 | cursor_pos : int, optional |
|
1952 | cursor_pos : int, optional | |
1982 | The position of the cursor on the input line. |
|
1953 | The position of the cursor on the input line. | |
1983 |
|
1954 | |||
1984 | Returns |
|
1955 | Returns | |
1985 | ------- |
|
1956 | ------- | |
1986 | text : string |
|
1957 | text : string | |
1987 | The actual text that was completed. |
|
1958 | The actual text that was completed. | |
1988 |
|
1959 | |||
1989 | matches : list |
|
1960 | matches : list | |
1990 | A sorted list with all possible completions. |
|
1961 | A sorted list with all possible completions. | |
1991 |
|
1962 | |||
1992 | The optional arguments allow the completion to take more context into |
|
1963 | The optional arguments allow the completion to take more context into | |
1993 | account, and are part of the low-level completion API. |
|
1964 | account, and are part of the low-level completion API. | |
1994 |
|
1965 | |||
1995 | This is a wrapper around the completion mechanism, similar to what |
|
1966 | This is a wrapper around the completion mechanism, similar to what | |
1996 | readline does at the command line when the TAB key is hit. By |
|
1967 | readline does at the command line when the TAB key is hit. By | |
1997 | exposing it as a method, it can be used by other non-readline |
|
1968 | exposing it as a method, it can be used by other non-readline | |
1998 | environments (such as GUIs) for text completion. |
|
1969 | environments (such as GUIs) for text completion. | |
1999 |
|
1970 | |||
2000 | Simple usage example: |
|
1971 | Simple usage example: | |
2001 |
|
1972 | |||
2002 | In [1]: x = 'hello' |
|
1973 | In [1]: x = 'hello' | |
2003 |
|
1974 | |||
2004 | In [2]: _ip.complete('x.l') |
|
1975 | In [2]: _ip.complete('x.l') | |
2005 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1976 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
2006 | """ |
|
1977 | """ | |
2007 |
|
1978 | |||
2008 | # Inject names into __builtin__ so we can complete on the added names. |
|
1979 | # Inject names into __builtin__ so we can complete on the added names. | |
2009 | with self.builtin_trap: |
|
1980 | with self.builtin_trap: | |
2010 | return self.Completer.complete(text, line, cursor_pos) |
|
1981 | return self.Completer.complete(text, line, cursor_pos) | |
2011 |
|
1982 | |||
2012 | def set_custom_completer(self, completer, pos=0): |
|
1983 | def set_custom_completer(self, completer, pos=0): | |
2013 | """Adds a new custom completer function. |
|
1984 | """Adds a new custom completer function. | |
2014 |
|
1985 | |||
2015 | The position argument (defaults to 0) is the index in the completers |
|
1986 | The position argument (defaults to 0) is the index in the completers | |
2016 | list where you want the completer to be inserted.""" |
|
1987 | list where you want the completer to be inserted.""" | |
2017 |
|
1988 | |||
2018 | newcomp = types.MethodType(completer,self.Completer) |
|
1989 | newcomp = types.MethodType(completer,self.Completer) | |
2019 | self.Completer.matchers.insert(pos,newcomp) |
|
1990 | self.Completer.matchers.insert(pos,newcomp) | |
2020 |
|
1991 | |||
2021 | def set_readline_completer(self): |
|
1992 | def set_readline_completer(self): | |
2022 | """Reset readline's completer to be our own.""" |
|
1993 | """Reset readline's completer to be our own.""" | |
2023 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1994 | self.readline.set_completer(self.Completer.rlcomplete) | |
2024 |
|
1995 | |||
2025 | def set_completer_frame(self, frame=None): |
|
1996 | def set_completer_frame(self, frame=None): | |
2026 | """Set the frame of the completer.""" |
|
1997 | """Set the frame of the completer.""" | |
2027 | if frame: |
|
1998 | if frame: | |
2028 | self.Completer.namespace = frame.f_locals |
|
1999 | self.Completer.namespace = frame.f_locals | |
2029 | self.Completer.global_namespace = frame.f_globals |
|
2000 | self.Completer.global_namespace = frame.f_globals | |
2030 | else: |
|
2001 | else: | |
2031 | self.Completer.namespace = self.user_ns |
|
2002 | self.Completer.namespace = self.user_ns | |
2032 | self.Completer.global_namespace = self.user_global_ns |
|
2003 | self.Completer.global_namespace = self.user_global_ns | |
2033 |
|
2004 | |||
2034 | #------------------------------------------------------------------------- |
|
2005 | #------------------------------------------------------------------------- | |
2035 | # Things related to magics |
|
2006 | # Things related to magics | |
2036 | #------------------------------------------------------------------------- |
|
2007 | #------------------------------------------------------------------------- | |
2037 |
|
2008 | |||
2038 | def init_magics(self): |
|
2009 | def init_magics(self): | |
2039 | from IPython.core import magics as m |
|
2010 | from IPython.core import magics as m | |
2040 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2011 | self.magics_manager = magic.MagicsManager(shell=self, | |
2041 | parent=self, |
|
2012 | parent=self, | |
2042 | user_magics=m.UserMagics(self)) |
|
2013 | user_magics=m.UserMagics(self)) | |
2043 | self.configurables.append(self.magics_manager) |
|
2014 | self.configurables.append(self.magics_manager) | |
2044 |
|
2015 | |||
2045 | # Expose as public API from the magics manager |
|
2016 | # Expose as public API from the magics manager | |
2046 | self.register_magics = self.magics_manager.register |
|
2017 | self.register_magics = self.magics_manager.register | |
2047 | self.register_magic_function = self.magics_manager.register_function |
|
2018 | self.register_magic_function = self.magics_manager.register_function | |
2048 | self.define_magic = self.magics_manager.define_magic |
|
2019 | self.define_magic = self.magics_manager.define_magic | |
2049 |
|
2020 | |||
2050 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2021 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, | |
2051 | m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2022 | m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics, | |
2052 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2023 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, | |
2053 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2024 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, | |
2054 | ) |
|
2025 | ) | |
2055 |
|
2026 | |||
2056 | # Register Magic Aliases |
|
2027 | # Register Magic Aliases | |
2057 | mman = self.magics_manager |
|
2028 | mman = self.magics_manager | |
2058 | # FIXME: magic aliases should be defined by the Magics classes |
|
2029 | # FIXME: magic aliases should be defined by the Magics classes | |
2059 | # or in MagicsManager, not here |
|
2030 | # or in MagicsManager, not here | |
2060 | mman.register_alias('ed', 'edit') |
|
2031 | mman.register_alias('ed', 'edit') | |
2061 | mman.register_alias('hist', 'history') |
|
2032 | mman.register_alias('hist', 'history') | |
2062 | mman.register_alias('rep', 'recall') |
|
2033 | mman.register_alias('rep', 'recall') | |
2063 | mman.register_alias('SVG', 'svg', 'cell') |
|
2034 | mman.register_alias('SVG', 'svg', 'cell') | |
2064 | mman.register_alias('HTML', 'html', 'cell') |
|
2035 | mman.register_alias('HTML', 'html', 'cell') | |
2065 | mman.register_alias('file', 'writefile', 'cell') |
|
2036 | mman.register_alias('file', 'writefile', 'cell') | |
2066 |
|
2037 | |||
2067 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2038 | # FIXME: Move the color initialization to the DisplayHook, which | |
2068 | # should be split into a prompt manager and displayhook. We probably |
|
2039 | # should be split into a prompt manager and displayhook. We probably | |
2069 | # even need a centralize colors management object. |
|
2040 | # even need a centralize colors management object. | |
2070 | self.magic('colors %s' % self.colors) |
|
2041 | self.magic('colors %s' % self.colors) | |
2071 |
|
2042 | |||
2072 | def run_line_magic(self, magic_name, line): |
|
2043 | def run_line_magic(self, magic_name, line): | |
2073 | """Execute the given line magic. |
|
2044 | """Execute the given line magic. | |
2074 |
|
2045 | |||
2075 | Parameters |
|
2046 | Parameters | |
2076 | ---------- |
|
2047 | ---------- | |
2077 | magic_name : str |
|
2048 | magic_name : str | |
2078 | Name of the desired magic function, without '%' prefix. |
|
2049 | Name of the desired magic function, without '%' prefix. | |
2079 |
|
2050 | |||
2080 | line : str |
|
2051 | line : str | |
2081 | The rest of the input line as a single string. |
|
2052 | The rest of the input line as a single string. | |
2082 | """ |
|
2053 | """ | |
2083 | fn = self.find_line_magic(magic_name) |
|
2054 | fn = self.find_line_magic(magic_name) | |
2084 | if fn is None: |
|
2055 | if fn is None: | |
2085 | cm = self.find_cell_magic(magic_name) |
|
2056 | cm = self.find_cell_magic(magic_name) | |
2086 | etpl = "Line magic function `%%%s` not found%s." |
|
2057 | etpl = "Line magic function `%%%s` not found%s." | |
2087 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2058 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' | |
2088 | 'did you mean that instead?)' % magic_name ) |
|
2059 | 'did you mean that instead?)' % magic_name ) | |
2089 | error(etpl % (magic_name, extra)) |
|
2060 | error(etpl % (magic_name, extra)) | |
2090 | else: |
|
2061 | else: | |
2091 | # Note: this is the distance in the stack to the user's frame. |
|
2062 | # Note: this is the distance in the stack to the user's frame. | |
2092 | # This will need to be updated if the internal calling logic gets |
|
2063 | # This will need to be updated if the internal calling logic gets | |
2093 | # refactored, or else we'll be expanding the wrong variables. |
|
2064 | # refactored, or else we'll be expanding the wrong variables. | |
2094 | stack_depth = 2 |
|
2065 | stack_depth = 2 | |
2095 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2066 | magic_arg_s = self.var_expand(line, stack_depth) | |
2096 | # Put magic args in a list so we can call with f(*a) syntax |
|
2067 | # Put magic args in a list so we can call with f(*a) syntax | |
2097 | args = [magic_arg_s] |
|
2068 | args = [magic_arg_s] | |
2098 | kwargs = {} |
|
2069 | kwargs = {} | |
2099 | # Grab local namespace if we need it: |
|
2070 | # Grab local namespace if we need it: | |
2100 | if getattr(fn, "needs_local_scope", False): |
|
2071 | if getattr(fn, "needs_local_scope", False): | |
2101 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2072 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals | |
2102 | with self.builtin_trap: |
|
2073 | with self.builtin_trap: | |
2103 | result = fn(*args,**kwargs) |
|
2074 | result = fn(*args,**kwargs) | |
2104 | return result |
|
2075 | return result | |
2105 |
|
2076 | |||
2106 | def run_cell_magic(self, magic_name, line, cell): |
|
2077 | def run_cell_magic(self, magic_name, line, cell): | |
2107 | """Execute the given cell magic. |
|
2078 | """Execute the given cell magic. | |
2108 |
|
2079 | |||
2109 | Parameters |
|
2080 | Parameters | |
2110 | ---------- |
|
2081 | ---------- | |
2111 | magic_name : str |
|
2082 | magic_name : str | |
2112 | Name of the desired magic function, without '%' prefix. |
|
2083 | Name of the desired magic function, without '%' prefix. | |
2113 |
|
2084 | |||
2114 | line : str |
|
2085 | line : str | |
2115 | The rest of the first input line as a single string. |
|
2086 | The rest of the first input line as a single string. | |
2116 |
|
2087 | |||
2117 | cell : str |
|
2088 | cell : str | |
2118 | The body of the cell as a (possibly multiline) string. |
|
2089 | The body of the cell as a (possibly multiline) string. | |
2119 | """ |
|
2090 | """ | |
2120 | fn = self.find_cell_magic(magic_name) |
|
2091 | fn = self.find_cell_magic(magic_name) | |
2121 | if fn is None: |
|
2092 | if fn is None: | |
2122 | lm = self.find_line_magic(magic_name) |
|
2093 | lm = self.find_line_magic(magic_name) | |
2123 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2094 | etpl = "Cell magic `%%{0}` not found{1}." | |
2124 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2095 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' | |
2125 | 'did you mean that instead?)'.format(magic_name)) |
|
2096 | 'did you mean that instead?)'.format(magic_name)) | |
2126 | error(etpl.format(magic_name, extra)) |
|
2097 | error(etpl.format(magic_name, extra)) | |
2127 | elif cell == '': |
|
2098 | elif cell == '': | |
2128 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2099 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) | |
2129 | if self.find_line_magic(magic_name) is not None: |
|
2100 | if self.find_line_magic(magic_name) is not None: | |
2130 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2101 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) | |
2131 | raise UsageError(message) |
|
2102 | raise UsageError(message) | |
2132 | else: |
|
2103 | else: | |
2133 | # Note: this is the distance in the stack to the user's frame. |
|
2104 | # Note: this is the distance in the stack to the user's frame. | |
2134 | # This will need to be updated if the internal calling logic gets |
|
2105 | # This will need to be updated if the internal calling logic gets | |
2135 | # refactored, or else we'll be expanding the wrong variables. |
|
2106 | # refactored, or else we'll be expanding the wrong variables. | |
2136 | stack_depth = 2 |
|
2107 | stack_depth = 2 | |
2137 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2108 | magic_arg_s = self.var_expand(line, stack_depth) | |
2138 | with self.builtin_trap: |
|
2109 | with self.builtin_trap: | |
2139 | result = fn(magic_arg_s, cell) |
|
2110 | result = fn(magic_arg_s, cell) | |
2140 | return result |
|
2111 | return result | |
2141 |
|
2112 | |||
2142 | def find_line_magic(self, magic_name): |
|
2113 | def find_line_magic(self, magic_name): | |
2143 | """Find and return a line magic by name. |
|
2114 | """Find and return a line magic by name. | |
2144 |
|
2115 | |||
2145 | Returns None if the magic isn't found.""" |
|
2116 | Returns None if the magic isn't found.""" | |
2146 | return self.magics_manager.magics['line'].get(magic_name) |
|
2117 | return self.magics_manager.magics['line'].get(magic_name) | |
2147 |
|
2118 | |||
2148 | def find_cell_magic(self, magic_name): |
|
2119 | def find_cell_magic(self, magic_name): | |
2149 | """Find and return a cell magic by name. |
|
2120 | """Find and return a cell magic by name. | |
2150 |
|
2121 | |||
2151 | Returns None if the magic isn't found.""" |
|
2122 | Returns None if the magic isn't found.""" | |
2152 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2123 | return self.magics_manager.magics['cell'].get(magic_name) | |
2153 |
|
2124 | |||
2154 | def find_magic(self, magic_name, magic_kind='line'): |
|
2125 | def find_magic(self, magic_name, magic_kind='line'): | |
2155 | """Find and return a magic of the given type by name. |
|
2126 | """Find and return a magic of the given type by name. | |
2156 |
|
2127 | |||
2157 | Returns None if the magic isn't found.""" |
|
2128 | Returns None if the magic isn't found.""" | |
2158 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2129 | return self.magics_manager.magics[magic_kind].get(magic_name) | |
2159 |
|
2130 | |||
2160 | def magic(self, arg_s): |
|
2131 | def magic(self, arg_s): | |
2161 | """DEPRECATED. Use run_line_magic() instead. |
|
2132 | """DEPRECATED. Use run_line_magic() instead. | |
2162 |
|
2133 | |||
2163 | Call a magic function by name. |
|
2134 | Call a magic function by name. | |
2164 |
|
2135 | |||
2165 | Input: a string containing the name of the magic function to call and |
|
2136 | Input: a string containing the name of the magic function to call and | |
2166 | any additional arguments to be passed to the magic. |
|
2137 | any additional arguments to be passed to the magic. | |
2167 |
|
2138 | |||
2168 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2139 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
2169 | prompt: |
|
2140 | prompt: | |
2170 |
|
2141 | |||
2171 | In[1]: %name -opt foo bar |
|
2142 | In[1]: %name -opt foo bar | |
2172 |
|
2143 | |||
2173 | To call a magic without arguments, simply use magic('name'). |
|
2144 | To call a magic without arguments, simply use magic('name'). | |
2174 |
|
2145 | |||
2175 | This provides a proper Python function to call IPython's magics in any |
|
2146 | This provides a proper Python function to call IPython's magics in any | |
2176 | valid Python code you can type at the interpreter, including loops and |
|
2147 | valid Python code you can type at the interpreter, including loops and | |
2177 | compound statements. |
|
2148 | compound statements. | |
2178 | """ |
|
2149 | """ | |
2179 | # TODO: should we issue a loud deprecation warning here? |
|
2150 | # TODO: should we issue a loud deprecation warning here? | |
2180 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2151 | magic_name, _, magic_arg_s = arg_s.partition(' ') | |
2181 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2152 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
2182 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2153 | return self.run_line_magic(magic_name, magic_arg_s) | |
2183 |
|
2154 | |||
2184 | #------------------------------------------------------------------------- |
|
2155 | #------------------------------------------------------------------------- | |
2185 | # Things related to macros |
|
2156 | # Things related to macros | |
2186 | #------------------------------------------------------------------------- |
|
2157 | #------------------------------------------------------------------------- | |
2187 |
|
2158 | |||
2188 | def define_macro(self, name, themacro): |
|
2159 | def define_macro(self, name, themacro): | |
2189 | """Define a new macro |
|
2160 | """Define a new macro | |
2190 |
|
2161 | |||
2191 | Parameters |
|
2162 | Parameters | |
2192 | ---------- |
|
2163 | ---------- | |
2193 | name : str |
|
2164 | name : str | |
2194 | The name of the macro. |
|
2165 | The name of the macro. | |
2195 | themacro : str or Macro |
|
2166 | themacro : str or Macro | |
2196 | The action to do upon invoking the macro. If a string, a new |
|
2167 | The action to do upon invoking the macro. If a string, a new | |
2197 | Macro object is created by passing the string to it. |
|
2168 | Macro object is created by passing the string to it. | |
2198 | """ |
|
2169 | """ | |
2199 |
|
2170 | |||
2200 | from IPython.core import macro |
|
2171 | from IPython.core import macro | |
2201 |
|
2172 | |||
2202 | if isinstance(themacro, basestring): |
|
2173 | if isinstance(themacro, basestring): | |
2203 | themacro = macro.Macro(themacro) |
|
2174 | themacro = macro.Macro(themacro) | |
2204 | if not isinstance(themacro, macro.Macro): |
|
2175 | if not isinstance(themacro, macro.Macro): | |
2205 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2176 | raise ValueError('A macro must be a string or a Macro instance.') | |
2206 | self.user_ns[name] = themacro |
|
2177 | self.user_ns[name] = themacro | |
2207 |
|
2178 | |||
2208 | #------------------------------------------------------------------------- |
|
2179 | #------------------------------------------------------------------------- | |
2209 | # Things related to the running of system commands |
|
2180 | # Things related to the running of system commands | |
2210 | #------------------------------------------------------------------------- |
|
2181 | #------------------------------------------------------------------------- | |
2211 |
|
2182 | |||
2212 | def system_piped(self, cmd): |
|
2183 | def system_piped(self, cmd): | |
2213 | """Call the given cmd in a subprocess, piping stdout/err |
|
2184 | """Call the given cmd in a subprocess, piping stdout/err | |
2214 |
|
2185 | |||
2215 | Parameters |
|
2186 | Parameters | |
2216 | ---------- |
|
2187 | ---------- | |
2217 | cmd : str |
|
2188 | cmd : str | |
2218 | Command to execute (can not end in '&', as background processes are |
|
2189 | Command to execute (can not end in '&', as background processes are | |
2219 | not supported. Should not be a command that expects input |
|
2190 | not supported. Should not be a command that expects input | |
2220 | other than simple text. |
|
2191 | other than simple text. | |
2221 | """ |
|
2192 | """ | |
2222 | if cmd.rstrip().endswith('&'): |
|
2193 | if cmd.rstrip().endswith('&'): | |
2223 | # this is *far* from a rigorous test |
|
2194 | # this is *far* from a rigorous test | |
2224 | # We do not support backgrounding processes because we either use |
|
2195 | # We do not support backgrounding processes because we either use | |
2225 | # pexpect or pipes to read from. Users can always just call |
|
2196 | # pexpect or pipes to read from. Users can always just call | |
2226 | # os.system() or use ip.system=ip.system_raw |
|
2197 | # os.system() or use ip.system=ip.system_raw | |
2227 | # if they really want a background process. |
|
2198 | # if they really want a background process. | |
2228 | raise OSError("Background processes not supported.") |
|
2199 | raise OSError("Background processes not supported.") | |
2229 |
|
2200 | |||
2230 | # we explicitly do NOT return the subprocess status code, because |
|
2201 | # we explicitly do NOT return the subprocess status code, because | |
2231 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2202 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2232 | # Instead, we store the exit_code in user_ns. |
|
2203 | # Instead, we store the exit_code in user_ns. | |
2233 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2204 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) | |
2234 |
|
2205 | |||
2235 | def system_raw(self, cmd): |
|
2206 | def system_raw(self, cmd): | |
2236 | """Call the given cmd in a subprocess using os.system |
|
2207 | """Call the given cmd in a subprocess using os.system | |
2237 |
|
2208 | |||
2238 | Parameters |
|
2209 | Parameters | |
2239 | ---------- |
|
2210 | ---------- | |
2240 | cmd : str |
|
2211 | cmd : str | |
2241 | Command to execute. |
|
2212 | Command to execute. | |
2242 | """ |
|
2213 | """ | |
2243 | cmd = self.var_expand(cmd, depth=1) |
|
2214 | cmd = self.var_expand(cmd, depth=1) | |
2244 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2215 | # protect os.system from UNC paths on Windows, which it can't handle: | |
2245 | if sys.platform == 'win32': |
|
2216 | if sys.platform == 'win32': | |
2246 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2217 | from IPython.utils._process_win32 import AvoidUNCPath | |
2247 | with AvoidUNCPath() as path: |
|
2218 | with AvoidUNCPath() as path: | |
2248 | if path is not None: |
|
2219 | if path is not None: | |
2249 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2220 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
2250 | cmd = py3compat.unicode_to_str(cmd) |
|
2221 | cmd = py3compat.unicode_to_str(cmd) | |
2251 | ec = os.system(cmd) |
|
2222 | ec = os.system(cmd) | |
2252 | else: |
|
2223 | else: | |
2253 | cmd = py3compat.unicode_to_str(cmd) |
|
2224 | cmd = py3compat.unicode_to_str(cmd) | |
2254 | ec = os.system(cmd) |
|
2225 | ec = os.system(cmd) | |
2255 | # The high byte is the exit code, the low byte is a signal number |
|
2226 | # The high byte is the exit code, the low byte is a signal number | |
2256 | # that we discard for now. See the docs for os.wait() |
|
2227 | # that we discard for now. See the docs for os.wait() | |
2257 | if ec > 255: |
|
2228 | if ec > 255: | |
2258 | ec >>= 8 |
|
2229 | ec >>= 8 | |
2259 |
|
2230 | |||
2260 | # We explicitly do NOT return the subprocess status code, because |
|
2231 | # We explicitly do NOT return the subprocess status code, because | |
2261 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2232 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2262 | # Instead, we store the exit_code in user_ns. |
|
2233 | # Instead, we store the exit_code in user_ns. | |
2263 | self.user_ns['_exit_code'] = ec |
|
2234 | self.user_ns['_exit_code'] = ec | |
2264 |
|
2235 | |||
2265 | # use piped system by default, because it is better behaved |
|
2236 | # use piped system by default, because it is better behaved | |
2266 | system = system_piped |
|
2237 | system = system_piped | |
2267 |
|
2238 | |||
2268 | def getoutput(self, cmd, split=True, depth=0): |
|
2239 | def getoutput(self, cmd, split=True, depth=0): | |
2269 | """Get output (possibly including stderr) from a subprocess. |
|
2240 | """Get output (possibly including stderr) from a subprocess. | |
2270 |
|
2241 | |||
2271 | Parameters |
|
2242 | Parameters | |
2272 | ---------- |
|
2243 | ---------- | |
2273 | cmd : str |
|
2244 | cmd : str | |
2274 | Command to execute (can not end in '&', as background processes are |
|
2245 | Command to execute (can not end in '&', as background processes are | |
2275 | not supported. |
|
2246 | not supported. | |
2276 | split : bool, optional |
|
2247 | split : bool, optional | |
2277 | If True, split the output into an IPython SList. Otherwise, an |
|
2248 | If True, split the output into an IPython SList. Otherwise, an | |
2278 | IPython LSString is returned. These are objects similar to normal |
|
2249 | IPython LSString is returned. These are objects similar to normal | |
2279 | lists and strings, with a few convenience attributes for easier |
|
2250 | lists and strings, with a few convenience attributes for easier | |
2280 | manipulation of line-based output. You can use '?' on them for |
|
2251 | manipulation of line-based output. You can use '?' on them for | |
2281 | details. |
|
2252 | details. | |
2282 | depth : int, optional |
|
2253 | depth : int, optional | |
2283 | How many frames above the caller are the local variables which should |
|
2254 | How many frames above the caller are the local variables which should | |
2284 | be expanded in the command string? The default (0) assumes that the |
|
2255 | be expanded in the command string? The default (0) assumes that the | |
2285 | expansion variables are in the stack frame calling this function. |
|
2256 | expansion variables are in the stack frame calling this function. | |
2286 | """ |
|
2257 | """ | |
2287 | if cmd.rstrip().endswith('&'): |
|
2258 | if cmd.rstrip().endswith('&'): | |
2288 | # this is *far* from a rigorous test |
|
2259 | # this is *far* from a rigorous test | |
2289 | raise OSError("Background processes not supported.") |
|
2260 | raise OSError("Background processes not supported.") | |
2290 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2261 | out = getoutput(self.var_expand(cmd, depth=depth+1)) | |
2291 | if split: |
|
2262 | if split: | |
2292 | out = SList(out.splitlines()) |
|
2263 | out = SList(out.splitlines()) | |
2293 | else: |
|
2264 | else: | |
2294 | out = LSString(out) |
|
2265 | out = LSString(out) | |
2295 | return out |
|
2266 | return out | |
2296 |
|
2267 | |||
2297 | #------------------------------------------------------------------------- |
|
2268 | #------------------------------------------------------------------------- | |
2298 | # Things related to aliases |
|
2269 | # Things related to aliases | |
2299 | #------------------------------------------------------------------------- |
|
2270 | #------------------------------------------------------------------------- | |
2300 |
|
2271 | |||
2301 | def init_alias(self): |
|
2272 | def init_alias(self): | |
2302 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2273 | self.alias_manager = AliasManager(shell=self, parent=self) | |
2303 | self.configurables.append(self.alias_manager) |
|
2274 | self.configurables.append(self.alias_manager) | |
2304 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
2275 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
2305 |
|
2276 | |||
2306 | #------------------------------------------------------------------------- |
|
2277 | #------------------------------------------------------------------------- | |
2307 | # Things related to extensions |
|
2278 | # Things related to extensions | |
2308 | #------------------------------------------------------------------------- |
|
2279 | #------------------------------------------------------------------------- | |
2309 |
|
2280 | |||
2310 | def init_extension_manager(self): |
|
2281 | def init_extension_manager(self): | |
2311 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2282 | self.extension_manager = ExtensionManager(shell=self, parent=self) | |
2312 | self.configurables.append(self.extension_manager) |
|
2283 | self.configurables.append(self.extension_manager) | |
2313 |
|
2284 | |||
2314 | #------------------------------------------------------------------------- |
|
2285 | #------------------------------------------------------------------------- | |
2315 | # Things related to payloads |
|
2286 | # Things related to payloads | |
2316 | #------------------------------------------------------------------------- |
|
2287 | #------------------------------------------------------------------------- | |
2317 |
|
2288 | |||
2318 | def init_payload(self): |
|
2289 | def init_payload(self): | |
2319 | self.payload_manager = PayloadManager(parent=self) |
|
2290 | self.payload_manager = PayloadManager(parent=self) | |
2320 | self.configurables.append(self.payload_manager) |
|
2291 | self.configurables.append(self.payload_manager) | |
2321 |
|
2292 | |||
2322 | #------------------------------------------------------------------------- |
|
2293 | #------------------------------------------------------------------------- | |
2323 | # Things related to the prefilter |
|
2294 | # Things related to the prefilter | |
2324 | #------------------------------------------------------------------------- |
|
2295 | #------------------------------------------------------------------------- | |
2325 |
|
2296 | |||
2326 | def init_prefilter(self): |
|
2297 | def init_prefilter(self): | |
2327 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2298 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) | |
2328 | self.configurables.append(self.prefilter_manager) |
|
2299 | self.configurables.append(self.prefilter_manager) | |
2329 | # Ultimately this will be refactored in the new interpreter code, but |
|
2300 | # Ultimately this will be refactored in the new interpreter code, but | |
2330 | # for now, we should expose the main prefilter method (there's legacy |
|
2301 | # for now, we should expose the main prefilter method (there's legacy | |
2331 | # code out there that may rely on this). |
|
2302 | # code out there that may rely on this). | |
2332 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2303 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2333 |
|
2304 | |||
2334 | def auto_rewrite_input(self, cmd): |
|
2305 | def auto_rewrite_input(self, cmd): | |
2335 | """Print to the screen the rewritten form of the user's command. |
|
2306 | """Print to the screen the rewritten form of the user's command. | |
2336 |
|
2307 | |||
2337 | This shows visual feedback by rewriting input lines that cause |
|
2308 | This shows visual feedback by rewriting input lines that cause | |
2338 | automatic calling to kick in, like:: |
|
2309 | automatic calling to kick in, like:: | |
2339 |
|
2310 | |||
2340 | /f x |
|
2311 | /f x | |
2341 |
|
2312 | |||
2342 | into:: |
|
2313 | into:: | |
2343 |
|
2314 | |||
2344 | ------> f(x) |
|
2315 | ------> f(x) | |
2345 |
|
2316 | |||
2346 | after the user's input prompt. This helps the user understand that the |
|
2317 | after the user's input prompt. This helps the user understand that the | |
2347 | input line was transformed automatically by IPython. |
|
2318 | input line was transformed automatically by IPython. | |
2348 | """ |
|
2319 | """ | |
2349 | if not self.show_rewritten_input: |
|
2320 | if not self.show_rewritten_input: | |
2350 | return |
|
2321 | return | |
2351 |
|
2322 | |||
2352 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2323 | rw = self.prompt_manager.render('rewrite') + cmd | |
2353 |
|
2324 | |||
2354 | try: |
|
2325 | try: | |
2355 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2326 | # plain ascii works better w/ pyreadline, on some machines, so | |
2356 | # we use it and only print uncolored rewrite if we have unicode |
|
2327 | # we use it and only print uncolored rewrite if we have unicode | |
2357 | rw = str(rw) |
|
2328 | rw = str(rw) | |
2358 | print(rw, file=io.stdout) |
|
2329 | print(rw, file=io.stdout) | |
2359 | except UnicodeEncodeError: |
|
2330 | except UnicodeEncodeError: | |
2360 | print("------> " + cmd) |
|
2331 | print("------> " + cmd) | |
2361 |
|
2332 | |||
2362 | #------------------------------------------------------------------------- |
|
2333 | #------------------------------------------------------------------------- | |
2363 | # Things related to extracting values/expressions from kernel and user_ns |
|
2334 | # Things related to extracting values/expressions from kernel and user_ns | |
2364 | #------------------------------------------------------------------------- |
|
2335 | #------------------------------------------------------------------------- | |
2365 |
|
2336 | |||
2366 | def _user_obj_error(self): |
|
2337 | def _user_obj_error(self): | |
2367 | """return simple exception dict |
|
2338 | """return simple exception dict | |
2368 |
|
2339 | |||
2369 | for use in user_variables / expressions |
|
2340 | for use in user_variables / expressions | |
2370 | """ |
|
2341 | """ | |
2371 |
|
2342 | |||
2372 | etype, evalue, tb = self._get_exc_info() |
|
2343 | etype, evalue, tb = self._get_exc_info() | |
2373 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2344 | stb = self.InteractiveTB.get_exception_only(etype, evalue) | |
2374 |
|
2345 | |||
2375 | exc_info = { |
|
2346 | exc_info = { | |
2376 | u'status' : 'error', |
|
2347 | u'status' : 'error', | |
2377 | u'traceback' : stb, |
|
2348 | u'traceback' : stb, | |
2378 | u'ename' : unicode(etype.__name__), |
|
2349 | u'ename' : unicode(etype.__name__), | |
2379 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2350 | u'evalue' : py3compat.safe_unicode(evalue), | |
2380 | } |
|
2351 | } | |
2381 |
|
2352 | |||
2382 | return exc_info |
|
2353 | return exc_info | |
2383 |
|
2354 | |||
2384 | def _format_user_obj(self, obj): |
|
2355 | def _format_user_obj(self, obj): | |
2385 | """format a user object to display dict |
|
2356 | """format a user object to display dict | |
2386 |
|
2357 | |||
2387 | for use in user_expressions / variables |
|
2358 | for use in user_expressions / variables | |
2388 | """ |
|
2359 | """ | |
2389 |
|
2360 | |||
2390 | data, md = self.display_formatter.format(obj) |
|
2361 | data, md = self.display_formatter.format(obj) | |
2391 | value = { |
|
2362 | value = { | |
2392 | 'status' : 'ok', |
|
2363 | 'status' : 'ok', | |
2393 | 'data' : data, |
|
2364 | 'data' : data, | |
2394 | 'metadata' : md, |
|
2365 | 'metadata' : md, | |
2395 | } |
|
2366 | } | |
2396 | return value |
|
2367 | return value | |
2397 |
|
2368 | |||
2398 | def user_variables(self, names): |
|
2369 | def user_variables(self, names): | |
2399 | """Get a list of variable names from the user's namespace. |
|
2370 | """Get a list of variable names from the user's namespace. | |
2400 |
|
2371 | |||
2401 | Parameters |
|
2372 | Parameters | |
2402 | ---------- |
|
2373 | ---------- | |
2403 | names : list of strings |
|
2374 | names : list of strings | |
2404 | A list of names of variables to be read from the user namespace. |
|
2375 | A list of names of variables to be read from the user namespace. | |
2405 |
|
2376 | |||
2406 | Returns |
|
2377 | Returns | |
2407 | ------- |
|
2378 | ------- | |
2408 | A dict, keyed by the input names and with the rich mime-type repr(s) of each value. |
|
2379 | A dict, keyed by the input names and with the rich mime-type repr(s) of each value. | |
2409 | Each element will be a sub-dict of the same form as a display_data message. |
|
2380 | Each element will be a sub-dict of the same form as a display_data message. | |
2410 | """ |
|
2381 | """ | |
2411 | out = {} |
|
2382 | out = {} | |
2412 | user_ns = self.user_ns |
|
2383 | user_ns = self.user_ns | |
2413 |
|
2384 | |||
2414 | for varname in names: |
|
2385 | for varname in names: | |
2415 | try: |
|
2386 | try: | |
2416 | value = self._format_user_obj(user_ns[varname]) |
|
2387 | value = self._format_user_obj(user_ns[varname]) | |
2417 | except: |
|
2388 | except: | |
2418 | value = self._user_obj_error() |
|
2389 | value = self._user_obj_error() | |
2419 | out[varname] = value |
|
2390 | out[varname] = value | |
2420 | return out |
|
2391 | return out | |
2421 |
|
2392 | |||
2422 | def user_expressions(self, expressions): |
|
2393 | def user_expressions(self, expressions): | |
2423 | """Evaluate a dict of expressions in the user's namespace. |
|
2394 | """Evaluate a dict of expressions in the user's namespace. | |
2424 |
|
2395 | |||
2425 | Parameters |
|
2396 | Parameters | |
2426 | ---------- |
|
2397 | ---------- | |
2427 | expressions : dict |
|
2398 | expressions : dict | |
2428 | A dict with string keys and string values. The expression values |
|
2399 | A dict with string keys and string values. The expression values | |
2429 | should be valid Python expressions, each of which will be evaluated |
|
2400 | should be valid Python expressions, each of which will be evaluated | |
2430 | in the user namespace. |
|
2401 | in the user namespace. | |
2431 |
|
2402 | |||
2432 | Returns |
|
2403 | Returns | |
2433 | ------- |
|
2404 | ------- | |
2434 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2405 | A dict, keyed like the input expressions dict, with the rich mime-typed | |
2435 | display_data of each value. |
|
2406 | display_data of each value. | |
2436 | """ |
|
2407 | """ | |
2437 | out = {} |
|
2408 | out = {} | |
2438 | user_ns = self.user_ns |
|
2409 | user_ns = self.user_ns | |
2439 | global_ns = self.user_global_ns |
|
2410 | global_ns = self.user_global_ns | |
2440 |
|
2411 | |||
2441 | for key, expr in expressions.iteritems(): |
|
2412 | for key, expr in expressions.iteritems(): | |
2442 | try: |
|
2413 | try: | |
2443 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2414 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) | |
2444 | except: |
|
2415 | except: | |
2445 | value = self._user_obj_error() |
|
2416 | value = self._user_obj_error() | |
2446 | out[key] = value |
|
2417 | out[key] = value | |
2447 | return out |
|
2418 | return out | |
2448 |
|
2419 | |||
2449 | #------------------------------------------------------------------------- |
|
2420 | #------------------------------------------------------------------------- | |
2450 | # Things related to the running of code |
|
2421 | # Things related to the running of code | |
2451 | #------------------------------------------------------------------------- |
|
2422 | #------------------------------------------------------------------------- | |
2452 |
|
2423 | |||
2453 | def ex(self, cmd): |
|
2424 | def ex(self, cmd): | |
2454 | """Execute a normal python statement in user namespace.""" |
|
2425 | """Execute a normal python statement in user namespace.""" | |
2455 | with self.builtin_trap: |
|
2426 | with self.builtin_trap: | |
2456 | exec cmd in self.user_global_ns, self.user_ns |
|
2427 | exec cmd in self.user_global_ns, self.user_ns | |
2457 |
|
2428 | |||
2458 | def ev(self, expr): |
|
2429 | def ev(self, expr): | |
2459 | """Evaluate python expression expr in user namespace. |
|
2430 | """Evaluate python expression expr in user namespace. | |
2460 |
|
2431 | |||
2461 | Returns the result of evaluation |
|
2432 | Returns the result of evaluation | |
2462 | """ |
|
2433 | """ | |
2463 | with self.builtin_trap: |
|
2434 | with self.builtin_trap: | |
2464 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2435 | return eval(expr, self.user_global_ns, self.user_ns) | |
2465 |
|
2436 | |||
2466 | def safe_execfile(self, fname, *where, **kw): |
|
2437 | def safe_execfile(self, fname, *where, **kw): | |
2467 | """A safe version of the builtin execfile(). |
|
2438 | """A safe version of the builtin execfile(). | |
2468 |
|
2439 | |||
2469 | This version will never throw an exception, but instead print |
|
2440 | This version will never throw an exception, but instead print | |
2470 | helpful error messages to the screen. This only works on pure |
|
2441 | helpful error messages to the screen. This only works on pure | |
2471 | Python files with the .py extension. |
|
2442 | Python files with the .py extension. | |
2472 |
|
2443 | |||
2473 | Parameters |
|
2444 | Parameters | |
2474 | ---------- |
|
2445 | ---------- | |
2475 | fname : string |
|
2446 | fname : string | |
2476 | The name of the file to be executed. |
|
2447 | The name of the file to be executed. | |
2477 | where : tuple |
|
2448 | where : tuple | |
2478 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2449 | One or two namespaces, passed to execfile() as (globals,locals). | |
2479 | If only one is given, it is passed as both. |
|
2450 | If only one is given, it is passed as both. | |
2480 | exit_ignore : bool (False) |
|
2451 | exit_ignore : bool (False) | |
2481 | If True, then silence SystemExit for non-zero status (it is always |
|
2452 | If True, then silence SystemExit for non-zero status (it is always | |
2482 | silenced for zero status, as it is so common). |
|
2453 | silenced for zero status, as it is so common). | |
2483 | raise_exceptions : bool (False) |
|
2454 | raise_exceptions : bool (False) | |
2484 | If True raise exceptions everywhere. Meant for testing. |
|
2455 | If True raise exceptions everywhere. Meant for testing. | |
2485 |
|
2456 | |||
2486 | """ |
|
2457 | """ | |
2487 | kw.setdefault('exit_ignore', False) |
|
2458 | kw.setdefault('exit_ignore', False) | |
2488 | kw.setdefault('raise_exceptions', False) |
|
2459 | kw.setdefault('raise_exceptions', False) | |
2489 |
|
2460 | |||
2490 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2461 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2491 |
|
2462 | |||
2492 | # Make sure we can open the file |
|
2463 | # Make sure we can open the file | |
2493 | try: |
|
2464 | try: | |
2494 | with open(fname) as thefile: |
|
2465 | with open(fname) as thefile: | |
2495 | pass |
|
2466 | pass | |
2496 | except: |
|
2467 | except: | |
2497 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2468 | warn('Could not open file <%s> for safe execution.' % fname) | |
2498 | return |
|
2469 | return | |
2499 |
|
2470 | |||
2500 | # Find things also in current directory. This is needed to mimic the |
|
2471 | # Find things also in current directory. This is needed to mimic the | |
2501 | # behavior of running a script from the system command line, where |
|
2472 | # behavior of running a script from the system command line, where | |
2502 | # Python inserts the script's directory into sys.path |
|
2473 | # Python inserts the script's directory into sys.path | |
2503 | dname = os.path.dirname(fname) |
|
2474 | dname = os.path.dirname(fname) | |
2504 |
|
2475 | |||
2505 | with prepended_to_syspath(dname): |
|
2476 | with prepended_to_syspath(dname): | |
2506 | try: |
|
2477 | try: | |
2507 | py3compat.execfile(fname,*where) |
|
2478 | py3compat.execfile(fname,*where) | |
2508 | except SystemExit as status: |
|
2479 | except SystemExit as status: | |
2509 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2480 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2510 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2481 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2511 | # these are considered normal by the OS: |
|
2482 | # these are considered normal by the OS: | |
2512 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2483 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2513 | # 0 |
|
2484 | # 0 | |
2514 | # > python -c'import sys;sys.exit()'; echo $? |
|
2485 | # > python -c'import sys;sys.exit()'; echo $? | |
2515 | # 0 |
|
2486 | # 0 | |
2516 | # For other exit status, we show the exception unless |
|
2487 | # For other exit status, we show the exception unless | |
2517 | # explicitly silenced, but only in short form. |
|
2488 | # explicitly silenced, but only in short form. | |
2518 | if kw['raise_exceptions']: |
|
2489 | if kw['raise_exceptions']: | |
2519 | raise |
|
2490 | raise | |
2520 | if status.code and not kw['exit_ignore']: |
|
2491 | if status.code and not kw['exit_ignore']: | |
2521 | self.showtraceback(exception_only=True) |
|
2492 | self.showtraceback(exception_only=True) | |
2522 | except: |
|
2493 | except: | |
2523 | if kw['raise_exceptions']: |
|
2494 | if kw['raise_exceptions']: | |
2524 | raise |
|
2495 | raise | |
2525 | self.showtraceback() |
|
2496 | self.showtraceback() | |
2526 |
|
2497 | |||
2527 | def safe_execfile_ipy(self, fname): |
|
2498 | def safe_execfile_ipy(self, fname): | |
2528 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2499 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2529 |
|
2500 | |||
2530 | Parameters |
|
2501 | Parameters | |
2531 | ---------- |
|
2502 | ---------- | |
2532 | fname : str |
|
2503 | fname : str | |
2533 | The name of the file to execute. The filename must have a |
|
2504 | The name of the file to execute. The filename must have a | |
2534 | .ipy extension. |
|
2505 | .ipy extension. | |
2535 | """ |
|
2506 | """ | |
2536 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2507 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2537 |
|
2508 | |||
2538 | # Make sure we can open the file |
|
2509 | # Make sure we can open the file | |
2539 | try: |
|
2510 | try: | |
2540 | with open(fname) as thefile: |
|
2511 | with open(fname) as thefile: | |
2541 | pass |
|
2512 | pass | |
2542 | except: |
|
2513 | except: | |
2543 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2514 | warn('Could not open file <%s> for safe execution.' % fname) | |
2544 | return |
|
2515 | return | |
2545 |
|
2516 | |||
2546 | # Find things also in current directory. This is needed to mimic the |
|
2517 | # Find things also in current directory. This is needed to mimic the | |
2547 | # behavior of running a script from the system command line, where |
|
2518 | # behavior of running a script from the system command line, where | |
2548 | # Python inserts the script's directory into sys.path |
|
2519 | # Python inserts the script's directory into sys.path | |
2549 | dname = os.path.dirname(fname) |
|
2520 | dname = os.path.dirname(fname) | |
2550 |
|
2521 | |||
2551 | with prepended_to_syspath(dname): |
|
2522 | with prepended_to_syspath(dname): | |
2552 | try: |
|
2523 | try: | |
2553 | with open(fname) as thefile: |
|
2524 | with open(fname) as thefile: | |
2554 | # self.run_cell currently captures all exceptions |
|
2525 | # self.run_cell currently captures all exceptions | |
2555 | # raised in user code. It would be nice if there were |
|
2526 | # raised in user code. It would be nice if there were | |
2556 | # versions of runlines, execfile that did raise, so |
|
2527 | # versions of runlines, execfile that did raise, so | |
2557 | # we could catch the errors. |
|
2528 | # we could catch the errors. | |
2558 | self.run_cell(thefile.read(), store_history=False, shell_futures=False) |
|
2529 | self.run_cell(thefile.read(), store_history=False, shell_futures=False) | |
2559 | except: |
|
2530 | except: | |
2560 | self.showtraceback() |
|
2531 | self.showtraceback() | |
2561 | warn('Unknown failure executing file: <%s>' % fname) |
|
2532 | warn('Unknown failure executing file: <%s>' % fname) | |
2562 |
|
2533 | |||
2563 | def safe_run_module(self, mod_name, where): |
|
2534 | def safe_run_module(self, mod_name, where): | |
2564 | """A safe version of runpy.run_module(). |
|
2535 | """A safe version of runpy.run_module(). | |
2565 |
|
2536 | |||
2566 | This version will never throw an exception, but instead print |
|
2537 | This version will never throw an exception, but instead print | |
2567 | helpful error messages to the screen. |
|
2538 | helpful error messages to the screen. | |
2568 |
|
2539 | |||
2569 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2540 | `SystemExit` exceptions with status code 0 or None are ignored. | |
2570 |
|
2541 | |||
2571 | Parameters |
|
2542 | Parameters | |
2572 | ---------- |
|
2543 | ---------- | |
2573 | mod_name : string |
|
2544 | mod_name : string | |
2574 | The name of the module to be executed. |
|
2545 | The name of the module to be executed. | |
2575 | where : dict |
|
2546 | where : dict | |
2576 | The globals namespace. |
|
2547 | The globals namespace. | |
2577 | """ |
|
2548 | """ | |
2578 | try: |
|
2549 | try: | |
2579 | try: |
|
2550 | try: | |
2580 | where.update( |
|
2551 | where.update( | |
2581 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2552 | runpy.run_module(str(mod_name), run_name="__main__", | |
2582 | alter_sys=True) |
|
2553 | alter_sys=True) | |
2583 | ) |
|
2554 | ) | |
2584 | except SystemExit as status: |
|
2555 | except SystemExit as status: | |
2585 | if status.code: |
|
2556 | if status.code: | |
2586 | raise |
|
2557 | raise | |
2587 | except: |
|
2558 | except: | |
2588 | self.showtraceback() |
|
2559 | self.showtraceback() | |
2589 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2560 | warn('Unknown failure executing module: <%s>' % mod_name) | |
2590 |
|
2561 | |||
2591 | def _run_cached_cell_magic(self, magic_name, line): |
|
2562 | def _run_cached_cell_magic(self, magic_name, line): | |
2592 | """Special method to call a cell magic with the data stored in self. |
|
2563 | """Special method to call a cell magic with the data stored in self. | |
2593 | """ |
|
2564 | """ | |
2594 | cell = self._current_cell_magic_body |
|
2565 | cell = self._current_cell_magic_body | |
2595 | self._current_cell_magic_body = None |
|
2566 | self._current_cell_magic_body = None | |
2596 | return self.run_cell_magic(magic_name, line, cell) |
|
2567 | return self.run_cell_magic(magic_name, line, cell) | |
2597 |
|
2568 | |||
2598 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2569 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): | |
2599 | """Run a complete IPython cell. |
|
2570 | """Run a complete IPython cell. | |
2600 |
|
2571 | |||
2601 | Parameters |
|
2572 | Parameters | |
2602 | ---------- |
|
2573 | ---------- | |
2603 | raw_cell : str |
|
2574 | raw_cell : str | |
2604 | The code (including IPython code such as %magic functions) to run. |
|
2575 | The code (including IPython code such as %magic functions) to run. | |
2605 | store_history : bool |
|
2576 | store_history : bool | |
2606 | If True, the raw and translated cell will be stored in IPython's |
|
2577 | If True, the raw and translated cell will be stored in IPython's | |
2607 | history. For user code calling back into IPython's machinery, this |
|
2578 | history. For user code calling back into IPython's machinery, this | |
2608 | should be set to False. |
|
2579 | should be set to False. | |
2609 | silent : bool |
|
2580 | silent : bool | |
2610 | If True, avoid side-effects, such as implicit displayhooks and |
|
2581 | If True, avoid side-effects, such as implicit displayhooks and | |
2611 | and logging. silent=True forces store_history=False. |
|
2582 | and logging. silent=True forces store_history=False. | |
2612 | shell_futures : bool |
|
2583 | shell_futures : bool | |
2613 | If True, the code will share future statements with the interactive |
|
2584 | If True, the code will share future statements with the interactive | |
2614 | shell. It will both be affected by previous __future__ imports, and |
|
2585 | shell. It will both be affected by previous __future__ imports, and | |
2615 | any __future__ imports in the code will affect the shell. If False, |
|
2586 | any __future__ imports in the code will affect the shell. If False, | |
2616 | __future__ imports are not shared in either direction. |
|
2587 | __future__ imports are not shared in either direction. | |
2617 | """ |
|
2588 | """ | |
2618 | if (not raw_cell) or raw_cell.isspace(): |
|
2589 | if (not raw_cell) or raw_cell.isspace(): | |
2619 | return |
|
2590 | return | |
2620 |
|
2591 | |||
2621 | if silent: |
|
2592 | if silent: | |
2622 | store_history = False |
|
2593 | store_history = False | |
2623 |
|
2594 | |||
2624 | self.input_transformer_manager.push(raw_cell) |
|
2595 | self.input_transformer_manager.push(raw_cell) | |
2625 | cell = self.input_transformer_manager.source_reset() |
|
2596 | cell = self.input_transformer_manager.source_reset() | |
2626 |
|
2597 | |||
2627 | # Our own compiler remembers the __future__ environment. If we want to |
|
2598 | # Our own compiler remembers the __future__ environment. If we want to | |
2628 | # run code with a separate __future__ environment, use the default |
|
2599 | # run code with a separate __future__ environment, use the default | |
2629 | # compiler |
|
2600 | # compiler | |
2630 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2601 | compiler = self.compile if shell_futures else CachingCompiler() | |
2631 |
|
2602 | |||
2632 | with self.builtin_trap: |
|
2603 | with self.builtin_trap: | |
2633 | prefilter_failed = False |
|
2604 | prefilter_failed = False | |
2634 | if len(cell.splitlines()) == 1: |
|
2605 | if len(cell.splitlines()) == 1: | |
2635 | try: |
|
2606 | try: | |
2636 | # use prefilter_lines to handle trailing newlines |
|
2607 | # use prefilter_lines to handle trailing newlines | |
2637 | # restore trailing newline for ast.parse |
|
2608 | # restore trailing newline for ast.parse | |
2638 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2609 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' | |
2639 | except AliasError as e: |
|
2610 | except AliasError as e: | |
2640 | error(e) |
|
2611 | error(e) | |
2641 | prefilter_failed = True |
|
2612 | prefilter_failed = True | |
2642 | except Exception: |
|
2613 | except Exception: | |
2643 | # don't allow prefilter errors to crash IPython |
|
2614 | # don't allow prefilter errors to crash IPython | |
2644 | self.showtraceback() |
|
2615 | self.showtraceback() | |
2645 | prefilter_failed = True |
|
2616 | prefilter_failed = True | |
2646 |
|
2617 | |||
2647 | # Store raw and processed history |
|
2618 | # Store raw and processed history | |
2648 | if store_history: |
|
2619 | if store_history: | |
2649 | self.history_manager.store_inputs(self.execution_count, |
|
2620 | self.history_manager.store_inputs(self.execution_count, | |
2650 | cell, raw_cell) |
|
2621 | cell, raw_cell) | |
2651 | if not silent: |
|
2622 | if not silent: | |
2652 | self.logger.log(cell, raw_cell) |
|
2623 | self.logger.log(cell, raw_cell) | |
2653 |
|
2624 | |||
2654 | if not prefilter_failed: |
|
2625 | if not prefilter_failed: | |
2655 | # don't run if prefilter failed |
|
2626 | # don't run if prefilter failed | |
2656 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2627 | cell_name = self.compile.cache(cell, self.execution_count) | |
2657 |
|
2628 | |||
2658 | with self.display_trap: |
|
2629 | with self.display_trap: | |
2659 | try: |
|
2630 | try: | |
2660 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2631 | code_ast = compiler.ast_parse(cell, filename=cell_name) | |
2661 | except IndentationError: |
|
2632 | except IndentationError: | |
2662 | self.showindentationerror() |
|
2633 | self.showindentationerror() | |
2663 | if store_history: |
|
2634 | if store_history: | |
2664 | self.execution_count += 1 |
|
2635 | self.execution_count += 1 | |
2665 | return None |
|
2636 | return None | |
2666 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2637 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2667 | MemoryError): |
|
2638 | MemoryError): | |
2668 | self.showsyntaxerror() |
|
2639 | self.showsyntaxerror() | |
2669 | if store_history: |
|
2640 | if store_history: | |
2670 | self.execution_count += 1 |
|
2641 | self.execution_count += 1 | |
2671 | return None |
|
2642 | return None | |
2672 |
|
2643 | |||
2673 | code_ast = self.transform_ast(code_ast) |
|
2644 | code_ast = self.transform_ast(code_ast) | |
2674 |
|
2645 | |||
2675 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2646 | interactivity = "none" if silent else self.ast_node_interactivity | |
2676 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2647 | self.run_ast_nodes(code_ast.body, cell_name, | |
2677 | interactivity=interactivity, compiler=compiler) |
|
2648 | interactivity=interactivity, compiler=compiler) | |
2678 |
|
2649 | |||
2679 | # Execute any registered post-execution functions. |
|
2650 | # Execute any registered post-execution functions. | |
2680 | # unless we are silent |
|
2651 | # unless we are silent | |
2681 | post_exec = [] if silent else self._post_execute.iteritems() |
|
2652 | post_exec = [] if silent else self._post_execute.iteritems() | |
2682 |
|
2653 | |||
2683 | for func, status in post_exec: |
|
2654 | for func, status in post_exec: | |
2684 | if self.disable_failing_post_execute and not status: |
|
2655 | if self.disable_failing_post_execute and not status: | |
2685 | continue |
|
2656 | continue | |
2686 | try: |
|
2657 | try: | |
2687 | func() |
|
2658 | func() | |
2688 | except KeyboardInterrupt: |
|
2659 | except KeyboardInterrupt: | |
2689 | print("\nKeyboardInterrupt", file=io.stderr) |
|
2660 | print("\nKeyboardInterrupt", file=io.stderr) | |
2690 | except Exception: |
|
2661 | except Exception: | |
2691 | # register as failing: |
|
2662 | # register as failing: | |
2692 | self._post_execute[func] = False |
|
2663 | self._post_execute[func] = False | |
2693 | self.showtraceback() |
|
2664 | self.showtraceback() | |
2694 | print('\n'.join([ |
|
2665 | print('\n'.join([ | |
2695 | "post-execution function %r produced an error." % func, |
|
2666 | "post-execution function %r produced an error." % func, | |
2696 | "If this problem persists, you can disable failing post-exec functions with:", |
|
2667 | "If this problem persists, you can disable failing post-exec functions with:", | |
2697 | "", |
|
2668 | "", | |
2698 | " get_ipython().disable_failing_post_execute = True" |
|
2669 | " get_ipython().disable_failing_post_execute = True" | |
2699 | ]), file=io.stderr) |
|
2670 | ]), file=io.stderr) | |
2700 |
|
2671 | |||
2701 | if store_history: |
|
2672 | if store_history: | |
2702 | # Write output to the database. Does nothing unless |
|
2673 | # Write output to the database. Does nothing unless | |
2703 | # history output logging is enabled. |
|
2674 | # history output logging is enabled. | |
2704 | self.history_manager.store_output(self.execution_count) |
|
2675 | self.history_manager.store_output(self.execution_count) | |
2705 | # Each cell is a *single* input, regardless of how many lines it has |
|
2676 | # Each cell is a *single* input, regardless of how many lines it has | |
2706 | self.execution_count += 1 |
|
2677 | self.execution_count += 1 | |
2707 |
|
2678 | |||
2708 | def transform_ast(self, node): |
|
2679 | def transform_ast(self, node): | |
2709 | """Apply the AST transformations from self.ast_transformers |
|
2680 | """Apply the AST transformations from self.ast_transformers | |
2710 |
|
2681 | |||
2711 | Parameters |
|
2682 | Parameters | |
2712 | ---------- |
|
2683 | ---------- | |
2713 | node : ast.Node |
|
2684 | node : ast.Node | |
2714 | The root node to be transformed. Typically called with the ast.Module |
|
2685 | The root node to be transformed. Typically called with the ast.Module | |
2715 | produced by parsing user input. |
|
2686 | produced by parsing user input. | |
2716 |
|
2687 | |||
2717 | Returns |
|
2688 | Returns | |
2718 | ------- |
|
2689 | ------- | |
2719 | An ast.Node corresponding to the node it was called with. Note that it |
|
2690 | An ast.Node corresponding to the node it was called with. Note that it | |
2720 | may also modify the passed object, so don't rely on references to the |
|
2691 | may also modify the passed object, so don't rely on references to the | |
2721 | original AST. |
|
2692 | original AST. | |
2722 | """ |
|
2693 | """ | |
2723 | for transformer in self.ast_transformers: |
|
2694 | for transformer in self.ast_transformers: | |
2724 | try: |
|
2695 | try: | |
2725 | node = transformer.visit(node) |
|
2696 | node = transformer.visit(node) | |
2726 | except Exception: |
|
2697 | except Exception: | |
2727 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2698 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) | |
2728 | self.ast_transformers.remove(transformer) |
|
2699 | self.ast_transformers.remove(transformer) | |
2729 |
|
2700 | |||
2730 | if self.ast_transformers: |
|
2701 | if self.ast_transformers: | |
2731 | ast.fix_missing_locations(node) |
|
2702 | ast.fix_missing_locations(node) | |
2732 | return node |
|
2703 | return node | |
2733 |
|
2704 | |||
2734 |
|
2705 | |||
2735 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2706 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', | |
2736 | compiler=compile): |
|
2707 | compiler=compile): | |
2737 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2708 | """Run a sequence of AST nodes. The execution mode depends on the | |
2738 | interactivity parameter. |
|
2709 | interactivity parameter. | |
2739 |
|
2710 | |||
2740 | Parameters |
|
2711 | Parameters | |
2741 | ---------- |
|
2712 | ---------- | |
2742 | nodelist : list |
|
2713 | nodelist : list | |
2743 | A sequence of AST nodes to run. |
|
2714 | A sequence of AST nodes to run. | |
2744 | cell_name : str |
|
2715 | cell_name : str | |
2745 | Will be passed to the compiler as the filename of the cell. Typically |
|
2716 | Will be passed to the compiler as the filename of the cell. Typically | |
2746 | the value returned by ip.compile.cache(cell). |
|
2717 | the value returned by ip.compile.cache(cell). | |
2747 | interactivity : str |
|
2718 | interactivity : str | |
2748 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2719 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
2749 | run interactively (displaying output from expressions). 'last_expr' |
|
2720 | run interactively (displaying output from expressions). 'last_expr' | |
2750 | will run the last node interactively only if it is an expression (i.e. |
|
2721 | will run the last node interactively only if it is an expression (i.e. | |
2751 | expressions in loops or other blocks are not displayed. Other values |
|
2722 | expressions in loops or other blocks are not displayed. Other values | |
2752 | for this parameter will raise a ValueError. |
|
2723 | for this parameter will raise a ValueError. | |
2753 | compiler : callable |
|
2724 | compiler : callable | |
2754 | A function with the same interface as the built-in compile(), to turn |
|
2725 | A function with the same interface as the built-in compile(), to turn | |
2755 | the AST nodes into code objects. Default is the built-in compile(). |
|
2726 | the AST nodes into code objects. Default is the built-in compile(). | |
2756 | """ |
|
2727 | """ | |
2757 | if not nodelist: |
|
2728 | if not nodelist: | |
2758 | return |
|
2729 | return | |
2759 |
|
2730 | |||
2760 | if interactivity == 'last_expr': |
|
2731 | if interactivity == 'last_expr': | |
2761 | if isinstance(nodelist[-1], ast.Expr): |
|
2732 | if isinstance(nodelist[-1], ast.Expr): | |
2762 | interactivity = "last" |
|
2733 | interactivity = "last" | |
2763 | else: |
|
2734 | else: | |
2764 | interactivity = "none" |
|
2735 | interactivity = "none" | |
2765 |
|
2736 | |||
2766 | if interactivity == 'none': |
|
2737 | if interactivity == 'none': | |
2767 | to_run_exec, to_run_interactive = nodelist, [] |
|
2738 | to_run_exec, to_run_interactive = nodelist, [] | |
2768 | elif interactivity == 'last': |
|
2739 | elif interactivity == 'last': | |
2769 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2740 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2770 | elif interactivity == 'all': |
|
2741 | elif interactivity == 'all': | |
2771 | to_run_exec, to_run_interactive = [], nodelist |
|
2742 | to_run_exec, to_run_interactive = [], nodelist | |
2772 | else: |
|
2743 | else: | |
2773 | raise ValueError("Interactivity was %r" % interactivity) |
|
2744 | raise ValueError("Interactivity was %r" % interactivity) | |
2774 |
|
2745 | |||
2775 | exec_count = self.execution_count |
|
2746 | exec_count = self.execution_count | |
2776 |
|
2747 | |||
2777 | try: |
|
2748 | try: | |
2778 | for i, node in enumerate(to_run_exec): |
|
2749 | for i, node in enumerate(to_run_exec): | |
2779 | mod = ast.Module([node]) |
|
2750 | mod = ast.Module([node]) | |
2780 | code = compiler(mod, cell_name, "exec") |
|
2751 | code = compiler(mod, cell_name, "exec") | |
2781 | if self.run_code(code): |
|
2752 | if self.run_code(code): | |
2782 | return True |
|
2753 | return True | |
2783 |
|
2754 | |||
2784 | for i, node in enumerate(to_run_interactive): |
|
2755 | for i, node in enumerate(to_run_interactive): | |
2785 | mod = ast.Interactive([node]) |
|
2756 | mod = ast.Interactive([node]) | |
2786 | code = compiler(mod, cell_name, "single") |
|
2757 | code = compiler(mod, cell_name, "single") | |
2787 | if self.run_code(code): |
|
2758 | if self.run_code(code): | |
2788 | return True |
|
2759 | return True | |
2789 |
|
2760 | |||
2790 | # Flush softspace |
|
2761 | # Flush softspace | |
2791 | if softspace(sys.stdout, 0): |
|
2762 | if softspace(sys.stdout, 0): | |
2792 | print() |
|
2763 | print() | |
2793 |
|
2764 | |||
2794 | except: |
|
2765 | except: | |
2795 | # It's possible to have exceptions raised here, typically by |
|
2766 | # It's possible to have exceptions raised here, typically by | |
2796 | # compilation of odd code (such as a naked 'return' outside a |
|
2767 | # compilation of odd code (such as a naked 'return' outside a | |
2797 | # function) that did parse but isn't valid. Typically the exception |
|
2768 | # function) that did parse but isn't valid. Typically the exception | |
2798 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2769 | # is a SyntaxError, but it's safest just to catch anything and show | |
2799 | # the user a traceback. |
|
2770 | # the user a traceback. | |
2800 |
|
2771 | |||
2801 | # We do only one try/except outside the loop to minimize the impact |
|
2772 | # We do only one try/except outside the loop to minimize the impact | |
2802 | # on runtime, and also because if any node in the node list is |
|
2773 | # on runtime, and also because if any node in the node list is | |
2803 | # broken, we should stop execution completely. |
|
2774 | # broken, we should stop execution completely. | |
2804 | self.showtraceback() |
|
2775 | self.showtraceback() | |
2805 |
|
2776 | |||
2806 | return False |
|
2777 | return False | |
2807 |
|
2778 | |||
2808 | def run_code(self, code_obj): |
|
2779 | def run_code(self, code_obj): | |
2809 | """Execute a code object. |
|
2780 | """Execute a code object. | |
2810 |
|
2781 | |||
2811 | When an exception occurs, self.showtraceback() is called to display a |
|
2782 | When an exception occurs, self.showtraceback() is called to display a | |
2812 | traceback. |
|
2783 | traceback. | |
2813 |
|
2784 | |||
2814 | Parameters |
|
2785 | Parameters | |
2815 | ---------- |
|
2786 | ---------- | |
2816 | code_obj : code object |
|
2787 | code_obj : code object | |
2817 | A compiled code object, to be executed |
|
2788 | A compiled code object, to be executed | |
2818 |
|
2789 | |||
2819 | Returns |
|
2790 | Returns | |
2820 | ------- |
|
2791 | ------- | |
2821 | False : successful execution. |
|
2792 | False : successful execution. | |
2822 | True : an error occurred. |
|
2793 | True : an error occurred. | |
2823 | """ |
|
2794 | """ | |
2824 |
|
2795 | |||
2825 | # Set our own excepthook in case the user code tries to call it |
|
2796 | # Set our own excepthook in case the user code tries to call it | |
2826 | # directly, so that the IPython crash handler doesn't get triggered |
|
2797 | # directly, so that the IPython crash handler doesn't get triggered | |
2827 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2798 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2828 |
|
2799 | |||
2829 | # we save the original sys.excepthook in the instance, in case config |
|
2800 | # we save the original sys.excepthook in the instance, in case config | |
2830 | # code (such as magics) needs access to it. |
|
2801 | # code (such as magics) needs access to it. | |
2831 | self.sys_excepthook = old_excepthook |
|
2802 | self.sys_excepthook = old_excepthook | |
2832 | outflag = 1 # happens in more places, so it's easier as default |
|
2803 | outflag = 1 # happens in more places, so it's easier as default | |
2833 | try: |
|
2804 | try: | |
2834 | try: |
|
2805 | try: | |
2835 | self.hooks.pre_run_code_hook() |
|
2806 | self.hooks.pre_run_code_hook() | |
2836 | #rprint('Running code', repr(code_obj)) # dbg |
|
2807 | #rprint('Running code', repr(code_obj)) # dbg | |
2837 | exec code_obj in self.user_global_ns, self.user_ns |
|
2808 | exec code_obj in self.user_global_ns, self.user_ns | |
2838 | finally: |
|
2809 | finally: | |
2839 | # Reset our crash handler in place |
|
2810 | # Reset our crash handler in place | |
2840 | sys.excepthook = old_excepthook |
|
2811 | sys.excepthook = old_excepthook | |
2841 | except SystemExit: |
|
2812 | except SystemExit: | |
2842 | self.showtraceback(exception_only=True) |
|
2813 | self.showtraceback(exception_only=True) | |
2843 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2814 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) | |
2844 | except self.custom_exceptions: |
|
2815 | except self.custom_exceptions: | |
2845 | etype,value,tb = sys.exc_info() |
|
2816 | etype,value,tb = sys.exc_info() | |
2846 | self.CustomTB(etype,value,tb) |
|
2817 | self.CustomTB(etype,value,tb) | |
2847 | except: |
|
2818 | except: | |
2848 | self.showtraceback() |
|
2819 | self.showtraceback() | |
2849 | else: |
|
2820 | else: | |
2850 | outflag = 0 |
|
2821 | outflag = 0 | |
2851 | return outflag |
|
2822 | return outflag | |
2852 |
|
2823 | |||
2853 | # For backwards compatibility |
|
2824 | # For backwards compatibility | |
2854 | runcode = run_code |
|
2825 | runcode = run_code | |
2855 |
|
2826 | |||
2856 | #------------------------------------------------------------------------- |
|
2827 | #------------------------------------------------------------------------- | |
2857 | # Things related to GUI support and pylab |
|
2828 | # Things related to GUI support and pylab | |
2858 | #------------------------------------------------------------------------- |
|
2829 | #------------------------------------------------------------------------- | |
2859 |
|
2830 | |||
2860 | def enable_gui(self, gui=None): |
|
2831 | def enable_gui(self, gui=None): | |
2861 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2832 | raise NotImplementedError('Implement enable_gui in a subclass') | |
2862 |
|
2833 | |||
2863 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
2834 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): | |
2864 | """Activate pylab support at runtime. |
|
2835 | """Activate pylab support at runtime. | |
2865 |
|
2836 | |||
2866 | This turns on support for matplotlib, preloads into the interactive |
|
2837 | This turns on support for matplotlib, preloads into the interactive | |
2867 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2838 | namespace all of numpy and pylab, and configures IPython to correctly | |
2868 | interact with the GUI event loop. The GUI backend to be used can be |
|
2839 | interact with the GUI event loop. The GUI backend to be used can be | |
2869 | optionally selected with the optional ``gui`` argument. |
|
2840 | optionally selected with the optional ``gui`` argument. | |
2870 |
|
2841 | |||
2871 | Parameters |
|
2842 | Parameters | |
2872 | ---------- |
|
2843 | ---------- | |
2873 | gui : optional, string |
|
2844 | gui : optional, string | |
2874 | If given, dictates the choice of matplotlib GUI backend to use |
|
2845 | If given, dictates the choice of matplotlib GUI backend to use | |
2875 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2846 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2876 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2847 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2877 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2848 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2878 | user's matplotlibrc configuration file). Note that not all backends |
|
2849 | user's matplotlibrc configuration file). Note that not all backends | |
2879 | make sense in all contexts, for example a terminal ipython can't |
|
2850 | make sense in all contexts, for example a terminal ipython can't | |
2880 | display figures inline. |
|
2851 | display figures inline. | |
2881 | """ |
|
2852 | """ | |
2882 | from IPython.core.pylabtools import mpl_runner |
|
2853 | from IPython.core.pylabtools import mpl_runner | |
2883 | # We want to prevent the loading of pylab to pollute the user's |
|
2854 | # We want to prevent the loading of pylab to pollute the user's | |
2884 | # namespace as shown by the %who* magics, so we execute the activation |
|
2855 | # namespace as shown by the %who* magics, so we execute the activation | |
2885 | # code in an empty namespace, and we update *both* user_ns and |
|
2856 | # code in an empty namespace, and we update *both* user_ns and | |
2886 | # user_ns_hidden with this information. |
|
2857 | # user_ns_hidden with this information. | |
2887 | ns = {} |
|
2858 | ns = {} | |
2888 | try: |
|
2859 | try: | |
2889 | gui = pylab_activate(ns, gui, import_all, self, welcome_message=welcome_message) |
|
2860 | gui = pylab_activate(ns, gui, import_all, self, welcome_message=welcome_message) | |
2890 | except KeyError: |
|
2861 | except KeyError: | |
2891 | error("Backend %r not supported" % gui) |
|
2862 | error("Backend %r not supported" % gui) | |
2892 | return |
|
2863 | return | |
2893 | except ImportError: |
|
2864 | except ImportError: | |
2894 | error("pylab mode doesn't work as matplotlib could not be found." + \ |
|
2865 | error("pylab mode doesn't work as matplotlib could not be found." + \ | |
2895 | "\nIs it installed on the system?") |
|
2866 | "\nIs it installed on the system?") | |
2896 | return |
|
2867 | return | |
2897 | self.user_ns.update(ns) |
|
2868 | self.user_ns.update(ns) | |
2898 | self.user_ns_hidden.update(ns) |
|
2869 | self.user_ns_hidden.update(ns) | |
2899 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2870 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
2900 | # plot updates into account |
|
2871 | # plot updates into account | |
2901 | self.enable_gui(gui) |
|
2872 | self.enable_gui(gui) | |
2902 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2873 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ | |
2903 | mpl_runner(self.safe_execfile) |
|
2874 | mpl_runner(self.safe_execfile) | |
2904 |
|
2875 | |||
2905 | #------------------------------------------------------------------------- |
|
2876 | #------------------------------------------------------------------------- | |
2906 | # Utilities |
|
2877 | # Utilities | |
2907 | #------------------------------------------------------------------------- |
|
2878 | #------------------------------------------------------------------------- | |
2908 |
|
2879 | |||
2909 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2880 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): | |
2910 | """Expand python variables in a string. |
|
2881 | """Expand python variables in a string. | |
2911 |
|
2882 | |||
2912 | The depth argument indicates how many frames above the caller should |
|
2883 | The depth argument indicates how many frames above the caller should | |
2913 | be walked to look for the local namespace where to expand variables. |
|
2884 | be walked to look for the local namespace where to expand variables. | |
2914 |
|
2885 | |||
2915 | The global namespace for expansion is always the user's interactive |
|
2886 | The global namespace for expansion is always the user's interactive | |
2916 | namespace. |
|
2887 | namespace. | |
2917 | """ |
|
2888 | """ | |
2918 | ns = self.user_ns.copy() |
|
2889 | ns = self.user_ns.copy() | |
2919 | ns.update(sys._getframe(depth+1).f_locals) |
|
2890 | ns.update(sys._getframe(depth+1).f_locals) | |
2920 | try: |
|
2891 | try: | |
2921 | # We have to use .vformat() here, because 'self' is a valid and common |
|
2892 | # We have to use .vformat() here, because 'self' is a valid and common | |
2922 | # name, and expanding **ns for .format() would make it collide with |
|
2893 | # name, and expanding **ns for .format() would make it collide with | |
2923 | # the 'self' argument of the method. |
|
2894 | # the 'self' argument of the method. | |
2924 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
2895 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) | |
2925 | except Exception: |
|
2896 | except Exception: | |
2926 | # if formatter couldn't format, just let it go untransformed |
|
2897 | # if formatter couldn't format, just let it go untransformed | |
2927 | pass |
|
2898 | pass | |
2928 | return cmd |
|
2899 | return cmd | |
2929 |
|
2900 | |||
2930 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2901 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2931 | """Make a new tempfile and return its filename. |
|
2902 | """Make a new tempfile and return its filename. | |
2932 |
|
2903 | |||
2933 | This makes a call to tempfile.mktemp, but it registers the created |
|
2904 | This makes a call to tempfile.mktemp, but it registers the created | |
2934 | filename internally so ipython cleans it up at exit time. |
|
2905 | filename internally so ipython cleans it up at exit time. | |
2935 |
|
2906 | |||
2936 | Optional inputs: |
|
2907 | Optional inputs: | |
2937 |
|
2908 | |||
2938 | - data(None): if data is given, it gets written out to the temp file |
|
2909 | - data(None): if data is given, it gets written out to the temp file | |
2939 | immediately, and the file is closed again.""" |
|
2910 | immediately, and the file is closed again.""" | |
2940 |
|
2911 | |||
2941 | filename = tempfile.mktemp('.py', prefix) |
|
2912 | filename = tempfile.mktemp('.py', prefix) | |
2942 | self.tempfiles.append(filename) |
|
2913 | self.tempfiles.append(filename) | |
2943 |
|
2914 | |||
2944 | if data: |
|
2915 | if data: | |
2945 | tmp_file = open(filename,'w') |
|
2916 | tmp_file = open(filename,'w') | |
2946 | tmp_file.write(data) |
|
2917 | tmp_file.write(data) | |
2947 | tmp_file.close() |
|
2918 | tmp_file.close() | |
2948 | return filename |
|
2919 | return filename | |
2949 |
|
2920 | |||
2950 | # TODO: This should be removed when Term is refactored. |
|
2921 | # TODO: This should be removed when Term is refactored. | |
2951 | def write(self,data): |
|
2922 | def write(self,data): | |
2952 | """Write a string to the default output""" |
|
2923 | """Write a string to the default output""" | |
2953 | io.stdout.write(data) |
|
2924 | io.stdout.write(data) | |
2954 |
|
2925 | |||
2955 | # TODO: This should be removed when Term is refactored. |
|
2926 | # TODO: This should be removed when Term is refactored. | |
2956 | def write_err(self,data): |
|
2927 | def write_err(self,data): | |
2957 | """Write a string to the default error output""" |
|
2928 | """Write a string to the default error output""" | |
2958 | io.stderr.write(data) |
|
2929 | io.stderr.write(data) | |
2959 |
|
2930 | |||
2960 | def ask_yes_no(self, prompt, default=None): |
|
2931 | def ask_yes_no(self, prompt, default=None): | |
2961 | if self.quiet: |
|
2932 | if self.quiet: | |
2962 | return True |
|
2933 | return True | |
2963 | return ask_yes_no(prompt,default) |
|
2934 | return ask_yes_no(prompt,default) | |
2964 |
|
2935 | |||
2965 | def show_usage(self): |
|
2936 | def show_usage(self): | |
2966 | """Show a usage message""" |
|
2937 | """Show a usage message""" | |
2967 | page.page(IPython.core.usage.interactive_usage) |
|
2938 | page.page(IPython.core.usage.interactive_usage) | |
2968 |
|
2939 | |||
2969 | def extract_input_lines(self, range_str, raw=False): |
|
2940 | def extract_input_lines(self, range_str, raw=False): | |
2970 | """Return as a string a set of input history slices. |
|
2941 | """Return as a string a set of input history slices. | |
2971 |
|
2942 | |||
2972 | Parameters |
|
2943 | Parameters | |
2973 | ---------- |
|
2944 | ---------- | |
2974 | range_str : string |
|
2945 | range_str : string | |
2975 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
2946 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", | |
2976 | since this function is for use by magic functions which get their |
|
2947 | since this function is for use by magic functions which get their | |
2977 | arguments as strings. The number before the / is the session |
|
2948 | arguments as strings. The number before the / is the session | |
2978 | number: ~n goes n back from the current session. |
|
2949 | number: ~n goes n back from the current session. | |
2979 |
|
2950 | |||
2980 | Optional Parameters: |
|
2951 | Optional Parameters: | |
2981 | - raw(False): by default, the processed input is used. If this is |
|
2952 | - raw(False): by default, the processed input is used. If this is | |
2982 | true, the raw input history is used instead. |
|
2953 | true, the raw input history is used instead. | |
2983 |
|
2954 | |||
2984 | Note that slices can be called with two notations: |
|
2955 | Note that slices can be called with two notations: | |
2985 |
|
2956 | |||
2986 | N:M -> standard python form, means including items N...(M-1). |
|
2957 | N:M -> standard python form, means including items N...(M-1). | |
2987 |
|
2958 | |||
2988 | N-M -> include items N..M (closed endpoint).""" |
|
2959 | N-M -> include items N..M (closed endpoint).""" | |
2989 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
2960 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) | |
2990 | return "\n".join(x for _, _, x in lines) |
|
2961 | return "\n".join(x for _, _, x in lines) | |
2991 |
|
2962 | |||
2992 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True): |
|
2963 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True): | |
2993 | """Get a code string from history, file, url, or a string or macro. |
|
2964 | """Get a code string from history, file, url, or a string or macro. | |
2994 |
|
2965 | |||
2995 | This is mainly used by magic functions. |
|
2966 | This is mainly used by magic functions. | |
2996 |
|
2967 | |||
2997 | Parameters |
|
2968 | Parameters | |
2998 | ---------- |
|
2969 | ---------- | |
2999 |
|
2970 | |||
3000 | target : str |
|
2971 | target : str | |
3001 |
|
2972 | |||
3002 | A string specifying code to retrieve. This will be tried respectively |
|
2973 | A string specifying code to retrieve. This will be tried respectively | |
3003 | as: ranges of input history (see %history for syntax), url, |
|
2974 | as: ranges of input history (see %history for syntax), url, | |
3004 | correspnding .py file, filename, or an expression evaluating to a |
|
2975 | correspnding .py file, filename, or an expression evaluating to a | |
3005 | string or Macro in the user namespace. |
|
2976 | string or Macro in the user namespace. | |
3006 |
|
2977 | |||
3007 | raw : bool |
|
2978 | raw : bool | |
3008 | If true (default), retrieve raw history. Has no effect on the other |
|
2979 | If true (default), retrieve raw history. Has no effect on the other | |
3009 | retrieval mechanisms. |
|
2980 | retrieval mechanisms. | |
3010 |
|
2981 | |||
3011 | py_only : bool (default False) |
|
2982 | py_only : bool (default False) | |
3012 | Only try to fetch python code, do not try alternative methods to decode file |
|
2983 | Only try to fetch python code, do not try alternative methods to decode file | |
3013 | if unicode fails. |
|
2984 | if unicode fails. | |
3014 |
|
2985 | |||
3015 | Returns |
|
2986 | Returns | |
3016 | ------- |
|
2987 | ------- | |
3017 | A string of code. |
|
2988 | A string of code. | |
3018 |
|
2989 | |||
3019 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2990 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
3020 | to an object of another type. In each case, .args[0] is a printable |
|
2991 | to an object of another type. In each case, .args[0] is a printable | |
3021 | message. |
|
2992 | message. | |
3022 | """ |
|
2993 | """ | |
3023 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2994 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
3024 | if code: |
|
2995 | if code: | |
3025 | return code |
|
2996 | return code | |
3026 | utarget = unquote_filename(target) |
|
2997 | utarget = unquote_filename(target) | |
3027 | try: |
|
2998 | try: | |
3028 | if utarget.startswith(('http://', 'https://')): |
|
2999 | if utarget.startswith(('http://', 'https://')): | |
3029 | return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie) |
|
3000 | return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie) | |
3030 | except UnicodeDecodeError: |
|
3001 | except UnicodeDecodeError: | |
3031 | if not py_only : |
|
3002 | if not py_only : | |
3032 | from urllib import urlopen # Deferred import |
|
3003 | from urllib import urlopen # Deferred import | |
3033 | response = urlopen(target) |
|
3004 | response = urlopen(target) | |
3034 | return response.read().decode('latin1') |
|
3005 | return response.read().decode('latin1') | |
3035 | raise ValueError(("'%s' seem to be unreadable.") % utarget) |
|
3006 | raise ValueError(("'%s' seem to be unreadable.") % utarget) | |
3036 |
|
3007 | |||
3037 | potential_target = [target] |
|
3008 | potential_target = [target] | |
3038 | try : |
|
3009 | try : | |
3039 | potential_target.insert(0,get_py_filename(target)) |
|
3010 | potential_target.insert(0,get_py_filename(target)) | |
3040 | except IOError: |
|
3011 | except IOError: | |
3041 | pass |
|
3012 | pass | |
3042 |
|
3013 | |||
3043 | for tgt in potential_target : |
|
3014 | for tgt in potential_target : | |
3044 | if os.path.isfile(tgt): # Read file |
|
3015 | if os.path.isfile(tgt): # Read file | |
3045 | try : |
|
3016 | try : | |
3046 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3017 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) | |
3047 | except UnicodeDecodeError : |
|
3018 | except UnicodeDecodeError : | |
3048 | if not py_only : |
|
3019 | if not py_only : | |
3049 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3020 | with io_open(tgt,'r', encoding='latin1') as f : | |
3050 | return f.read() |
|
3021 | return f.read() | |
3051 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3022 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3052 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3023 | elif os.path.isdir(os.path.expanduser(tgt)): | |
3053 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3024 | raise ValueError("'%s' is a directory, not a regular file." % target) | |
3054 |
|
3025 | |||
3055 | try: # User namespace |
|
3026 | try: # User namespace | |
3056 | codeobj = eval(target, self.user_ns) |
|
3027 | codeobj = eval(target, self.user_ns) | |
3057 | except Exception: |
|
3028 | except Exception: | |
3058 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3029 | raise ValueError(("'%s' was not found in history, as a file, url, " | |
3059 | "nor in the user namespace.") % target) |
|
3030 | "nor in the user namespace.") % target) | |
3060 | if isinstance(codeobj, basestring): |
|
3031 | if isinstance(codeobj, basestring): | |
3061 | return codeobj |
|
3032 | return codeobj | |
3062 | elif isinstance(codeobj, Macro): |
|
3033 | elif isinstance(codeobj, Macro): | |
3063 | return codeobj.value |
|
3034 | return codeobj.value | |
3064 |
|
3035 | |||
3065 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3036 | raise TypeError("%s is neither a string nor a macro." % target, | |
3066 | codeobj) |
|
3037 | codeobj) | |
3067 |
|
3038 | |||
3068 | #------------------------------------------------------------------------- |
|
3039 | #------------------------------------------------------------------------- | |
3069 | # Things related to IPython exiting |
|
3040 | # Things related to IPython exiting | |
3070 | #------------------------------------------------------------------------- |
|
3041 | #------------------------------------------------------------------------- | |
3071 | def atexit_operations(self): |
|
3042 | def atexit_operations(self): | |
3072 | """This will be executed at the time of exit. |
|
3043 | """This will be executed at the time of exit. | |
3073 |
|
3044 | |||
3074 | Cleanup operations and saving of persistent data that is done |
|
3045 | Cleanup operations and saving of persistent data that is done | |
3075 | unconditionally by IPython should be performed here. |
|
3046 | unconditionally by IPython should be performed here. | |
3076 |
|
3047 | |||
3077 | For things that may depend on startup flags or platform specifics (such |
|
3048 | For things that may depend on startup flags or platform specifics (such | |
3078 | as having readline or not), register a separate atexit function in the |
|
3049 | as having readline or not), register a separate atexit function in the | |
3079 | code that has the appropriate information, rather than trying to |
|
3050 | code that has the appropriate information, rather than trying to | |
3080 | clutter |
|
3051 | clutter | |
3081 | """ |
|
3052 | """ | |
3082 | # Close the history session (this stores the end time and line count) |
|
3053 | # Close the history session (this stores the end time and line count) | |
3083 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3054 | # this must be *before* the tempfile cleanup, in case of temporary | |
3084 | # history db |
|
3055 | # history db | |
3085 | self.history_manager.end_session() |
|
3056 | self.history_manager.end_session() | |
3086 |
|
3057 | |||
3087 | # Cleanup all tempfiles left around |
|
3058 | # Cleanup all tempfiles left around | |
3088 | for tfile in self.tempfiles: |
|
3059 | for tfile in self.tempfiles: | |
3089 | try: |
|
3060 | try: | |
3090 | os.unlink(tfile) |
|
3061 | os.unlink(tfile) | |
3091 | except OSError: |
|
3062 | except OSError: | |
3092 | pass |
|
3063 | pass | |
3093 |
|
3064 | |||
3094 | # Clear all user namespaces to release all references cleanly. |
|
3065 | # Clear all user namespaces to release all references cleanly. | |
3095 | self.reset(new_session=False) |
|
3066 | self.reset(new_session=False) | |
3096 |
|
3067 | |||
3097 | # Run user hooks |
|
3068 | # Run user hooks | |
3098 | self.hooks.shutdown_hook() |
|
3069 | self.hooks.shutdown_hook() | |
3099 |
|
3070 | |||
3100 | def cleanup(self): |
|
3071 | def cleanup(self): | |
3101 | self.restore_sys_module_state() |
|
3072 | self.restore_sys_module_state() | |
3102 |
|
3073 | |||
3103 |
|
3074 | |||
3104 | class InteractiveShellABC(object): |
|
3075 | class InteractiveShellABC(object): | |
3105 | """An abstract base class for InteractiveShell.""" |
|
3076 | """An abstract base class for InteractiveShell.""" | |
3106 | __metaclass__ = abc.ABCMeta |
|
3077 | __metaclass__ = abc.ABCMeta | |
3107 |
|
3078 | |||
3108 | InteractiveShellABC.register(InteractiveShell) |
|
3079 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,1183 +1,1182 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Implementation of execution-related magic functions. |
|
2 | """Implementation of execution-related magic functions. | |
3 | """ |
|
3 | """ | |
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (c) 2012 The IPython Development Team. |
|
5 | # Copyright (c) 2012 The IPython Development Team. | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the Modified BSD License. |
|
7 | # Distributed under the terms of the Modified BSD License. | |
8 | # |
|
8 | # | |
9 | # The full license is in the file COPYING.txt, distributed with this software. |
|
9 | # The full license is in the file COPYING.txt, distributed with this software. | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Imports |
|
13 | # Imports | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | # Stdlib |
|
16 | # Stdlib | |
17 | import __builtin__ as builtin_mod |
|
17 | import __builtin__ as builtin_mod | |
18 | import ast |
|
18 | import ast | |
19 | import bdb |
|
19 | import bdb | |
20 | import os |
|
20 | import os | |
21 | import sys |
|
21 | import sys | |
22 | import time |
|
22 | import time | |
23 | from StringIO import StringIO |
|
23 | from StringIO import StringIO | |
24 |
|
24 | |||
25 | # cProfile was added in Python2.5 |
|
25 | # cProfile was added in Python2.5 | |
26 | try: |
|
26 | try: | |
27 | import cProfile as profile |
|
27 | import cProfile as profile | |
28 | import pstats |
|
28 | import pstats | |
29 | except ImportError: |
|
29 | except ImportError: | |
30 | # profile isn't bundled by default in Debian for license reasons |
|
30 | # profile isn't bundled by default in Debian for license reasons | |
31 | try: |
|
31 | try: | |
32 | import profile, pstats |
|
32 | import profile, pstats | |
33 | except ImportError: |
|
33 | except ImportError: | |
34 | profile = pstats = None |
|
34 | profile = pstats = None | |
35 |
|
35 | |||
36 | # Our own packages |
|
36 | # Our own packages | |
37 | from IPython.core import debugger, oinspect |
|
37 | from IPython.core import debugger, oinspect | |
38 | from IPython.core import magic_arguments |
|
38 | from IPython.core import magic_arguments | |
39 | from IPython.core import page |
|
39 | from IPython.core import page | |
40 | from IPython.core.error import UsageError |
|
40 | from IPython.core.error import UsageError | |
41 | from IPython.core.macro import Macro |
|
41 | from IPython.core.macro import Macro | |
42 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, |
|
42 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, | |
43 | line_cell_magic, on_off, needs_local_scope) |
|
43 | line_cell_magic, on_off, needs_local_scope) | |
44 | from IPython.testing.skipdoctest import skip_doctest |
|
44 | from IPython.testing.skipdoctest import skip_doctest | |
45 | from IPython.utils import py3compat |
|
45 | from IPython.utils import py3compat | |
46 | from IPython.utils.contexts import preserve_keys |
|
46 | from IPython.utils.contexts import preserve_keys | |
47 | from IPython.utils.io import capture_output |
|
47 | from IPython.utils.io import capture_output | |
48 | from IPython.utils.ipstruct import Struct |
|
48 | from IPython.utils.ipstruct import Struct | |
49 | from IPython.utils.module_paths import find_mod |
|
49 | from IPython.utils.module_paths import find_mod | |
50 | from IPython.utils.path import get_py_filename, unquote_filename, shellglob |
|
50 | from IPython.utils.path import get_py_filename, unquote_filename, shellglob | |
51 | from IPython.utils.timing import clock, clock2 |
|
51 | from IPython.utils.timing import clock, clock2 | |
52 | from IPython.utils.warn import warn, error |
|
52 | from IPython.utils.warn import warn, error | |
53 |
|
53 | |||
54 |
|
54 | |||
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 | # Magic implementation classes |
|
56 | # Magic implementation classes | |
57 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
58 |
|
58 | |||
59 | @magics_class |
|
59 | @magics_class | |
60 | class ExecutionMagics(Magics): |
|
60 | class ExecutionMagics(Magics): | |
61 | """Magics related to code execution, debugging, profiling, etc. |
|
61 | """Magics related to code execution, debugging, profiling, etc. | |
62 |
|
62 | |||
63 | """ |
|
63 | """ | |
64 |
|
64 | |||
65 | def __init__(self, shell): |
|
65 | def __init__(self, shell): | |
66 | super(ExecutionMagics, self).__init__(shell) |
|
66 | super(ExecutionMagics, self).__init__(shell) | |
67 | if profile is None: |
|
67 | if profile is None: | |
68 | self.prun = self.profile_missing_notice |
|
68 | self.prun = self.profile_missing_notice | |
69 | # Default execution function used to actually run user code. |
|
69 | # Default execution function used to actually run user code. | |
70 | self.default_runner = None |
|
70 | self.default_runner = None | |
71 |
|
71 | |||
72 | def profile_missing_notice(self, *args, **kwargs): |
|
72 | def profile_missing_notice(self, *args, **kwargs): | |
73 | error("""\ |
|
73 | error("""\ | |
74 | The profile module could not be found. It has been removed from the standard |
|
74 | The profile module could not be found. It has been removed from the standard | |
75 | python packages because of its non-free license. To use profiling, install the |
|
75 | python packages because of its non-free license. To use profiling, install the | |
76 | python-profiler package from non-free.""") |
|
76 | python-profiler package from non-free.""") | |
77 |
|
77 | |||
78 | @skip_doctest |
|
78 | @skip_doctest | |
79 | @line_cell_magic |
|
79 | @line_cell_magic | |
80 | def prun(self, parameter_s='', cell=None): |
|
80 | def prun(self, parameter_s='', cell=None): | |
81 |
|
81 | |||
82 | """Run a statement through the python code profiler. |
|
82 | """Run a statement through the python code profiler. | |
83 |
|
83 | |||
84 | Usage, in line mode: |
|
84 | Usage, in line mode: | |
85 | %prun [options] statement |
|
85 | %prun [options] statement | |
86 |
|
86 | |||
87 | Usage, in cell mode: |
|
87 | Usage, in cell mode: | |
88 | %%prun [options] [statement] |
|
88 | %%prun [options] [statement] | |
89 | code... |
|
89 | code... | |
90 | code... |
|
90 | code... | |
91 |
|
91 | |||
92 | In cell mode, the additional code lines are appended to the (possibly |
|
92 | In cell mode, the additional code lines are appended to the (possibly | |
93 | empty) statement in the first line. Cell mode allows you to easily |
|
93 | empty) statement in the first line. Cell mode allows you to easily | |
94 | profile multiline blocks without having to put them in a separate |
|
94 | profile multiline blocks without having to put them in a separate | |
95 | function. |
|
95 | function. | |
96 |
|
96 | |||
97 | The given statement (which doesn't require quote marks) is run via the |
|
97 | The given statement (which doesn't require quote marks) is run via the | |
98 | python profiler in a manner similar to the profile.run() function. |
|
98 | python profiler in a manner similar to the profile.run() function. | |
99 | Namespaces are internally managed to work correctly; profile.run |
|
99 | Namespaces are internally managed to work correctly; profile.run | |
100 | cannot be used in IPython because it makes certain assumptions about |
|
100 | cannot be used in IPython because it makes certain assumptions about | |
101 | namespaces which do not hold under IPython. |
|
101 | namespaces which do not hold under IPython. | |
102 |
|
102 | |||
103 | Options: |
|
103 | Options: | |
104 |
|
104 | |||
105 | -l <limit>: you can place restrictions on what or how much of the |
|
105 | -l <limit>: you can place restrictions on what or how much of the | |
106 | profile gets printed. The limit value can be: |
|
106 | profile gets printed. The limit value can be: | |
107 |
|
107 | |||
108 | * A string: only information for function names containing this string |
|
108 | * A string: only information for function names containing this string | |
109 | is printed. |
|
109 | is printed. | |
110 |
|
110 | |||
111 | * An integer: only these many lines are printed. |
|
111 | * An integer: only these many lines are printed. | |
112 |
|
112 | |||
113 | * A float (between 0 and 1): this fraction of the report is printed |
|
113 | * A float (between 0 and 1): this fraction of the report is printed | |
114 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
114 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
115 |
|
115 | |||
116 | You can combine several limits with repeated use of the option. For |
|
116 | You can combine several limits with repeated use of the option. For | |
117 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
117 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
118 | information about class constructors. |
|
118 | information about class constructors. | |
119 |
|
119 | |||
120 | -r: return the pstats.Stats object generated by the profiling. This |
|
120 | -r: return the pstats.Stats object generated by the profiling. This | |
121 | object has all the information about the profile in it, and you can |
|
121 | object has all the information about the profile in it, and you can | |
122 | later use it for further analysis or in other functions. |
|
122 | later use it for further analysis or in other functions. | |
123 |
|
123 | |||
124 | -s <key>: sort profile by given key. You can provide more than one key |
|
124 | -s <key>: sort profile by given key. You can provide more than one key | |
125 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
125 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
126 | default sorting key is 'time'. |
|
126 | default sorting key is 'time'. | |
127 |
|
127 | |||
128 | The following is copied verbatim from the profile documentation |
|
128 | The following is copied verbatim from the profile documentation | |
129 | referenced below: |
|
129 | referenced below: | |
130 |
|
130 | |||
131 | When more than one key is provided, additional keys are used as |
|
131 | When more than one key is provided, additional keys are used as | |
132 | secondary criteria when the there is equality in all keys selected |
|
132 | secondary criteria when the there is equality in all keys selected | |
133 | before them. |
|
133 | before them. | |
134 |
|
134 | |||
135 | Abbreviations can be used for any key names, as long as the |
|
135 | Abbreviations can be used for any key names, as long as the | |
136 | abbreviation is unambiguous. The following are the keys currently |
|
136 | abbreviation is unambiguous. The following are the keys currently | |
137 | defined: |
|
137 | defined: | |
138 |
|
138 | |||
139 | Valid Arg Meaning |
|
139 | Valid Arg Meaning | |
140 | "calls" call count |
|
140 | "calls" call count | |
141 | "cumulative" cumulative time |
|
141 | "cumulative" cumulative time | |
142 | "file" file name |
|
142 | "file" file name | |
143 | "module" file name |
|
143 | "module" file name | |
144 | "pcalls" primitive call count |
|
144 | "pcalls" primitive call count | |
145 | "line" line number |
|
145 | "line" line number | |
146 | "name" function name |
|
146 | "name" function name | |
147 | "nfl" name/file/line |
|
147 | "nfl" name/file/line | |
148 | "stdname" standard name |
|
148 | "stdname" standard name | |
149 | "time" internal time |
|
149 | "time" internal time | |
150 |
|
150 | |||
151 | Note that all sorts on statistics are in descending order (placing |
|
151 | Note that all sorts on statistics are in descending order (placing | |
152 | most time consuming items first), where as name, file, and line number |
|
152 | most time consuming items first), where as name, file, and line number | |
153 | searches are in ascending order (i.e., alphabetical). The subtle |
|
153 | searches are in ascending order (i.e., alphabetical). The subtle | |
154 | distinction between "nfl" and "stdname" is that the standard name is a |
|
154 | distinction between "nfl" and "stdname" is that the standard name is a | |
155 | sort of the name as printed, which means that the embedded line |
|
155 | sort of the name as printed, which means that the embedded line | |
156 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
156 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
157 | would (if the file names were the same) appear in the string order |
|
157 | would (if the file names were the same) appear in the string order | |
158 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
158 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
159 | line numbers. In fact, sort_stats("nfl") is the same as |
|
159 | line numbers. In fact, sort_stats("nfl") is the same as | |
160 | sort_stats("name", "file", "line"). |
|
160 | sort_stats("name", "file", "line"). | |
161 |
|
161 | |||
162 | -T <filename>: save profile results as shown on screen to a text |
|
162 | -T <filename>: save profile results as shown on screen to a text | |
163 | file. The profile is still shown on screen. |
|
163 | file. The profile is still shown on screen. | |
164 |
|
164 | |||
165 | -D <filename>: save (via dump_stats) profile statistics to given |
|
165 | -D <filename>: save (via dump_stats) profile statistics to given | |
166 | filename. This data is in a format understood by the pstats module, and |
|
166 | filename. This data is in a format understood by the pstats module, and | |
167 | is generated by a call to the dump_stats() method of profile |
|
167 | is generated by a call to the dump_stats() method of profile | |
168 | objects. The profile is still shown on screen. |
|
168 | objects. The profile is still shown on screen. | |
169 |
|
169 | |||
170 | -q: suppress output to the pager. Best used with -T and/or -D above. |
|
170 | -q: suppress output to the pager. Best used with -T and/or -D above. | |
171 |
|
171 | |||
172 | If you want to run complete programs under the profiler's control, use |
|
172 | If you want to run complete programs under the profiler's control, use | |
173 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
173 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
174 | contains profiler specific options as described here. |
|
174 | contains profiler specific options as described here. | |
175 |
|
175 | |||
176 | You can read the complete documentation for the profile module with:: |
|
176 | You can read the complete documentation for the profile module with:: | |
177 |
|
177 | |||
178 | In [1]: import profile; profile.help() |
|
178 | In [1]: import profile; profile.help() | |
179 | """ |
|
179 | """ | |
180 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', |
|
180 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', | |
181 | list_all=True, posix=False) |
|
181 | list_all=True, posix=False) | |
182 | if cell is not None: |
|
182 | if cell is not None: | |
183 | arg_str += '\n' + cell |
|
183 | arg_str += '\n' + cell | |
184 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) |
|
184 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) | |
185 |
|
185 | |||
186 | def _run_with_profiler(self, code, opts, namespace): |
|
186 | def _run_with_profiler(self, code, opts, namespace): | |
187 | """ |
|
187 | """ | |
188 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. |
|
188 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. | |
189 |
|
189 | |||
190 | Parameters |
|
190 | Parameters | |
191 | ---------- |
|
191 | ---------- | |
192 | code : str |
|
192 | code : str | |
193 | Code to be executed. |
|
193 | Code to be executed. | |
194 | opts : Struct |
|
194 | opts : Struct | |
195 | Options parsed by `self.parse_options`. |
|
195 | Options parsed by `self.parse_options`. | |
196 | namespace : dict |
|
196 | namespace : dict | |
197 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). |
|
197 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). | |
198 |
|
198 | |||
199 | """ |
|
199 | """ | |
200 |
|
200 | |||
201 | # Fill default values for unspecified options: |
|
201 | # Fill default values for unspecified options: | |
202 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) |
|
202 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) | |
203 |
|
203 | |||
204 | prof = profile.Profile() |
|
204 | prof = profile.Profile() | |
205 | try: |
|
205 | try: | |
206 | prof = prof.runctx(code, namespace, namespace) |
|
206 | prof = prof.runctx(code, namespace, namespace) | |
207 | sys_exit = '' |
|
207 | sys_exit = '' | |
208 | except SystemExit: |
|
208 | except SystemExit: | |
209 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
209 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
210 |
|
210 | |||
211 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
211 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
212 |
|
212 | |||
213 | lims = opts.l |
|
213 | lims = opts.l | |
214 | if lims: |
|
214 | if lims: | |
215 | lims = [] # rebuild lims with ints/floats/strings |
|
215 | lims = [] # rebuild lims with ints/floats/strings | |
216 | for lim in opts.l: |
|
216 | for lim in opts.l: | |
217 | try: |
|
217 | try: | |
218 | lims.append(int(lim)) |
|
218 | lims.append(int(lim)) | |
219 | except ValueError: |
|
219 | except ValueError: | |
220 | try: |
|
220 | try: | |
221 | lims.append(float(lim)) |
|
221 | lims.append(float(lim)) | |
222 | except ValueError: |
|
222 | except ValueError: | |
223 | lims.append(lim) |
|
223 | lims.append(lim) | |
224 |
|
224 | |||
225 | # Trap output. |
|
225 | # Trap output. | |
226 | stdout_trap = StringIO() |
|
226 | stdout_trap = StringIO() | |
227 | stats_stream = stats.stream |
|
227 | stats_stream = stats.stream | |
228 | try: |
|
228 | try: | |
229 | stats.stream = stdout_trap |
|
229 | stats.stream = stdout_trap | |
230 | stats.print_stats(*lims) |
|
230 | stats.print_stats(*lims) | |
231 | finally: |
|
231 | finally: | |
232 | stats.stream = stats_stream |
|
232 | stats.stream = stats_stream | |
233 |
|
233 | |||
234 | output = stdout_trap.getvalue() |
|
234 | output = stdout_trap.getvalue() | |
235 | output = output.rstrip() |
|
235 | output = output.rstrip() | |
236 |
|
236 | |||
237 | if 'q' not in opts: |
|
237 | if 'q' not in opts: | |
238 | page.page(output) |
|
238 | page.page(output) | |
239 | print sys_exit, |
|
239 | print sys_exit, | |
240 |
|
240 | |||
241 | dump_file = opts.D[0] |
|
241 | dump_file = opts.D[0] | |
242 | text_file = opts.T[0] |
|
242 | text_file = opts.T[0] | |
243 | if dump_file: |
|
243 | if dump_file: | |
244 | dump_file = unquote_filename(dump_file) |
|
244 | dump_file = unquote_filename(dump_file) | |
245 | prof.dump_stats(dump_file) |
|
245 | prof.dump_stats(dump_file) | |
246 | print '\n*** Profile stats marshalled to file',\ |
|
246 | print '\n*** Profile stats marshalled to file',\ | |
247 | repr(dump_file)+'.',sys_exit |
|
247 | repr(dump_file)+'.',sys_exit | |
248 | if text_file: |
|
248 | if text_file: | |
249 | text_file = unquote_filename(text_file) |
|
249 | text_file = unquote_filename(text_file) | |
250 | pfile = open(text_file,'w') |
|
250 | pfile = open(text_file,'w') | |
251 | pfile.write(output) |
|
251 | pfile.write(output) | |
252 | pfile.close() |
|
252 | pfile.close() | |
253 | print '\n*** Profile printout saved to text file',\ |
|
253 | print '\n*** Profile printout saved to text file',\ | |
254 | repr(text_file)+'.',sys_exit |
|
254 | repr(text_file)+'.',sys_exit | |
255 |
|
255 | |||
256 | if 'r' in opts: |
|
256 | if 'r' in opts: | |
257 | return stats |
|
257 | return stats | |
258 | else: |
|
258 | else: | |
259 | return None |
|
259 | return None | |
260 |
|
260 | |||
261 | @line_magic |
|
261 | @line_magic | |
262 | def pdb(self, parameter_s=''): |
|
262 | def pdb(self, parameter_s=''): | |
263 | """Control the automatic calling of the pdb interactive debugger. |
|
263 | """Control the automatic calling of the pdb interactive debugger. | |
264 |
|
264 | |||
265 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
265 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
266 | argument it works as a toggle. |
|
266 | argument it works as a toggle. | |
267 |
|
267 | |||
268 | When an exception is triggered, IPython can optionally call the |
|
268 | When an exception is triggered, IPython can optionally call the | |
269 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
269 | interactive pdb debugger after the traceback printout. %pdb toggles | |
270 | this feature on and off. |
|
270 | this feature on and off. | |
271 |
|
271 | |||
272 | The initial state of this feature is set in your configuration |
|
272 | The initial state of this feature is set in your configuration | |
273 | file (the option is ``InteractiveShell.pdb``). |
|
273 | file (the option is ``InteractiveShell.pdb``). | |
274 |
|
274 | |||
275 | If you want to just activate the debugger AFTER an exception has fired, |
|
275 | If you want to just activate the debugger AFTER an exception has fired, | |
276 | without having to type '%pdb on' and rerunning your code, you can use |
|
276 | without having to type '%pdb on' and rerunning your code, you can use | |
277 | the %debug magic.""" |
|
277 | the %debug magic.""" | |
278 |
|
278 | |||
279 | par = parameter_s.strip().lower() |
|
279 | par = parameter_s.strip().lower() | |
280 |
|
280 | |||
281 | if par: |
|
281 | if par: | |
282 | try: |
|
282 | try: | |
283 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
283 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
284 | except KeyError: |
|
284 | except KeyError: | |
285 | print ('Incorrect argument. Use on/1, off/0, ' |
|
285 | print ('Incorrect argument. Use on/1, off/0, ' | |
286 | 'or nothing for a toggle.') |
|
286 | 'or nothing for a toggle.') | |
287 | return |
|
287 | return | |
288 | else: |
|
288 | else: | |
289 | # toggle |
|
289 | # toggle | |
290 | new_pdb = not self.shell.call_pdb |
|
290 | new_pdb = not self.shell.call_pdb | |
291 |
|
291 | |||
292 | # set on the shell |
|
292 | # set on the shell | |
293 | self.shell.call_pdb = new_pdb |
|
293 | self.shell.call_pdb = new_pdb | |
294 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
294 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
295 |
|
295 | |||
296 | @line_magic |
|
296 | @line_magic | |
297 | def debug(self, parameter_s=''): |
|
297 | def debug(self, parameter_s=''): | |
298 | """Activate the interactive debugger in post-mortem mode. |
|
298 | """Activate the interactive debugger in post-mortem mode. | |
299 |
|
299 | |||
300 | If an exception has just occurred, this lets you inspect its stack |
|
300 | If an exception has just occurred, this lets you inspect its stack | |
301 | frames interactively. Note that this will always work only on the last |
|
301 | frames interactively. Note that this will always work only on the last | |
302 | traceback that occurred, so you must call this quickly after an |
|
302 | traceback that occurred, so you must call this quickly after an | |
303 | exception that you wish to inspect has fired, because if another one |
|
303 | exception that you wish to inspect has fired, because if another one | |
304 | occurs, it clobbers the previous one. |
|
304 | occurs, it clobbers the previous one. | |
305 |
|
305 | |||
306 | If you want IPython to automatically do this on every exception, see |
|
306 | If you want IPython to automatically do this on every exception, see | |
307 | the %pdb magic for more details. |
|
307 | the %pdb magic for more details. | |
308 | """ |
|
308 | """ | |
309 | self.shell.debugger(force=True) |
|
309 | self.shell.debugger(force=True) | |
310 |
|
310 | |||
311 | @line_magic |
|
311 | @line_magic | |
312 | def tb(self, s): |
|
312 | def tb(self, s): | |
313 | """Print the last traceback with the currently active exception mode. |
|
313 | """Print the last traceback with the currently active exception mode. | |
314 |
|
314 | |||
315 | See %xmode for changing exception reporting modes.""" |
|
315 | See %xmode for changing exception reporting modes.""" | |
316 | self.shell.showtraceback() |
|
316 | self.shell.showtraceback() | |
317 |
|
317 | |||
318 | @skip_doctest |
|
318 | @skip_doctest | |
319 | @line_magic |
|
319 | @line_magic | |
320 | def run(self, parameter_s='', runner=None, |
|
320 | def run(self, parameter_s='', runner=None, | |
321 | file_finder=get_py_filename): |
|
321 | file_finder=get_py_filename): | |
322 | """Run the named file inside IPython as a program. |
|
322 | """Run the named file inside IPython as a program. | |
323 |
|
323 | |||
324 | Usage: |
|
324 | Usage: | |
325 | %run [-n -i -e -G] |
|
325 | %run [-n -i -e -G] | |
326 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] |
|
326 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] | |
327 | ( -m mod | file ) [args] |
|
327 | ( -m mod | file ) [args] | |
328 |
|
328 | |||
329 | Parameters after the filename are passed as command-line arguments to |
|
329 | Parameters after the filename are passed as command-line arguments to | |
330 | the program (put in sys.argv). Then, control returns to IPython's |
|
330 | the program (put in sys.argv). Then, control returns to IPython's | |
331 | prompt. |
|
331 | prompt. | |
332 |
|
332 | |||
333 | This is similar to running at a system prompt:\\ |
|
333 | This is similar to running at a system prompt:\\ | |
334 | $ python file args\\ |
|
334 | $ python file args\\ | |
335 | but with the advantage of giving you IPython's tracebacks, and of |
|
335 | but with the advantage of giving you IPython's tracebacks, and of | |
336 | loading all variables into your interactive namespace for further use |
|
336 | loading all variables into your interactive namespace for further use | |
337 | (unless -p is used, see below). |
|
337 | (unless -p is used, see below). | |
338 |
|
338 | |||
339 | The file is executed in a namespace initially consisting only of |
|
339 | The file is executed in a namespace initially consisting only of | |
340 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
340 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
341 | sees its environment as if it were being run as a stand-alone program |
|
341 | sees its environment as if it were being run as a stand-alone program | |
342 | (except for sharing global objects such as previously imported |
|
342 | (except for sharing global objects such as previously imported | |
343 | modules). But after execution, the IPython interactive namespace gets |
|
343 | modules). But after execution, the IPython interactive namespace gets | |
344 | updated with all variables defined in the program (except for __name__ |
|
344 | updated with all variables defined in the program (except for __name__ | |
345 | and sys.argv). This allows for very convenient loading of code for |
|
345 | and sys.argv). This allows for very convenient loading of code for | |
346 | interactive work, while giving each program a 'clean sheet' to run in. |
|
346 | interactive work, while giving each program a 'clean sheet' to run in. | |
347 |
|
347 | |||
348 | Arguments are expanded using shell-like glob match. Patterns |
|
348 | Arguments are expanded using shell-like glob match. Patterns | |
349 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, |
|
349 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, | |
350 | tilde '~' will be expanded into user's home directory. Unlike |
|
350 | tilde '~' will be expanded into user's home directory. Unlike | |
351 | real shells, quotation does not suppress expansions. Use |
|
351 | real shells, quotation does not suppress expansions. Use | |
352 | *two* back slashes (e.g., '\\\\*') to suppress expansions. |
|
352 | *two* back slashes (e.g., '\\\\*') to suppress expansions. | |
353 | To completely disable these expansions, you can use -G flag. |
|
353 | To completely disable these expansions, you can use -G flag. | |
354 |
|
354 | |||
355 | Options: |
|
355 | Options: | |
356 |
|
356 | |||
357 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
357 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
358 | without extension (as python does under import). This allows running |
|
358 | without extension (as python does under import). This allows running | |
359 | scripts and reloading the definitions in them without calling code |
|
359 | scripts and reloading the definitions in them without calling code | |
360 | protected by an ' if __name__ == "__main__" ' clause. |
|
360 | protected by an ' if __name__ == "__main__" ' clause. | |
361 |
|
361 | |||
362 | -i: run the file in IPython's namespace instead of an empty one. This |
|
362 | -i: run the file in IPython's namespace instead of an empty one. This | |
363 | is useful if you are experimenting with code written in a text editor |
|
363 | is useful if you are experimenting with code written in a text editor | |
364 | which depends on variables defined interactively. |
|
364 | which depends on variables defined interactively. | |
365 |
|
365 | |||
366 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
366 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
367 | being run. This is particularly useful if IPython is being used to |
|
367 | being run. This is particularly useful if IPython is being used to | |
368 | run unittests, which always exit with a sys.exit() call. In such |
|
368 | run unittests, which always exit with a sys.exit() call. In such | |
369 | cases you are interested in the output of the test results, not in |
|
369 | cases you are interested in the output of the test results, not in | |
370 | seeing a traceback of the unittest module. |
|
370 | seeing a traceback of the unittest module. | |
371 |
|
371 | |||
372 | -t: print timing information at the end of the run. IPython will give |
|
372 | -t: print timing information at the end of the run. IPython will give | |
373 | you an estimated CPU time consumption for your script, which under |
|
373 | you an estimated CPU time consumption for your script, which under | |
374 | Unix uses the resource module to avoid the wraparound problems of |
|
374 | Unix uses the resource module to avoid the wraparound problems of | |
375 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
375 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
376 | is also given (for Windows platforms this is reported as 0.0). |
|
376 | is also given (for Windows platforms this is reported as 0.0). | |
377 |
|
377 | |||
378 | If -t is given, an additional -N<N> option can be given, where <N> |
|
378 | If -t is given, an additional -N<N> option can be given, where <N> | |
379 | must be an integer indicating how many times you want the script to |
|
379 | must be an integer indicating how many times you want the script to | |
380 | run. The final timing report will include total and per run results. |
|
380 | run. The final timing report will include total and per run results. | |
381 |
|
381 | |||
382 | For example (testing the script uniq_stable.py):: |
|
382 | For example (testing the script uniq_stable.py):: | |
383 |
|
383 | |||
384 | In [1]: run -t uniq_stable |
|
384 | In [1]: run -t uniq_stable | |
385 |
|
385 | |||
386 | IPython CPU timings (estimated):\\ |
|
386 | IPython CPU timings (estimated):\\ | |
387 | User : 0.19597 s.\\ |
|
387 | User : 0.19597 s.\\ | |
388 | System: 0.0 s.\\ |
|
388 | System: 0.0 s.\\ | |
389 |
|
389 | |||
390 | In [2]: run -t -N5 uniq_stable |
|
390 | In [2]: run -t -N5 uniq_stable | |
391 |
|
391 | |||
392 | IPython CPU timings (estimated):\\ |
|
392 | IPython CPU timings (estimated):\\ | |
393 | Total runs performed: 5\\ |
|
393 | Total runs performed: 5\\ | |
394 | Times : Total Per run\\ |
|
394 | Times : Total Per run\\ | |
395 | User : 0.910862 s, 0.1821724 s.\\ |
|
395 | User : 0.910862 s, 0.1821724 s.\\ | |
396 | System: 0.0 s, 0.0 s. |
|
396 | System: 0.0 s, 0.0 s. | |
397 |
|
397 | |||
398 | -d: run your program under the control of pdb, the Python debugger. |
|
398 | -d: run your program under the control of pdb, the Python debugger. | |
399 | This allows you to execute your program step by step, watch variables, |
|
399 | This allows you to execute your program step by step, watch variables, | |
400 | etc. Internally, what IPython does is similar to calling: |
|
400 | etc. Internally, what IPython does is similar to calling: | |
401 |
|
401 | |||
402 | pdb.run('execfile("YOURFILENAME")') |
|
402 | pdb.run('execfile("YOURFILENAME")') | |
403 |
|
403 | |||
404 | with a breakpoint set on line 1 of your file. You can change the line |
|
404 | with a breakpoint set on line 1 of your file. You can change the line | |
405 | number for this automatic breakpoint to be <N> by using the -bN option |
|
405 | number for this automatic breakpoint to be <N> by using the -bN option | |
406 | (where N must be an integer). For example:: |
|
406 | (where N must be an integer). For example:: | |
407 |
|
407 | |||
408 | %run -d -b40 myscript |
|
408 | %run -d -b40 myscript | |
409 |
|
409 | |||
410 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
410 | will set the first breakpoint at line 40 in myscript.py. Note that | |
411 | the first breakpoint must be set on a line which actually does |
|
411 | the first breakpoint must be set on a line which actually does | |
412 | something (not a comment or docstring) for it to stop execution. |
|
412 | something (not a comment or docstring) for it to stop execution. | |
413 |
|
413 | |||
414 | Or you can specify a breakpoint in a different file:: |
|
414 | Or you can specify a breakpoint in a different file:: | |
415 |
|
415 | |||
416 | %run -d -b myotherfile.py:20 myscript |
|
416 | %run -d -b myotherfile.py:20 myscript | |
417 |
|
417 | |||
418 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
418 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
419 | first enter 'c' (without quotes) to start execution up to the first |
|
419 | first enter 'c' (without quotes) to start execution up to the first | |
420 | breakpoint. |
|
420 | breakpoint. | |
421 |
|
421 | |||
422 | Entering 'help' gives information about the use of the debugger. You |
|
422 | Entering 'help' gives information about the use of the debugger. You | |
423 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
423 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
424 | at a prompt. |
|
424 | at a prompt. | |
425 |
|
425 | |||
426 | -p: run program under the control of the Python profiler module (which |
|
426 | -p: run program under the control of the Python profiler module (which | |
427 | prints a detailed report of execution times, function calls, etc). |
|
427 | prints a detailed report of execution times, function calls, etc). | |
428 |
|
428 | |||
429 | You can pass other options after -p which affect the behavior of the |
|
429 | You can pass other options after -p which affect the behavior of the | |
430 | profiler itself. See the docs for %prun for details. |
|
430 | profiler itself. See the docs for %prun for details. | |
431 |
|
431 | |||
432 | In this mode, the program's variables do NOT propagate back to the |
|
432 | In this mode, the program's variables do NOT propagate back to the | |
433 | IPython interactive namespace (because they remain in the namespace |
|
433 | IPython interactive namespace (because they remain in the namespace | |
434 | where the profiler executes them). |
|
434 | where the profiler executes them). | |
435 |
|
435 | |||
436 | Internally this triggers a call to %prun, see its documentation for |
|
436 | Internally this triggers a call to %prun, see its documentation for | |
437 | details on the options available specifically for profiling. |
|
437 | details on the options available specifically for profiling. | |
438 |
|
438 | |||
439 | There is one special usage for which the text above doesn't apply: |
|
439 | There is one special usage for which the text above doesn't apply: | |
440 | if the filename ends with .ipy, the file is run as ipython script, |
|
440 | if the filename ends with .ipy, the file is run as ipython script, | |
441 | just as if the commands were written on IPython prompt. |
|
441 | just as if the commands were written on IPython prompt. | |
442 |
|
442 | |||
443 | -m: specify module name to load instead of script path. Similar to |
|
443 | -m: specify module name to load instead of script path. Similar to | |
444 | the -m option for the python interpreter. Use this option last if you |
|
444 | the -m option for the python interpreter. Use this option last if you | |
445 | want to combine with other %run options. Unlike the python interpreter |
|
445 | want to combine with other %run options. Unlike the python interpreter | |
446 | only source modules are allowed no .pyc or .pyo files. |
|
446 | only source modules are allowed no .pyc or .pyo files. | |
447 | For example:: |
|
447 | For example:: | |
448 |
|
448 | |||
449 | %run -m example |
|
449 | %run -m example | |
450 |
|
450 | |||
451 | will run the example module. |
|
451 | will run the example module. | |
452 |
|
452 | |||
453 | -G: disable shell-like glob expansion of arguments. |
|
453 | -G: disable shell-like glob expansion of arguments. | |
454 |
|
454 | |||
455 | """ |
|
455 | """ | |
456 |
|
456 | |||
457 | # get arguments and set sys.argv for program to be run. |
|
457 | # get arguments and set sys.argv for program to be run. | |
458 | opts, arg_lst = self.parse_options(parameter_s, |
|
458 | opts, arg_lst = self.parse_options(parameter_s, | |
459 | 'nidtN:b:pD:l:rs:T:em:G', |
|
459 | 'nidtN:b:pD:l:rs:T:em:G', | |
460 | mode='list', list_all=1) |
|
460 | mode='list', list_all=1) | |
461 | if "m" in opts: |
|
461 | if "m" in opts: | |
462 | modulename = opts["m"][0] |
|
462 | modulename = opts["m"][0] | |
463 | modpath = find_mod(modulename) |
|
463 | modpath = find_mod(modulename) | |
464 | if modpath is None: |
|
464 | if modpath is None: | |
465 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
465 | warn('%r is not a valid modulename on sys.path'%modulename) | |
466 | return |
|
466 | return | |
467 | arg_lst = [modpath] + arg_lst |
|
467 | arg_lst = [modpath] + arg_lst | |
468 | try: |
|
468 | try: | |
469 | filename = file_finder(arg_lst[0]) |
|
469 | filename = file_finder(arg_lst[0]) | |
470 | except IndexError: |
|
470 | except IndexError: | |
471 | warn('you must provide at least a filename.') |
|
471 | warn('you must provide at least a filename.') | |
472 | print '\n%run:\n', oinspect.getdoc(self.run) |
|
472 | print '\n%run:\n', oinspect.getdoc(self.run) | |
473 | return |
|
473 | return | |
474 | except IOError as e: |
|
474 | except IOError as e: | |
475 | try: |
|
475 | try: | |
476 | msg = str(e) |
|
476 | msg = str(e) | |
477 | except UnicodeError: |
|
477 | except UnicodeError: | |
478 | msg = e.message |
|
478 | msg = e.message | |
479 | error(msg) |
|
479 | error(msg) | |
480 | return |
|
480 | return | |
481 |
|
481 | |||
482 | if filename.lower().endswith('.ipy'): |
|
482 | if filename.lower().endswith('.ipy'): | |
483 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
483 | with preserve_keys(self.shell.user_ns, '__file__'): | |
484 | self.shell.user_ns['__file__'] = filename |
|
484 | self.shell.user_ns['__file__'] = filename | |
485 | self.shell.safe_execfile_ipy(filename) |
|
485 | self.shell.safe_execfile_ipy(filename) | |
486 | return |
|
486 | return | |
487 |
|
487 | |||
488 | # Control the response to exit() calls made by the script being run |
|
488 | # Control the response to exit() calls made by the script being run | |
489 | exit_ignore = 'e' in opts |
|
489 | exit_ignore = 'e' in opts | |
490 |
|
490 | |||
491 | # Make sure that the running script gets a proper sys.argv as if it |
|
491 | # Make sure that the running script gets a proper sys.argv as if it | |
492 | # were run from a system shell. |
|
492 | # were run from a system shell. | |
493 | save_argv = sys.argv # save it for later restoring |
|
493 | save_argv = sys.argv # save it for later restoring | |
494 |
|
494 | |||
495 | if 'G' in opts: |
|
495 | if 'G' in opts: | |
496 | args = arg_lst[1:] |
|
496 | args = arg_lst[1:] | |
497 | else: |
|
497 | else: | |
498 | # tilde and glob expansion |
|
498 | # tilde and glob expansion | |
499 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) |
|
499 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) | |
500 |
|
500 | |||
501 | sys.argv = [filename] + args # put in the proper filename |
|
501 | sys.argv = [filename] + args # put in the proper filename | |
502 | # protect sys.argv from potential unicode strings on Python 2: |
|
502 | # protect sys.argv from potential unicode strings on Python 2: | |
503 | if not py3compat.PY3: |
|
503 | if not py3compat.PY3: | |
504 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
504 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] | |
505 |
|
505 | |||
506 | if 'i' in opts: |
|
506 | if 'i' in opts: | |
507 | # Run in user's interactive namespace |
|
507 | # Run in user's interactive namespace | |
508 | prog_ns = self.shell.user_ns |
|
508 | prog_ns = self.shell.user_ns | |
509 | __name__save = self.shell.user_ns['__name__'] |
|
509 | __name__save = self.shell.user_ns['__name__'] | |
510 | prog_ns['__name__'] = '__main__' |
|
510 | prog_ns['__name__'] = '__main__' | |
511 |
main_mod = self.shell. |
|
511 | main_mod = self.shell.user_module | |
512 | else: |
|
512 | else: | |
513 | # Run in a fresh, empty namespace |
|
513 | # Run in a fresh, empty namespace | |
514 | if 'n' in opts: |
|
514 | if 'n' in opts: | |
515 | name = os.path.splitext(os.path.basename(filename))[0] |
|
515 | name = os.path.splitext(os.path.basename(filename))[0] | |
516 | else: |
|
516 | else: | |
517 | name = '__main__' |
|
517 | name = '__main__' | |
518 |
|
518 | |||
519 | main_mod = self.shell.new_main_mod() |
|
519 | # The shell MUST hold a reference to prog_ns so after %run | |
|
520 | # exits, the python deletion mechanism doesn't zero it out | |||
|
521 | # (leaving dangling references). See interactiveshell for details | |||
|
522 | main_mod = self.shell.new_main_mod(filename) | |||
520 | prog_ns = main_mod.__dict__ |
|
523 | prog_ns = main_mod.__dict__ | |
521 | prog_ns['__name__'] = name |
|
524 | prog_ns['__name__'] = name | |
522 |
|
525 | |||
523 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
526 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
524 | # set the __file__ global in the script's namespace |
|
527 | # set the __file__ global in the script's namespace | |
525 | prog_ns['__file__'] = filename |
|
528 | prog_ns['__file__'] = filename | |
526 |
|
529 | |||
527 | # pickle fix. See interactiveshell for an explanation. But we need to |
|
530 | # pickle fix. See interactiveshell for an explanation. But we need to | |
528 | # make sure that, if we overwrite __main__, we replace it at the end |
|
531 | # make sure that, if we overwrite __main__, we replace it at the end | |
529 | main_mod_name = prog_ns['__name__'] |
|
532 | main_mod_name = prog_ns['__name__'] | |
530 |
|
533 | |||
531 | if main_mod_name == '__main__': |
|
534 | if main_mod_name == '__main__': | |
532 | restore_main = sys.modules['__main__'] |
|
535 | restore_main = sys.modules['__main__'] | |
533 | else: |
|
536 | else: | |
534 | restore_main = False |
|
537 | restore_main = False | |
535 |
|
538 | |||
536 | # This needs to be undone at the end to prevent holding references to |
|
539 | # This needs to be undone at the end to prevent holding references to | |
537 | # every single object ever created. |
|
540 | # every single object ever created. | |
538 | sys.modules[main_mod_name] = main_mod |
|
541 | sys.modules[main_mod_name] = main_mod | |
539 |
|
542 | |||
540 | if 'p' in opts or 'd' in opts: |
|
543 | if 'p' in opts or 'd' in opts: | |
541 | if 'm' in opts: |
|
544 | if 'm' in opts: | |
542 | code = 'run_module(modulename, prog_ns)' |
|
545 | code = 'run_module(modulename, prog_ns)' | |
543 | code_ns = { |
|
546 | code_ns = { | |
544 | 'run_module': self.shell.safe_run_module, |
|
547 | 'run_module': self.shell.safe_run_module, | |
545 | 'prog_ns': prog_ns, |
|
548 | 'prog_ns': prog_ns, | |
546 | 'modulename': modulename, |
|
549 | 'modulename': modulename, | |
547 | } |
|
550 | } | |
548 | else: |
|
551 | else: | |
549 | code = 'execfile(filename, prog_ns)' |
|
552 | code = 'execfile(filename, prog_ns)' | |
550 | code_ns = { |
|
553 | code_ns = { | |
551 | 'execfile': self.shell.safe_execfile, |
|
554 | 'execfile': self.shell.safe_execfile, | |
552 | 'prog_ns': prog_ns, |
|
555 | 'prog_ns': prog_ns, | |
553 | 'filename': get_py_filename(filename), |
|
556 | 'filename': get_py_filename(filename), | |
554 | } |
|
557 | } | |
555 |
|
558 | |||
556 | try: |
|
559 | try: | |
557 | stats = None |
|
560 | stats = None | |
558 | with self.shell.readline_no_record: |
|
561 | with self.shell.readline_no_record: | |
559 | if 'p' in opts: |
|
562 | if 'p' in opts: | |
560 | stats = self._run_with_profiler(code, opts, code_ns) |
|
563 | stats = self._run_with_profiler(code, opts, code_ns) | |
561 | else: |
|
564 | else: | |
562 | if 'd' in opts: |
|
565 | if 'd' in opts: | |
563 | self._run_with_debugger( |
|
566 | self._run_with_debugger( | |
564 | code, code_ns, opts.get('b', ['1'])[0], filename) |
|
567 | code, code_ns, opts.get('b', ['1'])[0], filename) | |
565 | else: |
|
568 | else: | |
566 | if 'm' in opts: |
|
569 | if 'm' in opts: | |
567 | def run(): |
|
570 | def run(): | |
568 | self.shell.safe_run_module(modulename, prog_ns) |
|
571 | self.shell.safe_run_module(modulename, prog_ns) | |
569 | else: |
|
572 | else: | |
570 | if runner is None: |
|
573 | if runner is None: | |
571 | runner = self.default_runner |
|
574 | runner = self.default_runner | |
572 | if runner is None: |
|
575 | if runner is None: | |
573 | runner = self.shell.safe_execfile |
|
576 | runner = self.shell.safe_execfile | |
574 |
|
577 | |||
575 | def run(): |
|
578 | def run(): | |
576 | runner(filename, prog_ns, prog_ns, |
|
579 | runner(filename, prog_ns, prog_ns, | |
577 | exit_ignore=exit_ignore) |
|
580 | exit_ignore=exit_ignore) | |
578 |
|
581 | |||
579 | if 't' in opts: |
|
582 | if 't' in opts: | |
580 | # timed execution |
|
583 | # timed execution | |
581 | try: |
|
584 | try: | |
582 | nruns = int(opts['N'][0]) |
|
585 | nruns = int(opts['N'][0]) | |
583 | if nruns < 1: |
|
586 | if nruns < 1: | |
584 | error('Number of runs must be >=1') |
|
587 | error('Number of runs must be >=1') | |
585 | return |
|
588 | return | |
586 | except (KeyError): |
|
589 | except (KeyError): | |
587 | nruns = 1 |
|
590 | nruns = 1 | |
588 | self._run_with_timing(run, nruns) |
|
591 | self._run_with_timing(run, nruns) | |
589 | else: |
|
592 | else: | |
590 | # regular execution |
|
593 | # regular execution | |
591 | run() |
|
594 | run() | |
592 |
|
595 | |||
593 | if 'i' in opts: |
|
596 | if 'i' in opts: | |
594 | self.shell.user_ns['__name__'] = __name__save |
|
597 | self.shell.user_ns['__name__'] = __name__save | |
595 | else: |
|
598 | else: | |
596 | # The shell MUST hold a reference to prog_ns so after %run |
|
|||
597 | # exits, the python deletion mechanism doesn't zero it out |
|
|||
598 | # (leaving dangling references). |
|
|||
599 | self.shell.cache_main_mod(prog_ns, filename) |
|
|||
600 | # update IPython interactive namespace |
|
599 | # update IPython interactive namespace | |
601 |
|
600 | |||
602 | # Some forms of read errors on the file may mean the |
|
601 | # Some forms of read errors on the file may mean the | |
603 | # __name__ key was never set; using pop we don't have to |
|
602 | # __name__ key was never set; using pop we don't have to | |
604 | # worry about a possible KeyError. |
|
603 | # worry about a possible KeyError. | |
605 | prog_ns.pop('__name__', None) |
|
604 | prog_ns.pop('__name__', None) | |
606 |
|
605 | |||
607 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
606 | with preserve_keys(self.shell.user_ns, '__file__'): | |
608 | self.shell.user_ns.update(prog_ns) |
|
607 | self.shell.user_ns.update(prog_ns) | |
609 | finally: |
|
608 | finally: | |
610 | # It's a bit of a mystery why, but __builtins__ can change from |
|
609 | # It's a bit of a mystery why, but __builtins__ can change from | |
611 | # being a module to becoming a dict missing some key data after |
|
610 | # being a module to becoming a dict missing some key data after | |
612 | # %run. As best I can see, this is NOT something IPython is doing |
|
611 | # %run. As best I can see, this is NOT something IPython is doing | |
613 | # at all, and similar problems have been reported before: |
|
612 | # at all, and similar problems have been reported before: | |
614 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
613 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
615 | # Since this seems to be done by the interpreter itself, the best |
|
614 | # Since this seems to be done by the interpreter itself, the best | |
616 | # we can do is to at least restore __builtins__ for the user on |
|
615 | # we can do is to at least restore __builtins__ for the user on | |
617 | # exit. |
|
616 | # exit. | |
618 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
617 | self.shell.user_ns['__builtins__'] = builtin_mod | |
619 |
|
618 | |||
620 | # Ensure key global structures are restored |
|
619 | # Ensure key global structures are restored | |
621 | sys.argv = save_argv |
|
620 | sys.argv = save_argv | |
622 | if restore_main: |
|
621 | if restore_main: | |
623 | sys.modules['__main__'] = restore_main |
|
622 | sys.modules['__main__'] = restore_main | |
624 | else: |
|
623 | else: | |
625 | # Remove from sys.modules the reference to main_mod we'd |
|
624 | # Remove from sys.modules the reference to main_mod we'd | |
626 | # added. Otherwise it will trap references to objects |
|
625 | # added. Otherwise it will trap references to objects | |
627 | # contained therein. |
|
626 | # contained therein. | |
628 | del sys.modules[main_mod_name] |
|
627 | del sys.modules[main_mod_name] | |
629 |
|
628 | |||
630 | return stats |
|
629 | return stats | |
631 |
|
630 | |||
632 | def _run_with_debugger(self, code, code_ns, break_point, filename): |
|
631 | def _run_with_debugger(self, code, code_ns, break_point, filename): | |
633 | """ |
|
632 | """ | |
634 | Run `code` in debugger with a break point. |
|
633 | Run `code` in debugger with a break point. | |
635 |
|
634 | |||
636 | Parameters |
|
635 | Parameters | |
637 | ---------- |
|
636 | ---------- | |
638 | code : str |
|
637 | code : str | |
639 | Code to execute. |
|
638 | Code to execute. | |
640 | code_ns : dict |
|
639 | code_ns : dict | |
641 | A namespace in which `code` is executed. |
|
640 | A namespace in which `code` is executed. | |
642 | break_point : str |
|
641 | break_point : str | |
643 | Line number in the file specified by `filename` argument |
|
642 | Line number in the file specified by `filename` argument | |
644 | or a string in the format ``file:line``. In the latter |
|
643 | or a string in the format ``file:line``. In the latter | |
645 | case, `filename` is ignored. |
|
644 | case, `filename` is ignored. | |
646 | See also :func:`.parse_breakpoint`. |
|
645 | See also :func:`.parse_breakpoint`. | |
647 | filename : str |
|
646 | filename : str | |
648 | Path to the file in which break point is specified. |
|
647 | Path to the file in which break point is specified. | |
649 |
|
648 | |||
650 | Raises |
|
649 | Raises | |
651 | ------ |
|
650 | ------ | |
652 | UsageError |
|
651 | UsageError | |
653 | If no meaningful break point is given by `break_point` and |
|
652 | If no meaningful break point is given by `break_point` and | |
654 | `filename`. |
|
653 | `filename`. | |
655 |
|
654 | |||
656 | """ |
|
655 | """ | |
657 | deb = debugger.Pdb(self.shell.colors) |
|
656 | deb = debugger.Pdb(self.shell.colors) | |
658 | # reset Breakpoint state, which is moronically kept |
|
657 | # reset Breakpoint state, which is moronically kept | |
659 | # in a class |
|
658 | # in a class | |
660 | bdb.Breakpoint.next = 1 |
|
659 | bdb.Breakpoint.next = 1 | |
661 | bdb.Breakpoint.bplist = {} |
|
660 | bdb.Breakpoint.bplist = {} | |
662 | bdb.Breakpoint.bpbynumber = [None] |
|
661 | bdb.Breakpoint.bpbynumber = [None] | |
663 | # Set an initial breakpoint to stop execution |
|
662 | # Set an initial breakpoint to stop execution | |
664 | maxtries = 10 |
|
663 | maxtries = 10 | |
665 | bp_file, bp_line = parse_breakpoint(break_point, filename) |
|
664 | bp_file, bp_line = parse_breakpoint(break_point, filename) | |
666 | checkline = deb.checkline(bp_file, bp_line) |
|
665 | checkline = deb.checkline(bp_file, bp_line) | |
667 | if not checkline: |
|
666 | if not checkline: | |
668 | for bp in range(bp_line + 1, bp_line + maxtries + 1): |
|
667 | for bp in range(bp_line + 1, bp_line + maxtries + 1): | |
669 | if deb.checkline(bp_file, bp): |
|
668 | if deb.checkline(bp_file, bp): | |
670 | break |
|
669 | break | |
671 | else: |
|
670 | else: | |
672 | msg = ("\nI failed to find a valid line to set " |
|
671 | msg = ("\nI failed to find a valid line to set " | |
673 | "a breakpoint\n" |
|
672 | "a breakpoint\n" | |
674 | "after trying up to line: %s.\n" |
|
673 | "after trying up to line: %s.\n" | |
675 | "Please set a valid breakpoint manually " |
|
674 | "Please set a valid breakpoint manually " | |
676 | "with the -b option." % bp) |
|
675 | "with the -b option." % bp) | |
677 | raise UsageError(msg) |
|
676 | raise UsageError(msg) | |
678 | # if we find a good linenumber, set the breakpoint |
|
677 | # if we find a good linenumber, set the breakpoint | |
679 | deb.do_break('%s:%s' % (bp_file, bp_line)) |
|
678 | deb.do_break('%s:%s' % (bp_file, bp_line)) | |
680 |
|
679 | |||
681 | # Mimic Pdb._runscript(...) |
|
680 | # Mimic Pdb._runscript(...) | |
682 | deb._wait_for_mainpyfile = True |
|
681 | deb._wait_for_mainpyfile = True | |
683 | deb.mainpyfile = deb.canonic(filename) |
|
682 | deb.mainpyfile = deb.canonic(filename) | |
684 |
|
683 | |||
685 | # Start file run |
|
684 | # Start file run | |
686 | print "NOTE: Enter 'c' at the", |
|
685 | print "NOTE: Enter 'c' at the", | |
687 | print "%s prompt to start your script." % deb.prompt |
|
686 | print "%s prompt to start your script." % deb.prompt | |
688 | try: |
|
687 | try: | |
689 | #save filename so it can be used by methods on the deb object |
|
688 | #save filename so it can be used by methods on the deb object | |
690 | deb._exec_filename = filename |
|
689 | deb._exec_filename = filename | |
691 | deb.run(code, code_ns) |
|
690 | deb.run(code, code_ns) | |
692 |
|
691 | |||
693 | except: |
|
692 | except: | |
694 | etype, value, tb = sys.exc_info() |
|
693 | etype, value, tb = sys.exc_info() | |
695 | # Skip three frames in the traceback: the %run one, |
|
694 | # Skip three frames in the traceback: the %run one, | |
696 | # one inside bdb.py, and the command-line typed by the |
|
695 | # one inside bdb.py, and the command-line typed by the | |
697 | # user (run by exec in pdb itself). |
|
696 | # user (run by exec in pdb itself). | |
698 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
697 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) | |
699 |
|
698 | |||
700 | @staticmethod |
|
699 | @staticmethod | |
701 | def _run_with_timing(run, nruns): |
|
700 | def _run_with_timing(run, nruns): | |
702 | """ |
|
701 | """ | |
703 | Run function `run` and print timing information. |
|
702 | Run function `run` and print timing information. | |
704 |
|
703 | |||
705 | Parameters |
|
704 | Parameters | |
706 | ---------- |
|
705 | ---------- | |
707 | run : callable |
|
706 | run : callable | |
708 | Any callable object which takes no argument. |
|
707 | Any callable object which takes no argument. | |
709 | nruns : int |
|
708 | nruns : int | |
710 | Number of times to execute `run`. |
|
709 | Number of times to execute `run`. | |
711 |
|
710 | |||
712 | """ |
|
711 | """ | |
713 | twall0 = time.time() |
|
712 | twall0 = time.time() | |
714 | if nruns == 1: |
|
713 | if nruns == 1: | |
715 | t0 = clock2() |
|
714 | t0 = clock2() | |
716 | run() |
|
715 | run() | |
717 | t1 = clock2() |
|
716 | t1 = clock2() | |
718 | t_usr = t1[0] - t0[0] |
|
717 | t_usr = t1[0] - t0[0] | |
719 | t_sys = t1[1] - t0[1] |
|
718 | t_sys = t1[1] - t0[1] | |
720 | print "\nIPython CPU timings (estimated):" |
|
719 | print "\nIPython CPU timings (estimated):" | |
721 | print " User : %10.2f s." % t_usr |
|
720 | print " User : %10.2f s." % t_usr | |
722 | print " System : %10.2f s." % t_sys |
|
721 | print " System : %10.2f s." % t_sys | |
723 | else: |
|
722 | else: | |
724 | runs = range(nruns) |
|
723 | runs = range(nruns) | |
725 | t0 = clock2() |
|
724 | t0 = clock2() | |
726 | for nr in runs: |
|
725 | for nr in runs: | |
727 | run() |
|
726 | run() | |
728 | t1 = clock2() |
|
727 | t1 = clock2() | |
729 | t_usr = t1[0] - t0[0] |
|
728 | t_usr = t1[0] - t0[0] | |
730 | t_sys = t1[1] - t0[1] |
|
729 | t_sys = t1[1] - t0[1] | |
731 | print "\nIPython CPU timings (estimated):" |
|
730 | print "\nIPython CPU timings (estimated):" | |
732 | print "Total runs performed:", nruns |
|
731 | print "Total runs performed:", nruns | |
733 | print " Times : %10s %10s" % ('Total', 'Per run') |
|
732 | print " Times : %10s %10s" % ('Total', 'Per run') | |
734 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) |
|
733 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) | |
735 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) |
|
734 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) | |
736 | twall1 = time.time() |
|
735 | twall1 = time.time() | |
737 | print "Wall time: %10.2f s." % (twall1 - twall0) |
|
736 | print "Wall time: %10.2f s." % (twall1 - twall0) | |
738 |
|
737 | |||
739 | @skip_doctest |
|
738 | @skip_doctest | |
740 | @line_cell_magic |
|
739 | @line_cell_magic | |
741 | def timeit(self, line='', cell=None): |
|
740 | def timeit(self, line='', cell=None): | |
742 | """Time execution of a Python statement or expression |
|
741 | """Time execution of a Python statement or expression | |
743 |
|
742 | |||
744 | Usage, in line mode: |
|
743 | Usage, in line mode: | |
745 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
744 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
746 | or in cell mode: |
|
745 | or in cell mode: | |
747 | %%timeit [-n<N> -r<R> [-t|-c]] setup_code |
|
746 | %%timeit [-n<N> -r<R> [-t|-c]] setup_code | |
748 | code |
|
747 | code | |
749 | code... |
|
748 | code... | |
750 |
|
749 | |||
751 | Time execution of a Python statement or expression using the timeit |
|
750 | Time execution of a Python statement or expression using the timeit | |
752 | module. This function can be used both as a line and cell magic: |
|
751 | module. This function can be used both as a line and cell magic: | |
753 |
|
752 | |||
754 | - In line mode you can time a single-line statement (though multiple |
|
753 | - In line mode you can time a single-line statement (though multiple | |
755 | ones can be chained with using semicolons). |
|
754 | ones can be chained with using semicolons). | |
756 |
|
755 | |||
757 | - In cell mode, the statement in the first line is used as setup code |
|
756 | - In cell mode, the statement in the first line is used as setup code | |
758 | (executed but not timed) and the body of the cell is timed. The cell |
|
757 | (executed but not timed) and the body of the cell is timed. The cell | |
759 | body has access to any variables created in the setup code. |
|
758 | body has access to any variables created in the setup code. | |
760 |
|
759 | |||
761 | Options: |
|
760 | Options: | |
762 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
761 | -n<N>: execute the given statement <N> times in a loop. If this value | |
763 | is not given, a fitting value is chosen. |
|
762 | is not given, a fitting value is chosen. | |
764 |
|
763 | |||
765 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
764 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
766 | Default: 3 |
|
765 | Default: 3 | |
767 |
|
766 | |||
768 | -t: use time.time to measure the time, which is the default on Unix. |
|
767 | -t: use time.time to measure the time, which is the default on Unix. | |
769 | This function measures wall time. |
|
768 | This function measures wall time. | |
770 |
|
769 | |||
771 | -c: use time.clock to measure the time, which is the default on |
|
770 | -c: use time.clock to measure the time, which is the default on | |
772 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
771 | Windows and measures wall time. On Unix, resource.getrusage is used | |
773 | instead and returns the CPU user time. |
|
772 | instead and returns the CPU user time. | |
774 |
|
773 | |||
775 | -p<P>: use a precision of <P> digits to display the timing result. |
|
774 | -p<P>: use a precision of <P> digits to display the timing result. | |
776 | Default: 3 |
|
775 | Default: 3 | |
777 |
|
776 | |||
778 |
|
777 | |||
779 | Examples |
|
778 | Examples | |
780 | -------- |
|
779 | -------- | |
781 | :: |
|
780 | :: | |
782 |
|
781 | |||
783 | In [1]: %timeit pass |
|
782 | In [1]: %timeit pass | |
784 | 10000000 loops, best of 3: 53.3 ns per loop |
|
783 | 10000000 loops, best of 3: 53.3 ns per loop | |
785 |
|
784 | |||
786 | In [2]: u = None |
|
785 | In [2]: u = None | |
787 |
|
786 | |||
788 | In [3]: %timeit u is None |
|
787 | In [3]: %timeit u is None | |
789 | 10000000 loops, best of 3: 184 ns per loop |
|
788 | 10000000 loops, best of 3: 184 ns per loop | |
790 |
|
789 | |||
791 | In [4]: %timeit -r 4 u == None |
|
790 | In [4]: %timeit -r 4 u == None | |
792 | 1000000 loops, best of 4: 242 ns per loop |
|
791 | 1000000 loops, best of 4: 242 ns per loop | |
793 |
|
792 | |||
794 | In [5]: import time |
|
793 | In [5]: import time | |
795 |
|
794 | |||
796 | In [6]: %timeit -n1 time.sleep(2) |
|
795 | In [6]: %timeit -n1 time.sleep(2) | |
797 | 1 loops, best of 3: 2 s per loop |
|
796 | 1 loops, best of 3: 2 s per loop | |
798 |
|
797 | |||
799 |
|
798 | |||
800 | The times reported by %timeit will be slightly higher than those |
|
799 | The times reported by %timeit will be slightly higher than those | |
801 | reported by the timeit.py script when variables are accessed. This is |
|
800 | reported by the timeit.py script when variables are accessed. This is | |
802 | due to the fact that %timeit executes the statement in the namespace |
|
801 | due to the fact that %timeit executes the statement in the namespace | |
803 | of the shell, compared with timeit.py, which uses a single setup |
|
802 | of the shell, compared with timeit.py, which uses a single setup | |
804 | statement to import function or create variables. Generally, the bias |
|
803 | statement to import function or create variables. Generally, the bias | |
805 | does not matter as long as results from timeit.py are not mixed with |
|
804 | does not matter as long as results from timeit.py are not mixed with | |
806 | those from %timeit.""" |
|
805 | those from %timeit.""" | |
807 |
|
806 | |||
808 | import timeit |
|
807 | import timeit | |
809 |
|
808 | |||
810 | opts, stmt = self.parse_options(line,'n:r:tcp:', |
|
809 | opts, stmt = self.parse_options(line,'n:r:tcp:', | |
811 | posix=False, strict=False) |
|
810 | posix=False, strict=False) | |
812 | if stmt == "" and cell is None: |
|
811 | if stmt == "" and cell is None: | |
813 | return |
|
812 | return | |
814 |
|
813 | |||
815 | timefunc = timeit.default_timer |
|
814 | timefunc = timeit.default_timer | |
816 | number = int(getattr(opts, "n", 0)) |
|
815 | number = int(getattr(opts, "n", 0)) | |
817 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
816 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
818 | precision = int(getattr(opts, "p", 3)) |
|
817 | precision = int(getattr(opts, "p", 3)) | |
819 | if hasattr(opts, "t"): |
|
818 | if hasattr(opts, "t"): | |
820 | timefunc = time.time |
|
819 | timefunc = time.time | |
821 | if hasattr(opts, "c"): |
|
820 | if hasattr(opts, "c"): | |
822 | timefunc = clock |
|
821 | timefunc = clock | |
823 |
|
822 | |||
824 | timer = timeit.Timer(timer=timefunc) |
|
823 | timer = timeit.Timer(timer=timefunc) | |
825 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
824 | # this code has tight coupling to the inner workings of timeit.Timer, | |
826 | # but is there a better way to achieve that the code stmt has access |
|
825 | # but is there a better way to achieve that the code stmt has access | |
827 | # to the shell namespace? |
|
826 | # to the shell namespace? | |
828 | transform = self.shell.input_splitter.transform_cell |
|
827 | transform = self.shell.input_splitter.transform_cell | |
829 |
|
828 | |||
830 | if cell is None: |
|
829 | if cell is None: | |
831 | # called as line magic |
|
830 | # called as line magic | |
832 | ast_setup = ast.parse("pass") |
|
831 | ast_setup = ast.parse("pass") | |
833 | ast_stmt = ast.parse(transform(stmt)) |
|
832 | ast_stmt = ast.parse(transform(stmt)) | |
834 | else: |
|
833 | else: | |
835 | ast_setup = ast.parse(transform(stmt)) |
|
834 | ast_setup = ast.parse(transform(stmt)) | |
836 | ast_stmt = ast.parse(transform(cell)) |
|
835 | ast_stmt = ast.parse(transform(cell)) | |
837 |
|
836 | |||
838 | ast_setup = self.shell.transform_ast(ast_setup) |
|
837 | ast_setup = self.shell.transform_ast(ast_setup) | |
839 | ast_stmt = self.shell.transform_ast(ast_stmt) |
|
838 | ast_stmt = self.shell.transform_ast(ast_stmt) | |
840 |
|
839 | |||
841 | # This codestring is taken from timeit.template - we fill it in as an |
|
840 | # This codestring is taken from timeit.template - we fill it in as an | |
842 | # AST, so that we can apply our AST transformations to the user code |
|
841 | # AST, so that we can apply our AST transformations to the user code | |
843 | # without affecting the timing code. |
|
842 | # without affecting the timing code. | |
844 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' |
|
843 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' | |
845 | ' setup\n' |
|
844 | ' setup\n' | |
846 | ' _t0 = _timer()\n' |
|
845 | ' _t0 = _timer()\n' | |
847 | ' for _i in _it:\n' |
|
846 | ' for _i in _it:\n' | |
848 | ' stmt\n' |
|
847 | ' stmt\n' | |
849 | ' _t1 = _timer()\n' |
|
848 | ' _t1 = _timer()\n' | |
850 | ' return _t1 - _t0\n') |
|
849 | ' return _t1 - _t0\n') | |
851 |
|
850 | |||
852 | class TimeitTemplateFiller(ast.NodeTransformer): |
|
851 | class TimeitTemplateFiller(ast.NodeTransformer): | |
853 | "This is quite tightly tied to the template definition above." |
|
852 | "This is quite tightly tied to the template definition above." | |
854 | def visit_FunctionDef(self, node): |
|
853 | def visit_FunctionDef(self, node): | |
855 | "Fill in the setup statement" |
|
854 | "Fill in the setup statement" | |
856 | self.generic_visit(node) |
|
855 | self.generic_visit(node) | |
857 | if node.name == "inner": |
|
856 | if node.name == "inner": | |
858 | node.body[:1] = ast_setup.body |
|
857 | node.body[:1] = ast_setup.body | |
859 |
|
858 | |||
860 | return node |
|
859 | return node | |
861 |
|
860 | |||
862 | def visit_For(self, node): |
|
861 | def visit_For(self, node): | |
863 | "Fill in the statement to be timed" |
|
862 | "Fill in the statement to be timed" | |
864 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': |
|
863 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': | |
865 | node.body = ast_stmt.body |
|
864 | node.body = ast_stmt.body | |
866 | return node |
|
865 | return node | |
867 |
|
866 | |||
868 | timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template) |
|
867 | timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template) | |
869 | timeit_ast = ast.fix_missing_locations(timeit_ast) |
|
868 | timeit_ast = ast.fix_missing_locations(timeit_ast) | |
870 |
|
869 | |||
871 | # Track compilation time so it can be reported if too long |
|
870 | # Track compilation time so it can be reported if too long | |
872 | # Minimum time above which compilation time will be reported |
|
871 | # Minimum time above which compilation time will be reported | |
873 | tc_min = 0.1 |
|
872 | tc_min = 0.1 | |
874 |
|
873 | |||
875 | t0 = clock() |
|
874 | t0 = clock() | |
876 | code = compile(timeit_ast, "<magic-timeit>", "exec") |
|
875 | code = compile(timeit_ast, "<magic-timeit>", "exec") | |
877 | tc = clock()-t0 |
|
876 | tc = clock()-t0 | |
878 |
|
877 | |||
879 | ns = {} |
|
878 | ns = {} | |
880 | exec code in self.shell.user_ns, ns |
|
879 | exec code in self.shell.user_ns, ns | |
881 | timer.inner = ns["inner"] |
|
880 | timer.inner = ns["inner"] | |
882 |
|
881 | |||
883 | if number == 0: |
|
882 | if number == 0: | |
884 | # determine number so that 0.2 <= total time < 2.0 |
|
883 | # determine number so that 0.2 <= total time < 2.0 | |
885 | number = 1 |
|
884 | number = 1 | |
886 | for i in range(1, 10): |
|
885 | for i in range(1, 10): | |
887 | if timer.timeit(number) >= 0.2: |
|
886 | if timer.timeit(number) >= 0.2: | |
888 | break |
|
887 | break | |
889 | number *= 10 |
|
888 | number *= 10 | |
890 |
|
889 | |||
891 | best = min(timer.repeat(repeat, number)) / number |
|
890 | best = min(timer.repeat(repeat, number)) / number | |
892 |
|
891 | |||
893 | print u"%d loops, best of %d: %s per loop" % (number, repeat, |
|
892 | print u"%d loops, best of %d: %s per loop" % (number, repeat, | |
894 | _format_time(best, precision)) |
|
893 | _format_time(best, precision)) | |
895 | if tc > tc_min: |
|
894 | if tc > tc_min: | |
896 | print "Compiler time: %.2f s" % tc |
|
895 | print "Compiler time: %.2f s" % tc | |
897 |
|
896 | |||
898 | @skip_doctest |
|
897 | @skip_doctest | |
899 | @needs_local_scope |
|
898 | @needs_local_scope | |
900 | @line_cell_magic |
|
899 | @line_cell_magic | |
901 | def time(self,line='', cell=None, local_ns=None): |
|
900 | def time(self,line='', cell=None, local_ns=None): | |
902 | """Time execution of a Python statement or expression. |
|
901 | """Time execution of a Python statement or expression. | |
903 |
|
902 | |||
904 | The CPU and wall clock times are printed, and the value of the |
|
903 | The CPU and wall clock times are printed, and the value of the | |
905 | expression (if any) is returned. Note that under Win32, system time |
|
904 | expression (if any) is returned. Note that under Win32, system time | |
906 | is always reported as 0, since it can not be measured. |
|
905 | is always reported as 0, since it can not be measured. | |
907 |
|
906 | |||
908 | This function can be used both as a line and cell magic: |
|
907 | This function can be used both as a line and cell magic: | |
909 |
|
908 | |||
910 | - In line mode you can time a single-line statement (though multiple |
|
909 | - In line mode you can time a single-line statement (though multiple | |
911 | ones can be chained with using semicolons). |
|
910 | ones can be chained with using semicolons). | |
912 |
|
911 | |||
913 | - In cell mode, you can time the cell body (a directly |
|
912 | - In cell mode, you can time the cell body (a directly | |
914 | following statement raises an error). |
|
913 | following statement raises an error). | |
915 |
|
914 | |||
916 | This function provides very basic timing functionality. Use the timeit |
|
915 | This function provides very basic timing functionality. Use the timeit | |
917 | magic for more controll over the measurement. |
|
916 | magic for more controll over the measurement. | |
918 |
|
917 | |||
919 | Examples |
|
918 | Examples | |
920 | -------- |
|
919 | -------- | |
921 | :: |
|
920 | :: | |
922 |
|
921 | |||
923 | In [1]: %time 2**128 |
|
922 | In [1]: %time 2**128 | |
924 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
923 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
925 | Wall time: 0.00 |
|
924 | Wall time: 0.00 | |
926 | Out[1]: 340282366920938463463374607431768211456L |
|
925 | Out[1]: 340282366920938463463374607431768211456L | |
927 |
|
926 | |||
928 | In [2]: n = 1000000 |
|
927 | In [2]: n = 1000000 | |
929 |
|
928 | |||
930 | In [3]: %time sum(range(n)) |
|
929 | In [3]: %time sum(range(n)) | |
931 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
930 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
932 | Wall time: 1.37 |
|
931 | Wall time: 1.37 | |
933 | Out[3]: 499999500000L |
|
932 | Out[3]: 499999500000L | |
934 |
|
933 | |||
935 | In [4]: %time print 'hello world' |
|
934 | In [4]: %time print 'hello world' | |
936 | hello world |
|
935 | hello world | |
937 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
936 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
938 | Wall time: 0.00 |
|
937 | Wall time: 0.00 | |
939 |
|
938 | |||
940 | Note that the time needed by Python to compile the given expression |
|
939 | Note that the time needed by Python to compile the given expression | |
941 | will be reported if it is more than 0.1s. In this example, the |
|
940 | will be reported if it is more than 0.1s. In this example, the | |
942 | actual exponentiation is done by Python at compilation time, so while |
|
941 | actual exponentiation is done by Python at compilation time, so while | |
943 | the expression can take a noticeable amount of time to compute, that |
|
942 | the expression can take a noticeable amount of time to compute, that | |
944 | time is purely due to the compilation: |
|
943 | time is purely due to the compilation: | |
945 |
|
944 | |||
946 | In [5]: %time 3**9999; |
|
945 | In [5]: %time 3**9999; | |
947 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
946 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
948 | Wall time: 0.00 s |
|
947 | Wall time: 0.00 s | |
949 |
|
948 | |||
950 | In [6]: %time 3**999999; |
|
949 | In [6]: %time 3**999999; | |
951 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
950 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
952 | Wall time: 0.00 s |
|
951 | Wall time: 0.00 s | |
953 | Compiler : 0.78 s |
|
952 | Compiler : 0.78 s | |
954 | """ |
|
953 | """ | |
955 |
|
954 | |||
956 | # fail immediately if the given expression can't be compiled |
|
955 | # fail immediately if the given expression can't be compiled | |
957 |
|
956 | |||
958 | if line and cell: |
|
957 | if line and cell: | |
959 | raise UsageError("Can't use statement directly after '%%time'!") |
|
958 | raise UsageError("Can't use statement directly after '%%time'!") | |
960 |
|
959 | |||
961 | if cell: |
|
960 | if cell: | |
962 | expr = self.shell.input_transformer_manager.transform_cell(cell) |
|
961 | expr = self.shell.input_transformer_manager.transform_cell(cell) | |
963 | else: |
|
962 | else: | |
964 | expr = self.shell.input_transformer_manager.transform_cell(line) |
|
963 | expr = self.shell.input_transformer_manager.transform_cell(line) | |
965 |
|
964 | |||
966 | # Minimum time above which parse time will be reported |
|
965 | # Minimum time above which parse time will be reported | |
967 | tp_min = 0.1 |
|
966 | tp_min = 0.1 | |
968 |
|
967 | |||
969 | t0 = clock() |
|
968 | t0 = clock() | |
970 | expr_ast = ast.parse(expr) |
|
969 | expr_ast = ast.parse(expr) | |
971 | tp = clock()-t0 |
|
970 | tp = clock()-t0 | |
972 |
|
971 | |||
973 | # Apply AST transformations |
|
972 | # Apply AST transformations | |
974 | expr_ast = self.shell.transform_ast(expr_ast) |
|
973 | expr_ast = self.shell.transform_ast(expr_ast) | |
975 |
|
974 | |||
976 | # Minimum time above which compilation time will be reported |
|
975 | # Minimum time above which compilation time will be reported | |
977 | tc_min = 0.1 |
|
976 | tc_min = 0.1 | |
978 |
|
977 | |||
979 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): |
|
978 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): | |
980 | mode = 'eval' |
|
979 | mode = 'eval' | |
981 | source = '<timed eval>' |
|
980 | source = '<timed eval>' | |
982 | expr_ast = ast.Expression(expr_ast.body[0].value) |
|
981 | expr_ast = ast.Expression(expr_ast.body[0].value) | |
983 | else: |
|
982 | else: | |
984 | mode = 'exec' |
|
983 | mode = 'exec' | |
985 | source = '<timed exec>' |
|
984 | source = '<timed exec>' | |
986 | t0 = clock() |
|
985 | t0 = clock() | |
987 | code = compile(expr_ast, source, mode) |
|
986 | code = compile(expr_ast, source, mode) | |
988 | tc = clock()-t0 |
|
987 | tc = clock()-t0 | |
989 |
|
988 | |||
990 | # skew measurement as little as possible |
|
989 | # skew measurement as little as possible | |
991 | glob = self.shell.user_ns |
|
990 | glob = self.shell.user_ns | |
992 | wtime = time.time |
|
991 | wtime = time.time | |
993 | # time execution |
|
992 | # time execution | |
994 | wall_st = wtime() |
|
993 | wall_st = wtime() | |
995 | if mode=='eval': |
|
994 | if mode=='eval': | |
996 | st = clock2() |
|
995 | st = clock2() | |
997 | out = eval(code, glob, local_ns) |
|
996 | out = eval(code, glob, local_ns) | |
998 | end = clock2() |
|
997 | end = clock2() | |
999 | else: |
|
998 | else: | |
1000 | st = clock2() |
|
999 | st = clock2() | |
1001 | exec code in glob, local_ns |
|
1000 | exec code in glob, local_ns | |
1002 | end = clock2() |
|
1001 | end = clock2() | |
1003 | out = None |
|
1002 | out = None | |
1004 | wall_end = wtime() |
|
1003 | wall_end = wtime() | |
1005 | # Compute actual times and report |
|
1004 | # Compute actual times and report | |
1006 | wall_time = wall_end-wall_st |
|
1005 | wall_time = wall_end-wall_st | |
1007 | cpu_user = end[0]-st[0] |
|
1006 | cpu_user = end[0]-st[0] | |
1008 | cpu_sys = end[1]-st[1] |
|
1007 | cpu_sys = end[1]-st[1] | |
1009 | cpu_tot = cpu_user+cpu_sys |
|
1008 | cpu_tot = cpu_user+cpu_sys | |
1010 | # On windows cpu_sys is always zero, so no new information to the next print |
|
1009 | # On windows cpu_sys is always zero, so no new information to the next print | |
1011 | if sys.platform != 'win32': |
|
1010 | if sys.platform != 'win32': | |
1012 | print "CPU times: user %s, sys: %s, total: %s" % \ |
|
1011 | print "CPU times: user %s, sys: %s, total: %s" % \ | |
1013 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)) |
|
1012 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)) | |
1014 | print "Wall time: %s" % _format_time(wall_time) |
|
1013 | print "Wall time: %s" % _format_time(wall_time) | |
1015 | if tc > tc_min: |
|
1014 | if tc > tc_min: | |
1016 | print "Compiler : %s" % _format_time(tc) |
|
1015 | print "Compiler : %s" % _format_time(tc) | |
1017 | if tp > tp_min: |
|
1016 | if tp > tp_min: | |
1018 | print "Parser : %s" % _format_time(tp) |
|
1017 | print "Parser : %s" % _format_time(tp) | |
1019 | return out |
|
1018 | return out | |
1020 |
|
1019 | |||
1021 | @skip_doctest |
|
1020 | @skip_doctest | |
1022 | @line_magic |
|
1021 | @line_magic | |
1023 | def macro(self, parameter_s=''): |
|
1022 | def macro(self, parameter_s=''): | |
1024 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1023 | """Define a macro for future re-execution. It accepts ranges of history, | |
1025 | filenames or string objects. |
|
1024 | filenames or string objects. | |
1026 |
|
1025 | |||
1027 | Usage:\\ |
|
1026 | Usage:\\ | |
1028 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1027 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1029 |
|
1028 | |||
1030 | Options: |
|
1029 | Options: | |
1031 |
|
1030 | |||
1032 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1031 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1033 | so that magics are loaded in their transformed version to valid |
|
1032 | so that magics are loaded in their transformed version to valid | |
1034 | Python. If this option is given, the raw input as typed at the |
|
1033 | Python. If this option is given, the raw input as typed at the | |
1035 | command line is used instead. |
|
1034 | command line is used instead. | |
1036 |
|
1035 | |||
1037 | -q: quiet macro definition. By default, a tag line is printed |
|
1036 | -q: quiet macro definition. By default, a tag line is printed | |
1038 | to indicate the macro has been created, and then the contents of |
|
1037 | to indicate the macro has been created, and then the contents of | |
1039 | the macro are printed. If this option is given, then no printout |
|
1038 | the macro are printed. If this option is given, then no printout | |
1040 | is produced once the macro is created. |
|
1039 | is produced once the macro is created. | |
1041 |
|
1040 | |||
1042 | This will define a global variable called `name` which is a string |
|
1041 | This will define a global variable called `name` which is a string | |
1043 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1042 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1044 | above) from your input history into a single string. This variable |
|
1043 | above) from your input history into a single string. This variable | |
1045 | acts like an automatic function which re-executes those lines as if |
|
1044 | acts like an automatic function which re-executes those lines as if | |
1046 | you had typed them. You just type 'name' at the prompt and the code |
|
1045 | you had typed them. You just type 'name' at the prompt and the code | |
1047 | executes. |
|
1046 | executes. | |
1048 |
|
1047 | |||
1049 | The syntax for indicating input ranges is described in %history. |
|
1048 | The syntax for indicating input ranges is described in %history. | |
1050 |
|
1049 | |||
1051 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1050 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1052 | notation, where N:M means numbers N through M-1. |
|
1051 | notation, where N:M means numbers N through M-1. | |
1053 |
|
1052 | |||
1054 | For example, if your history contains (print using %hist -n ):: |
|
1053 | For example, if your history contains (print using %hist -n ):: | |
1055 |
|
1054 | |||
1056 | 44: x=1 |
|
1055 | 44: x=1 | |
1057 | 45: y=3 |
|
1056 | 45: y=3 | |
1058 | 46: z=x+y |
|
1057 | 46: z=x+y | |
1059 | 47: print x |
|
1058 | 47: print x | |
1060 | 48: a=5 |
|
1059 | 48: a=5 | |
1061 | 49: print 'x',x,'y',y |
|
1060 | 49: print 'x',x,'y',y | |
1062 |
|
1061 | |||
1063 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1062 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1064 | called my_macro with:: |
|
1063 | called my_macro with:: | |
1065 |
|
1064 | |||
1066 | In [55]: %macro my_macro 44-47 49 |
|
1065 | In [55]: %macro my_macro 44-47 49 | |
1067 |
|
1066 | |||
1068 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1067 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1069 | in one pass. |
|
1068 | in one pass. | |
1070 |
|
1069 | |||
1071 | You don't need to give the line-numbers in order, and any given line |
|
1070 | You don't need to give the line-numbers in order, and any given line | |
1072 | number can appear multiple times. You can assemble macros with any |
|
1071 | number can appear multiple times. You can assemble macros with any | |
1073 | lines from your input history in any order. |
|
1072 | lines from your input history in any order. | |
1074 |
|
1073 | |||
1075 | The macro is a simple object which holds its value in an attribute, |
|
1074 | The macro is a simple object which holds its value in an attribute, | |
1076 | but IPython's display system checks for macros and executes them as |
|
1075 | but IPython's display system checks for macros and executes them as | |
1077 | code instead of printing them when you type their name. |
|
1076 | code instead of printing them when you type their name. | |
1078 |
|
1077 | |||
1079 | You can view a macro's contents by explicitly printing it with:: |
|
1078 | You can view a macro's contents by explicitly printing it with:: | |
1080 |
|
1079 | |||
1081 | print macro_name |
|
1080 | print macro_name | |
1082 |
|
1081 | |||
1083 | """ |
|
1082 | """ | |
1084 | opts,args = self.parse_options(parameter_s,'rq',mode='list') |
|
1083 | opts,args = self.parse_options(parameter_s,'rq',mode='list') | |
1085 | if not args: # List existing macros |
|
1084 | if not args: # List existing macros | |
1086 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
1085 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
1087 | isinstance(v, Macro)) |
|
1086 | isinstance(v, Macro)) | |
1088 | if len(args) == 1: |
|
1087 | if len(args) == 1: | |
1089 | raise UsageError( |
|
1088 | raise UsageError( | |
1090 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1089 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1091 | name, codefrom = args[0], " ".join(args[1:]) |
|
1090 | name, codefrom = args[0], " ".join(args[1:]) | |
1092 |
|
1091 | |||
1093 | #print 'rng',ranges # dbg |
|
1092 | #print 'rng',ranges # dbg | |
1094 | try: |
|
1093 | try: | |
1095 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
1094 | lines = self.shell.find_user_code(codefrom, 'r' in opts) | |
1096 | except (ValueError, TypeError) as e: |
|
1095 | except (ValueError, TypeError) as e: | |
1097 | print e.args[0] |
|
1096 | print e.args[0] | |
1098 | return |
|
1097 | return | |
1099 | macro = Macro(lines) |
|
1098 | macro = Macro(lines) | |
1100 | self.shell.define_macro(name, macro) |
|
1099 | self.shell.define_macro(name, macro) | |
1101 | if not ( 'q' in opts) : |
|
1100 | if not ( 'q' in opts) : | |
1102 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1101 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1103 | print '=== Macro contents: ===' |
|
1102 | print '=== Macro contents: ===' | |
1104 | print macro, |
|
1103 | print macro, | |
1105 |
|
1104 | |||
1106 | @magic_arguments.magic_arguments() |
|
1105 | @magic_arguments.magic_arguments() | |
1107 | @magic_arguments.argument('output', type=str, default='', nargs='?', |
|
1106 | @magic_arguments.argument('output', type=str, default='', nargs='?', | |
1108 | help="""The name of the variable in which to store output. |
|
1107 | help="""The name of the variable in which to store output. | |
1109 | This is a utils.io.CapturedIO object with stdout/err attributes |
|
1108 | This is a utils.io.CapturedIO object with stdout/err attributes | |
1110 | for the text of the captured output. |
|
1109 | for the text of the captured output. | |
1111 |
|
1110 | |||
1112 | CapturedOutput also has a show() method for displaying the output, |
|
1111 | CapturedOutput also has a show() method for displaying the output, | |
1113 | and __call__ as well, so you can use that to quickly display the |
|
1112 | and __call__ as well, so you can use that to quickly display the | |
1114 | output. |
|
1113 | output. | |
1115 |
|
1114 | |||
1116 | If unspecified, captured output is discarded. |
|
1115 | If unspecified, captured output is discarded. | |
1117 | """ |
|
1116 | """ | |
1118 | ) |
|
1117 | ) | |
1119 | @magic_arguments.argument('--no-stderr', action="store_true", |
|
1118 | @magic_arguments.argument('--no-stderr', action="store_true", | |
1120 | help="""Don't capture stderr.""" |
|
1119 | help="""Don't capture stderr.""" | |
1121 | ) |
|
1120 | ) | |
1122 | @magic_arguments.argument('--no-stdout', action="store_true", |
|
1121 | @magic_arguments.argument('--no-stdout', action="store_true", | |
1123 | help="""Don't capture stdout.""" |
|
1122 | help="""Don't capture stdout.""" | |
1124 | ) |
|
1123 | ) | |
1125 | @cell_magic |
|
1124 | @cell_magic | |
1126 | def capture(self, line, cell): |
|
1125 | def capture(self, line, cell): | |
1127 | """run the cell, capturing stdout/err""" |
|
1126 | """run the cell, capturing stdout/err""" | |
1128 | args = magic_arguments.parse_argstring(self.capture, line) |
|
1127 | args = magic_arguments.parse_argstring(self.capture, line) | |
1129 | out = not args.no_stdout |
|
1128 | out = not args.no_stdout | |
1130 | err = not args.no_stderr |
|
1129 | err = not args.no_stderr | |
1131 | with capture_output(out, err) as io: |
|
1130 | with capture_output(out, err) as io: | |
1132 | self.shell.run_cell(cell) |
|
1131 | self.shell.run_cell(cell) | |
1133 | if args.output: |
|
1132 | if args.output: | |
1134 | self.shell.user_ns[args.output] = io |
|
1133 | self.shell.user_ns[args.output] = io | |
1135 |
|
1134 | |||
1136 | def parse_breakpoint(text, current_file): |
|
1135 | def parse_breakpoint(text, current_file): | |
1137 | '''Returns (file, line) for file:line and (current_file, line) for line''' |
|
1136 | '''Returns (file, line) for file:line and (current_file, line) for line''' | |
1138 | colon = text.find(':') |
|
1137 | colon = text.find(':') | |
1139 | if colon == -1: |
|
1138 | if colon == -1: | |
1140 | return current_file, int(text) |
|
1139 | return current_file, int(text) | |
1141 | else: |
|
1140 | else: | |
1142 | return text[:colon], int(text[colon+1:]) |
|
1141 | return text[:colon], int(text[colon+1:]) | |
1143 |
|
1142 | |||
1144 | def _format_time(timespan, precision=3): |
|
1143 | def _format_time(timespan, precision=3): | |
1145 | """Formats the timespan in a human readable form""" |
|
1144 | """Formats the timespan in a human readable form""" | |
1146 | import math |
|
1145 | import math | |
1147 |
|
1146 | |||
1148 | if timespan >= 60.0: |
|
1147 | if timespan >= 60.0: | |
1149 | # we have more than a minute, format that in a human readable form |
|
1148 | # we have more than a minute, format that in a human readable form | |
1150 | # Idea from http://snipplr.com/view/5713/ |
|
1149 | # Idea from http://snipplr.com/view/5713/ | |
1151 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] |
|
1150 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] | |
1152 | time = [] |
|
1151 | time = [] | |
1153 | leftover = timespan |
|
1152 | leftover = timespan | |
1154 | for suffix, length in parts: |
|
1153 | for suffix, length in parts: | |
1155 | value = int(leftover / length) |
|
1154 | value = int(leftover / length) | |
1156 | if value > 0: |
|
1155 | if value > 0: | |
1157 | leftover = leftover % length |
|
1156 | leftover = leftover % length | |
1158 | time.append(u'%s%s' % (str(value), suffix)) |
|
1157 | time.append(u'%s%s' % (str(value), suffix)) | |
1159 | if leftover < 1: |
|
1158 | if leftover < 1: | |
1160 | break |
|
1159 | break | |
1161 | return " ".join(time) |
|
1160 | return " ".join(time) | |
1162 |
|
1161 | |||
1163 |
|
1162 | |||
1164 | # Unfortunately the unicode 'micro' symbol can cause problems in |
|
1163 | # Unfortunately the unicode 'micro' symbol can cause problems in | |
1165 | # certain terminals. |
|
1164 | # certain terminals. | |
1166 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1165 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1167 | # Try to prevent crashes by being more secure than it needs to |
|
1166 | # Try to prevent crashes by being more secure than it needs to | |
1168 | # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set. |
|
1167 | # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set. | |
1169 | units = [u"s", u"ms",u'us',"ns"] # the save value |
|
1168 | units = [u"s", u"ms",u'us',"ns"] # the save value | |
1170 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
1169 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: | |
1171 | try: |
|
1170 | try: | |
1172 | u'\xb5'.encode(sys.stdout.encoding) |
|
1171 | u'\xb5'.encode(sys.stdout.encoding) | |
1173 | units = [u"s", u"ms",u'\xb5s',"ns"] |
|
1172 | units = [u"s", u"ms",u'\xb5s',"ns"] | |
1174 | except: |
|
1173 | except: | |
1175 | pass |
|
1174 | pass | |
1176 | scaling = [1, 1e3, 1e6, 1e9] |
|
1175 | scaling = [1, 1e3, 1e6, 1e9] | |
1177 |
|
1176 | |||
1178 | if timespan > 0.0: |
|
1177 | if timespan > 0.0: | |
1179 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) |
|
1178 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) | |
1180 | else: |
|
1179 | else: | |
1181 | order = 3 |
|
1180 | order = 3 | |
1182 | ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order]) |
|
1181 | ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order]) | |
1183 | return ret |
|
1182 | return ret |
General Comments 0
You need to be logged in to leave comments.
Login now