Show More
@@ -1,2665 +1,2648 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 with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
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 codeop |
|
25 | import codeop | |
26 | import inspect |
|
26 | import inspect | |
27 | import os |
|
27 | import os | |
28 | import re |
|
28 | import re | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | import types |
|
31 | import types | |
32 | try: |
|
32 | try: | |
33 | from contextlib import nested |
|
33 | from contextlib import nested | |
34 | except: |
|
34 | except: | |
35 | from IPython.utils.nested_context import nested |
|
35 | from IPython.utils.nested_context import nested | |
36 |
|
36 | |||
37 | from IPython.config.configurable import SingletonConfigurable |
|
37 | from IPython.config.configurable import SingletonConfigurable | |
38 | from IPython.core import debugger, oinspect |
|
38 | from IPython.core import debugger, oinspect | |
39 | from IPython.core import history as ipcorehist |
|
39 | from IPython.core import history as ipcorehist | |
40 | from IPython.core import page |
|
40 | from IPython.core import page | |
41 | from IPython.core import prefilter |
|
41 | from IPython.core import prefilter | |
42 | from IPython.core import shadowns |
|
42 | from IPython.core import shadowns | |
43 | from IPython.core import ultratb |
|
43 | from IPython.core import ultratb | |
44 | from IPython.core.alias import AliasManager, AliasError |
|
44 | from IPython.core.alias import AliasManager, AliasError | |
45 | from IPython.core.autocall import ExitAutocall |
|
45 | from IPython.core.autocall import ExitAutocall | |
46 | from IPython.core.builtin_trap import BuiltinTrap |
|
46 | from IPython.core.builtin_trap import BuiltinTrap | |
47 | from IPython.core.compilerop import CachingCompiler |
|
47 | from IPython.core.compilerop import CachingCompiler | |
48 | from IPython.core.display_trap import DisplayTrap |
|
48 | from IPython.core.display_trap import DisplayTrap | |
49 | from IPython.core.displayhook import DisplayHook |
|
49 | from IPython.core.displayhook import DisplayHook | |
50 | from IPython.core.displaypub import DisplayPublisher |
|
50 | from IPython.core.displaypub import DisplayPublisher | |
51 | from IPython.core.error import TryNext, UsageError |
|
51 | from IPython.core.error import TryNext, UsageError | |
52 | from IPython.core.extensions import ExtensionManager |
|
52 | from IPython.core.extensions import ExtensionManager | |
53 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
53 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
54 | from IPython.core.formatters import DisplayFormatter |
|
54 | from IPython.core.formatters import DisplayFormatter | |
55 | from IPython.core.history import HistoryManager |
|
55 | from IPython.core.history import HistoryManager | |
56 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
56 | from IPython.core.inputsplitter import IPythonInputSplitter | |
57 | from IPython.core.logger import Logger |
|
57 | from IPython.core.logger import Logger | |
58 | from IPython.core.macro import Macro |
|
58 | from IPython.core.macro import Macro | |
59 | from IPython.core.magic import Magic |
|
59 | from IPython.core.magic import Magic | |
60 | from IPython.core.payload import PayloadManager |
|
60 | from IPython.core.payload import PayloadManager | |
61 | from IPython.core.plugin import PluginManager |
|
61 | from IPython.core.plugin import PluginManager | |
62 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
62 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
63 | from IPython.core.profiledir import ProfileDir |
|
63 | from IPython.core.profiledir import ProfileDir | |
64 | from IPython.external.Itpl import ItplNS |
|
64 | from IPython.external.Itpl import ItplNS | |
65 | from IPython.utils import PyColorize |
|
65 | from IPython.utils import PyColorize | |
66 | from IPython.utils import io |
|
66 | from IPython.utils import io | |
67 | from IPython.utils import py3compat |
|
67 | from IPython.utils import py3compat | |
68 | from IPython.utils.doctestreload import doctest_reload |
|
68 | from IPython.utils.doctestreload import doctest_reload | |
69 | from IPython.utils.io import ask_yes_no, rprint |
|
69 | from IPython.utils.io import ask_yes_no, rprint | |
70 | from IPython.utils.ipstruct import Struct |
|
70 | from IPython.utils.ipstruct import Struct | |
71 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
71 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
72 | from IPython.utils.pickleshare import PickleShareDB |
|
72 | from IPython.utils.pickleshare import PickleShareDB | |
73 | from IPython.utils.process import system, getoutput |
|
73 | from IPython.utils.process import system, getoutput | |
74 | from IPython.utils.strdispatch import StrDispatch |
|
74 | from IPython.utils.strdispatch import StrDispatch | |
75 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
75 | from IPython.utils.syspathcontext import prepended_to_syspath | |
76 | from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList, |
|
76 | from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList, | |
77 | DollarFormatter) |
|
77 | DollarFormatter) | |
78 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, |
|
78 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, | |
79 | List, Unicode, Instance, Type) |
|
79 | List, Unicode, Instance, Type) | |
80 | from IPython.utils.warn import warn, error, fatal |
|
80 | from IPython.utils.warn import warn, error, fatal | |
81 | import IPython.core.hooks |
|
81 | import IPython.core.hooks | |
82 |
|
82 | |||
83 | #----------------------------------------------------------------------------- |
|
83 | #----------------------------------------------------------------------------- | |
84 | # Globals |
|
84 | # Globals | |
85 | #----------------------------------------------------------------------------- |
|
85 | #----------------------------------------------------------------------------- | |
86 |
|
86 | |||
87 | # compiled regexps for autoindent management |
|
87 | # compiled regexps for autoindent management | |
88 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
88 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
89 |
|
89 | |||
90 | #----------------------------------------------------------------------------- |
|
90 | #----------------------------------------------------------------------------- | |
91 | # Utilities |
|
91 | # Utilities | |
92 | #----------------------------------------------------------------------------- |
|
92 | #----------------------------------------------------------------------------- | |
93 |
|
93 | |||
94 | def softspace(file, newvalue): |
|
94 | def softspace(file, newvalue): | |
95 | """Copied from code.py, to remove the dependency""" |
|
95 | """Copied from code.py, to remove the dependency""" | |
96 |
|
96 | |||
97 | oldvalue = 0 |
|
97 | oldvalue = 0 | |
98 | try: |
|
98 | try: | |
99 | oldvalue = file.softspace |
|
99 | oldvalue = file.softspace | |
100 | except AttributeError: |
|
100 | except AttributeError: | |
101 | pass |
|
101 | pass | |
102 | try: |
|
102 | try: | |
103 | file.softspace = newvalue |
|
103 | file.softspace = newvalue | |
104 | except (AttributeError, TypeError): |
|
104 | except (AttributeError, TypeError): | |
105 | # "attribute-less object" or "read-only attributes" |
|
105 | # "attribute-less object" or "read-only attributes" | |
106 | pass |
|
106 | pass | |
107 | return oldvalue |
|
107 | return oldvalue | |
108 |
|
108 | |||
109 |
|
109 | |||
110 | def no_op(*a, **kw): pass |
|
110 | def no_op(*a, **kw): pass | |
111 |
|
111 | |||
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 | class Bunch: pass |
|
119 | class Bunch: pass | |
120 |
|
120 | |||
121 |
|
121 | |||
122 | def get_default_colors(): |
|
122 | def get_default_colors(): | |
123 | if sys.platform=='darwin': |
|
123 | if sys.platform=='darwin': | |
124 | return "LightBG" |
|
124 | return "LightBG" | |
125 | elif os.name=='nt': |
|
125 | elif os.name=='nt': | |
126 | return 'Linux' |
|
126 | return 'Linux' | |
127 | else: |
|
127 | else: | |
128 | return 'Linux' |
|
128 | return 'Linux' | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | class SeparateUnicode(Unicode): |
|
131 | class SeparateUnicode(Unicode): | |
132 | """A Unicode subclass to validate separate_in, separate_out, etc. |
|
132 | """A Unicode subclass to validate separate_in, separate_out, etc. | |
133 |
|
133 | |||
134 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. |
|
134 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. | |
135 | """ |
|
135 | """ | |
136 |
|
136 | |||
137 | def validate(self, obj, value): |
|
137 | def validate(self, obj, value): | |
138 | if value == '0': value = '' |
|
138 | if value == '0': value = '' | |
139 | value = value.replace('\\n','\n') |
|
139 | value = value.replace('\\n','\n') | |
140 | return super(SeparateUnicode, self).validate(obj, value) |
|
140 | return super(SeparateUnicode, self).validate(obj, value) | |
141 |
|
141 | |||
142 |
|
142 | |||
143 | class ReadlineNoRecord(object): |
|
143 | class ReadlineNoRecord(object): | |
144 | """Context manager to execute some code, then reload readline history |
|
144 | """Context manager to execute some code, then reload readline history | |
145 | so that interactive input to the code doesn't appear when pressing up.""" |
|
145 | so that interactive input to the code doesn't appear when pressing up.""" | |
146 | def __init__(self, shell): |
|
146 | def __init__(self, shell): | |
147 | self.shell = shell |
|
147 | self.shell = shell | |
148 | self._nested_level = 0 |
|
148 | self._nested_level = 0 | |
149 |
|
149 | |||
150 | def __enter__(self): |
|
150 | def __enter__(self): | |
151 | if self._nested_level == 0: |
|
151 | if self._nested_level == 0: | |
152 | try: |
|
152 | try: | |
153 | self.orig_length = self.current_length() |
|
153 | self.orig_length = self.current_length() | |
154 | self.readline_tail = self.get_readline_tail() |
|
154 | self.readline_tail = self.get_readline_tail() | |
155 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
155 | except (AttributeError, IndexError): # Can fail with pyreadline | |
156 | self.orig_length, self.readline_tail = 999999, [] |
|
156 | self.orig_length, self.readline_tail = 999999, [] | |
157 | self._nested_level += 1 |
|
157 | self._nested_level += 1 | |
158 |
|
158 | |||
159 | def __exit__(self, type, value, traceback): |
|
159 | def __exit__(self, type, value, traceback): | |
160 | self._nested_level -= 1 |
|
160 | self._nested_level -= 1 | |
161 | if self._nested_level == 0: |
|
161 | if self._nested_level == 0: | |
162 | # Try clipping the end if it's got longer |
|
162 | # Try clipping the end if it's got longer | |
163 | try: |
|
163 | try: | |
164 | e = self.current_length() - self.orig_length |
|
164 | e = self.current_length() - self.orig_length | |
165 | if e > 0: |
|
165 | if e > 0: | |
166 | for _ in range(e): |
|
166 | for _ in range(e): | |
167 | self.shell.readline.remove_history_item(self.orig_length) |
|
167 | self.shell.readline.remove_history_item(self.orig_length) | |
168 |
|
168 | |||
169 | # If it still doesn't match, just reload readline history. |
|
169 | # If it still doesn't match, just reload readline history. | |
170 | if self.current_length() != self.orig_length \ |
|
170 | if self.current_length() != self.orig_length \ | |
171 | or self.get_readline_tail() != self.readline_tail: |
|
171 | or self.get_readline_tail() != self.readline_tail: | |
172 | self.shell.refill_readline_hist() |
|
172 | self.shell.refill_readline_hist() | |
173 | except (AttributeError, IndexError): |
|
173 | except (AttributeError, IndexError): | |
174 | pass |
|
174 | pass | |
175 | # Returning False will cause exceptions to propagate |
|
175 | # Returning False will cause exceptions to propagate | |
176 | return False |
|
176 | return False | |
177 |
|
177 | |||
178 | def current_length(self): |
|
178 | def current_length(self): | |
179 | return self.shell.readline.get_current_history_length() |
|
179 | return self.shell.readline.get_current_history_length() | |
180 |
|
180 | |||
181 | def get_readline_tail(self, n=10): |
|
181 | def get_readline_tail(self, n=10): | |
182 | """Get the last n items in readline history.""" |
|
182 | """Get the last n items in readline history.""" | |
183 | end = self.shell.readline.get_current_history_length() + 1 |
|
183 | end = self.shell.readline.get_current_history_length() + 1 | |
184 | start = max(end-n, 1) |
|
184 | start = max(end-n, 1) | |
185 | ghi = self.shell.readline.get_history_item |
|
185 | ghi = self.shell.readline.get_history_item | |
186 | return [ghi(x) for x in range(start, end)] |
|
186 | return [ghi(x) for x in range(start, end)] | |
187 |
|
187 | |||
188 |
|
188 | |||
189 | _autocall_help = """ |
|
189 | _autocall_help = """ | |
190 | Make IPython automatically call any callable object even if |
|
190 | Make IPython automatically call any callable object even if | |
191 | you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
191 | you didn't type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
192 | automatically. The value can be '0' to disable the feature, '1' for 'smart' |
|
192 | automatically. The value can be '0' to disable the feature, '1' for 'smart' | |
193 | autocall, where it is not applied if there are no more arguments on the line, |
|
193 | autocall, where it is not applied if there are no more arguments on the line, | |
194 | and '2' for 'full' autocall, where all callable objects are automatically |
|
194 | and '2' for 'full' autocall, where all callable objects are automatically | |
195 | called (even if no arguments are present). The default is '1'. |
|
195 | called (even if no arguments are present). The default is '1'. | |
196 | """ |
|
196 | """ | |
197 |
|
197 | |||
198 | #----------------------------------------------------------------------------- |
|
198 | #----------------------------------------------------------------------------- | |
199 | # Main IPython class |
|
199 | # Main IPython class | |
200 | #----------------------------------------------------------------------------- |
|
200 | #----------------------------------------------------------------------------- | |
201 |
|
201 | |||
202 | class InteractiveShell(SingletonConfigurable, Magic): |
|
202 | class InteractiveShell(SingletonConfigurable, Magic): | |
203 | """An enhanced, interactive shell for Python.""" |
|
203 | """An enhanced, interactive shell for Python.""" | |
204 |
|
204 | |||
205 | _instance = None |
|
205 | _instance = None | |
206 |
|
206 | |||
207 | autocall = Enum((0,1,2), default_value=1, config=True, help= |
|
207 | autocall = Enum((0,1,2), default_value=1, config=True, help= | |
208 | """ |
|
208 | """ | |
209 | Make IPython automatically call any callable object even if you didn't |
|
209 | Make IPython automatically call any callable object even if you didn't | |
210 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
210 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
211 | automatically. The value can be '0' to disable the feature, '1' for |
|
211 | automatically. The value can be '0' to disable the feature, '1' for | |
212 | 'smart' autocall, where it is not applied if there are no more |
|
212 | 'smart' autocall, where it is not applied if there are no more | |
213 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
213 | arguments on the line, and '2' for 'full' autocall, where all callable | |
214 | objects are automatically called (even if no arguments are present). |
|
214 | objects are automatically called (even if no arguments are present). | |
215 | The default is '1'. |
|
215 | The default is '1'. | |
216 | """ |
|
216 | """ | |
217 | ) |
|
217 | ) | |
218 | # TODO: remove all autoindent logic and put into frontends. |
|
218 | # TODO: remove all autoindent logic and put into frontends. | |
219 | # We can't do this yet because even runlines uses the autoindent. |
|
219 | # We can't do this yet because even runlines uses the autoindent. | |
220 | autoindent = CBool(True, config=True, help= |
|
220 | autoindent = CBool(True, config=True, help= | |
221 | """ |
|
221 | """ | |
222 | Autoindent IPython code entered interactively. |
|
222 | Autoindent IPython code entered interactively. | |
223 | """ |
|
223 | """ | |
224 | ) |
|
224 | ) | |
225 | automagic = CBool(True, config=True, help= |
|
225 | automagic = CBool(True, config=True, help= | |
226 | """ |
|
226 | """ | |
227 | Enable magic commands to be called without the leading %. |
|
227 | Enable magic commands to be called without the leading %. | |
228 | """ |
|
228 | """ | |
229 | ) |
|
229 | ) | |
230 | cache_size = Integer(1000, config=True, help= |
|
230 | cache_size = Integer(1000, config=True, help= | |
231 | """ |
|
231 | """ | |
232 | Set the size of the output cache. The default is 1000, you can |
|
232 | Set the size of the output cache. The default is 1000, you can | |
233 | change it permanently in your config file. Setting it to 0 completely |
|
233 | change it permanently in your config file. Setting it to 0 completely | |
234 | disables the caching system, and the minimum value accepted is 20 (if |
|
234 | disables the caching system, and the minimum value accepted is 20 (if | |
235 | you provide a value less than 20, it is reset to 0 and a warning is |
|
235 | you provide a value less than 20, it is reset to 0 and a warning is | |
236 | issued). This limit is defined because otherwise you'll spend more |
|
236 | issued). This limit is defined because otherwise you'll spend more | |
237 | time re-flushing a too small cache than working |
|
237 | time re-flushing a too small cache than working | |
238 | """ |
|
238 | """ | |
239 | ) |
|
239 | ) | |
240 | color_info = CBool(True, config=True, help= |
|
240 | color_info = CBool(True, config=True, help= | |
241 | """ |
|
241 | """ | |
242 | Use colors for displaying information about objects. Because this |
|
242 | Use colors for displaying information about objects. Because this | |
243 | information is passed through a pager (like 'less'), and some pagers |
|
243 | information is passed through a pager (like 'less'), and some pagers | |
244 | get confused with color codes, this capability can be turned off. |
|
244 | get confused with color codes, this capability can be turned off. | |
245 | """ |
|
245 | """ | |
246 | ) |
|
246 | ) | |
247 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
247 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
248 | default_value=get_default_colors(), config=True, |
|
248 | default_value=get_default_colors(), config=True, | |
249 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
249 | help="Set the color scheme (NoColor, Linux, or LightBG)." | |
250 | ) |
|
250 | ) | |
251 | colors_force = CBool(False, help= |
|
251 | colors_force = CBool(False, help= | |
252 | """ |
|
252 | """ | |
253 | Force use of ANSI color codes, regardless of OS and readline |
|
253 | Force use of ANSI color codes, regardless of OS and readline | |
254 | availability. |
|
254 | availability. | |
255 | """ |
|
255 | """ | |
256 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
256 | # FIXME: This is essentially a hack to allow ZMQShell to show colors | |
257 | # without readline on Win32. When the ZMQ formatting system is |
|
257 | # without readline on Win32. When the ZMQ formatting system is | |
258 | # refactored, this should be removed. |
|
258 | # refactored, this should be removed. | |
259 | ) |
|
259 | ) | |
260 | debug = CBool(False, config=True) |
|
260 | debug = CBool(False, config=True) | |
261 | deep_reload = CBool(False, config=True, help= |
|
261 | deep_reload = CBool(False, config=True, help= | |
262 | """ |
|
262 | """ | |
263 | Enable deep (recursive) reloading by default. IPython can use the |
|
263 | Enable deep (recursive) reloading by default. IPython can use the | |
264 | deep_reload module which reloads changes in modules recursively (it |
|
264 | deep_reload module which reloads changes in modules recursively (it | |
265 | replaces the reload() function, so you don't need to change anything to |
|
265 | replaces the reload() function, so you don't need to change anything to | |
266 | use it). deep_reload() forces a full reload of modules whose code may |
|
266 | use it). deep_reload() forces a full reload of modules whose code may | |
267 | have changed, which the default reload() function does not. When |
|
267 | have changed, which the default reload() function does not. When | |
268 | deep_reload is off, IPython will use the normal reload(), but |
|
268 | deep_reload is off, IPython will use the normal reload(), but | |
269 | deep_reload will still be available as dreload(). |
|
269 | deep_reload will still be available as dreload(). | |
270 | """ |
|
270 | """ | |
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 |
|
275 | |||
276 | exit_now = CBool(False) |
|
276 | exit_now = CBool(False) | |
277 | exiter = Instance(ExitAutocall) |
|
277 | exiter = Instance(ExitAutocall) | |
278 | def _exiter_default(self): |
|
278 | def _exiter_default(self): | |
279 | return ExitAutocall(self) |
|
279 | return ExitAutocall(self) | |
280 | # Monotonically increasing execution counter |
|
280 | # Monotonically increasing execution counter | |
281 | execution_count = Integer(1) |
|
281 | execution_count = Integer(1) | |
282 | filename = Unicode("<ipython console>") |
|
282 | filename = Unicode("<ipython console>") | |
283 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
283 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
284 |
|
284 | |||
285 | # Input splitter, to split entire cells of input into either individual |
|
285 | # Input splitter, to split entire cells of input into either individual | |
286 | # interactive statements or whole blocks. |
|
286 | # interactive statements or whole blocks. | |
287 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
287 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
288 | (), {}) |
|
288 | (), {}) | |
289 | logstart = CBool(False, config=True, help= |
|
289 | logstart = CBool(False, config=True, help= | |
290 | """ |
|
290 | """ | |
291 | Start logging to the default log file. |
|
291 | Start logging to the default log file. | |
292 | """ |
|
292 | """ | |
293 | ) |
|
293 | ) | |
294 | logfile = Unicode('', config=True, help= |
|
294 | logfile = Unicode('', config=True, help= | |
295 | """ |
|
295 | """ | |
296 | The name of the logfile to use. |
|
296 | The name of the logfile to use. | |
297 | """ |
|
297 | """ | |
298 | ) |
|
298 | ) | |
299 | logappend = Unicode('', config=True, help= |
|
299 | logappend = Unicode('', config=True, help= | |
300 | """ |
|
300 | """ | |
301 | Start logging to the given file in append mode. |
|
301 | Start logging to the given file in append mode. | |
302 | """ |
|
302 | """ | |
303 | ) |
|
303 | ) | |
304 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
304 | object_info_string_level = Enum((0,1,2), default_value=0, | |
305 | config=True) |
|
305 | config=True) | |
306 | pdb = CBool(False, config=True, help= |
|
306 | pdb = CBool(False, config=True, help= | |
307 | """ |
|
307 | """ | |
308 | Automatically call the pdb debugger after every exception. |
|
308 | Automatically call the pdb debugger after every exception. | |
309 | """ |
|
309 | """ | |
310 | ) |
|
310 | ) | |
311 | multiline_history = CBool(sys.platform != 'win32', config=True, |
|
311 | multiline_history = CBool(sys.platform != 'win32', config=True, | |
312 | help="Save multi-line entries as one entry in readline history" |
|
312 | help="Save multi-line entries as one entry in readline history" | |
313 | ) |
|
313 | ) | |
314 |
|
314 | |||
315 | prompt_in1 = Unicode('In [\\#]: ', config=True) |
|
315 | prompt_in1 = Unicode('In [\\#]: ', config=True) | |
316 | prompt_in2 = Unicode(' .\\D.: ', config=True) |
|
316 | prompt_in2 = Unicode(' .\\D.: ', config=True) | |
317 | prompt_out = Unicode('Out[\\#]: ', config=True) |
|
317 | prompt_out = Unicode('Out[\\#]: ', config=True) | |
318 | prompts_pad_left = CBool(True, config=True) |
|
318 | prompts_pad_left = CBool(True, config=True) | |
319 | quiet = CBool(False, config=True) |
|
319 | quiet = CBool(False, config=True) | |
320 |
|
320 | |||
321 | history_length = Integer(10000, config=True) |
|
321 | history_length = Integer(10000, config=True) | |
322 |
|
322 | |||
323 | # The readline stuff will eventually be moved to the terminal subclass |
|
323 | # The readline stuff will eventually be moved to the terminal subclass | |
324 | # but for now, we can't do that as readline is welded in everywhere. |
|
324 | # but for now, we can't do that as readline is welded in everywhere. | |
325 | readline_use = CBool(True, config=True) |
|
325 | readline_use = CBool(True, config=True) | |
326 | readline_remove_delims = Unicode('-/~', config=True) |
|
326 | readline_remove_delims = Unicode('-/~', config=True) | |
327 | # don't use \M- bindings by default, because they |
|
327 | # don't use \M- bindings by default, because they | |
328 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
328 | # conflict with 8-bit encodings. See gh-58,gh-88 | |
329 | readline_parse_and_bind = List([ |
|
329 | readline_parse_and_bind = List([ | |
330 | 'tab: complete', |
|
330 | 'tab: complete', | |
331 | '"\C-l": clear-screen', |
|
331 | '"\C-l": clear-screen', | |
332 | 'set show-all-if-ambiguous on', |
|
332 | 'set show-all-if-ambiguous on', | |
333 | '"\C-o": tab-insert', |
|
333 | '"\C-o": tab-insert', | |
334 | '"\C-r": reverse-search-history', |
|
334 | '"\C-r": reverse-search-history', | |
335 | '"\C-s": forward-search-history', |
|
335 | '"\C-s": forward-search-history', | |
336 | '"\C-p": history-search-backward', |
|
336 | '"\C-p": history-search-backward', | |
337 | '"\C-n": history-search-forward', |
|
337 | '"\C-n": history-search-forward', | |
338 | '"\e[A": history-search-backward', |
|
338 | '"\e[A": history-search-backward', | |
339 | '"\e[B": history-search-forward', |
|
339 | '"\e[B": history-search-forward', | |
340 | '"\C-k": kill-line', |
|
340 | '"\C-k": kill-line', | |
341 | '"\C-u": unix-line-discard', |
|
341 | '"\C-u": unix-line-discard', | |
342 | ], allow_none=False, config=True) |
|
342 | ], allow_none=False, config=True) | |
343 |
|
343 | |||
344 | # TODO: this part of prompt management should be moved to the frontends. |
|
344 | # TODO: this part of prompt management should be moved to the frontends. | |
345 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
345 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
346 | separate_in = SeparateUnicode('\n', config=True) |
|
346 | separate_in = SeparateUnicode('\n', config=True) | |
347 | separate_out = SeparateUnicode('', config=True) |
|
347 | separate_out = SeparateUnicode('', config=True) | |
348 | separate_out2 = SeparateUnicode('', config=True) |
|
348 | separate_out2 = SeparateUnicode('', config=True) | |
349 | wildcards_case_sensitive = CBool(True, config=True) |
|
349 | wildcards_case_sensitive = CBool(True, config=True) | |
350 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
350 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
351 | default_value='Context', config=True) |
|
351 | default_value='Context', config=True) | |
352 |
|
352 | |||
353 | # Subcomponents of InteractiveShell |
|
353 | # Subcomponents of InteractiveShell | |
354 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
354 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
355 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
355 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
356 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
356 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
357 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
357 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
358 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
358 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
359 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
359 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
360 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
360 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
361 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
361 | history_manager = Instance('IPython.core.history.HistoryManager') | |
362 |
|
362 | |||
363 | profile_dir = Instance('IPython.core.application.ProfileDir') |
|
363 | profile_dir = Instance('IPython.core.application.ProfileDir') | |
364 | @property |
|
364 | @property | |
365 | def profile(self): |
|
365 | def profile(self): | |
366 | if self.profile_dir is not None: |
|
366 | if self.profile_dir is not None: | |
367 | name = os.path.basename(self.profile_dir.location) |
|
367 | name = os.path.basename(self.profile_dir.location) | |
368 | return name.replace('profile_','') |
|
368 | return name.replace('profile_','') | |
369 |
|
369 | |||
370 |
|
370 | |||
371 | # Private interface |
|
371 | # Private interface | |
372 | _post_execute = Instance(dict) |
|
372 | _post_execute = Instance(dict) | |
373 |
|
373 | |||
374 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, |
|
374 | def __init__(self, config=None, ipython_dir=None, profile_dir=None, | |
375 | user_module=None, user_ns=None, |
|
375 | user_module=None, user_ns=None, | |
376 | custom_exceptions=((), None)): |
|
376 | custom_exceptions=((), None)): | |
377 |
|
377 | |||
378 | # This is where traits with a config_key argument are updated |
|
378 | # This is where traits with a config_key argument are updated | |
379 | # from the values on config. |
|
379 | # from the values on config. | |
380 | super(InteractiveShell, self).__init__(config=config) |
|
380 | super(InteractiveShell, self).__init__(config=config) | |
381 | self.configurables = [self] |
|
381 | self.configurables = [self] | |
382 |
|
382 | |||
383 | # These are relatively independent and stateless |
|
383 | # These are relatively independent and stateless | |
384 | self.init_ipython_dir(ipython_dir) |
|
384 | self.init_ipython_dir(ipython_dir) | |
385 | self.init_profile_dir(profile_dir) |
|
385 | self.init_profile_dir(profile_dir) | |
386 | self.init_instance_attrs() |
|
386 | self.init_instance_attrs() | |
387 | self.init_environment() |
|
387 | self.init_environment() | |
388 |
|
388 | |||
389 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
389 | # Create namespaces (user_ns, user_global_ns, etc.) | |
390 | self.init_create_namespaces(user_module, user_ns) |
|
390 | self.init_create_namespaces(user_module, user_ns) | |
391 | # This has to be done after init_create_namespaces because it uses |
|
391 | # This has to be done after init_create_namespaces because it uses | |
392 | # something in self.user_ns, but before init_sys_modules, which |
|
392 | # something in self.user_ns, but before init_sys_modules, which | |
393 | # is the first thing to modify sys. |
|
393 | # is the first thing to modify sys. | |
394 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
394 | # TODO: When we override sys.stdout and sys.stderr before this class | |
395 | # is created, we are saving the overridden ones here. Not sure if this |
|
395 | # is created, we are saving the overridden ones here. Not sure if this | |
396 | # is what we want to do. |
|
396 | # is what we want to do. | |
397 | self.save_sys_module_state() |
|
397 | self.save_sys_module_state() | |
398 | self.init_sys_modules() |
|
398 | self.init_sys_modules() | |
399 |
|
399 | |||
400 | # While we're trying to have each part of the code directly access what |
|
400 | # While we're trying to have each part of the code directly access what | |
401 | # it needs without keeping redundant references to objects, we have too |
|
401 | # it needs without keeping redundant references to objects, we have too | |
402 | # much legacy code that expects ip.db to exist. |
|
402 | # much legacy code that expects ip.db to exist. | |
403 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
403 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) | |
404 |
|
404 | |||
405 | self.init_history() |
|
405 | self.init_history() | |
406 | self.init_encoding() |
|
406 | self.init_encoding() | |
407 | self.init_prefilter() |
|
407 | self.init_prefilter() | |
408 |
|
408 | |||
409 | Magic.__init__(self, self) |
|
409 | Magic.__init__(self, self) | |
410 |
|
410 | |||
411 | self.init_syntax_highlighting() |
|
411 | self.init_syntax_highlighting() | |
412 | self.init_hooks() |
|
412 | self.init_hooks() | |
413 | self.init_pushd_popd_magic() |
|
413 | self.init_pushd_popd_magic() | |
414 | # self.init_traceback_handlers use to be here, but we moved it below |
|
414 | # self.init_traceback_handlers use to be here, but we moved it below | |
415 | # because it and init_io have to come after init_readline. |
|
415 | # because it and init_io have to come after init_readline. | |
416 | self.init_user_ns() |
|
416 | self.init_user_ns() | |
417 | self.init_logger() |
|
417 | self.init_logger() | |
418 | self.init_alias() |
|
418 | self.init_alias() | |
419 | self.init_builtins() |
|
419 | self.init_builtins() | |
420 |
|
420 | |||
421 | # pre_config_initialization |
|
421 | # pre_config_initialization | |
422 |
|
422 | |||
423 | # The next section should contain everything that was in ipmaker. |
|
423 | # The next section should contain everything that was in ipmaker. | |
424 | self.init_logstart() |
|
424 | self.init_logstart() | |
425 |
|
425 | |||
426 | # The following was in post_config_initialization |
|
426 | # The following was in post_config_initialization | |
427 | self.init_inspector() |
|
427 | self.init_inspector() | |
428 | # init_readline() must come before init_io(), because init_io uses |
|
428 | # init_readline() must come before init_io(), because init_io uses | |
429 | # readline related things. |
|
429 | # readline related things. | |
430 | self.init_readline() |
|
430 | self.init_readline() | |
431 | # We save this here in case user code replaces raw_input, but it needs |
|
431 | # We save this here in case user code replaces raw_input, but it needs | |
432 | # to be after init_readline(), because PyPy's readline works by replacing |
|
432 | # to be after init_readline(), because PyPy's readline works by replacing | |
433 | # raw_input. |
|
433 | # raw_input. | |
434 | if py3compat.PY3: |
|
434 | if py3compat.PY3: | |
435 | self.raw_input_original = input |
|
435 | self.raw_input_original = input | |
436 | else: |
|
436 | else: | |
437 | self.raw_input_original = raw_input |
|
437 | self.raw_input_original = raw_input | |
438 | # init_completer must come after init_readline, because it needs to |
|
438 | # init_completer must come after init_readline, because it needs to | |
439 | # know whether readline is present or not system-wide to configure the |
|
439 | # know whether readline is present or not system-wide to configure the | |
440 | # completers, since the completion machinery can now operate |
|
440 | # completers, since the completion machinery can now operate | |
441 | # independently of readline (e.g. over the network) |
|
441 | # independently of readline (e.g. over the network) | |
442 | self.init_completer() |
|
442 | self.init_completer() | |
443 | # TODO: init_io() needs to happen before init_traceback handlers |
|
443 | # TODO: init_io() needs to happen before init_traceback handlers | |
444 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
444 | # because the traceback handlers hardcode the stdout/stderr streams. | |
445 | # This logic in in debugger.Pdb and should eventually be changed. |
|
445 | # This logic in in debugger.Pdb and should eventually be changed. | |
446 | self.init_io() |
|
446 | self.init_io() | |
447 | self.init_traceback_handlers(custom_exceptions) |
|
447 | self.init_traceback_handlers(custom_exceptions) | |
448 | self.init_prompts() |
|
448 | self.init_prompts() | |
449 | self.init_display_formatter() |
|
449 | self.init_display_formatter() | |
450 | self.init_display_pub() |
|
450 | self.init_display_pub() | |
451 | self.init_displayhook() |
|
451 | self.init_displayhook() | |
452 | self.init_reload_doctest() |
|
452 | self.init_reload_doctest() | |
453 | self.init_magics() |
|
453 | self.init_magics() | |
454 | self.init_pdb() |
|
454 | self.init_pdb() | |
455 | self.init_extension_manager() |
|
455 | self.init_extension_manager() | |
456 | self.init_plugin_manager() |
|
456 | self.init_plugin_manager() | |
457 | self.init_payload() |
|
457 | self.init_payload() | |
458 | self.hooks.late_startup_hook() |
|
458 | self.hooks.late_startup_hook() | |
459 | atexit.register(self.atexit_operations) |
|
459 | atexit.register(self.atexit_operations) | |
460 |
|
460 | |||
461 | def get_ipython(self): |
|
461 | def get_ipython(self): | |
462 | """Return the currently running IPython instance.""" |
|
462 | """Return the currently running IPython instance.""" | |
463 | return self |
|
463 | return self | |
464 |
|
464 | |||
465 | #------------------------------------------------------------------------- |
|
465 | #------------------------------------------------------------------------- | |
466 | # Trait changed handlers |
|
466 | # Trait changed handlers | |
467 | #------------------------------------------------------------------------- |
|
467 | #------------------------------------------------------------------------- | |
468 |
|
468 | |||
469 | def _ipython_dir_changed(self, name, new): |
|
469 | def _ipython_dir_changed(self, name, new): | |
470 | if not os.path.isdir(new): |
|
470 | if not os.path.isdir(new): | |
471 | os.makedirs(new, mode = 0777) |
|
471 | os.makedirs(new, mode = 0777) | |
472 |
|
472 | |||
473 | def set_autoindent(self,value=None): |
|
473 | def set_autoindent(self,value=None): | |
474 | """Set the autoindent flag, checking for readline support. |
|
474 | """Set the autoindent flag, checking for readline support. | |
475 |
|
475 | |||
476 | If called with no arguments, it acts as a toggle.""" |
|
476 | If called with no arguments, it acts as a toggle.""" | |
477 |
|
477 | |||
478 | if value != 0 and not self.has_readline: |
|
478 | if value != 0 and not self.has_readline: | |
479 | if os.name == 'posix': |
|
479 | if os.name == 'posix': | |
480 | warn("The auto-indent feature requires the readline library") |
|
480 | warn("The auto-indent feature requires the readline library") | |
481 | self.autoindent = 0 |
|
481 | self.autoindent = 0 | |
482 | return |
|
482 | return | |
483 | if value is None: |
|
483 | if value is None: | |
484 | self.autoindent = not self.autoindent |
|
484 | self.autoindent = not self.autoindent | |
485 | else: |
|
485 | else: | |
486 | self.autoindent = value |
|
486 | self.autoindent = value | |
487 |
|
487 | |||
488 | #------------------------------------------------------------------------- |
|
488 | #------------------------------------------------------------------------- | |
489 | # init_* methods called by __init__ |
|
489 | # init_* methods called by __init__ | |
490 | #------------------------------------------------------------------------- |
|
490 | #------------------------------------------------------------------------- | |
491 |
|
491 | |||
492 | def init_ipython_dir(self, ipython_dir): |
|
492 | def init_ipython_dir(self, ipython_dir): | |
493 | if ipython_dir is not None: |
|
493 | if ipython_dir is not None: | |
494 | self.ipython_dir = ipython_dir |
|
494 | self.ipython_dir = ipython_dir | |
495 | return |
|
495 | return | |
496 |
|
496 | |||
497 | self.ipython_dir = get_ipython_dir() |
|
497 | self.ipython_dir = get_ipython_dir() | |
498 |
|
498 | |||
499 | def init_profile_dir(self, profile_dir): |
|
499 | def init_profile_dir(self, profile_dir): | |
500 | if profile_dir is not None: |
|
500 | if profile_dir is not None: | |
501 | self.profile_dir = profile_dir |
|
501 | self.profile_dir = profile_dir | |
502 | return |
|
502 | return | |
503 | self.profile_dir =\ |
|
503 | self.profile_dir =\ | |
504 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
504 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') | |
505 |
|
505 | |||
506 | def init_instance_attrs(self): |
|
506 | def init_instance_attrs(self): | |
507 | self.more = False |
|
507 | self.more = False | |
508 |
|
508 | |||
509 | # command compiler |
|
509 | # command compiler | |
510 | self.compile = CachingCompiler() |
|
510 | self.compile = CachingCompiler() | |
511 |
|
511 | |||
512 | # Make an empty namespace, which extension writers can rely on both |
|
512 | # Make an empty namespace, which extension writers can rely on both | |
513 | # existing and NEVER being used by ipython itself. This gives them a |
|
513 | # existing and NEVER being used by ipython itself. This gives them a | |
514 | # convenient location for storing additional information and state |
|
514 | # convenient location for storing additional information and state | |
515 | # their extensions may require, without fear of collisions with other |
|
515 | # their extensions may require, without fear of collisions with other | |
516 | # ipython names that may develop later. |
|
516 | # ipython names that may develop later. | |
517 | self.meta = Struct() |
|
517 | self.meta = Struct() | |
518 |
|
518 | |||
519 | # Temporary files used for various purposes. Deleted at exit. |
|
519 | # Temporary files used for various purposes. Deleted at exit. | |
520 | self.tempfiles = [] |
|
520 | self.tempfiles = [] | |
521 |
|
521 | |||
522 | # Keep track of readline usage (later set by init_readline) |
|
522 | # Keep track of readline usage (later set by init_readline) | |
523 | self.has_readline = False |
|
523 | self.has_readline = False | |
524 |
|
524 | |||
525 | # keep track of where we started running (mainly for crash post-mortem) |
|
525 | # keep track of where we started running (mainly for crash post-mortem) | |
526 | # This is not being used anywhere currently. |
|
526 | # This is not being used anywhere currently. | |
527 | self.starting_dir = os.getcwdu() |
|
527 | self.starting_dir = os.getcwdu() | |
528 |
|
528 | |||
529 | # Indentation management |
|
529 | # Indentation management | |
530 | self.indent_current_nsp = 0 |
|
530 | self.indent_current_nsp = 0 | |
531 |
|
531 | |||
532 | # Dict to track post-execution functions that have been registered |
|
532 | # Dict to track post-execution functions that have been registered | |
533 | self._post_execute = {} |
|
533 | self._post_execute = {} | |
534 |
|
534 | |||
535 | def init_environment(self): |
|
535 | def init_environment(self): | |
536 | """Any changes we need to make to the user's environment.""" |
|
536 | """Any changes we need to make to the user's environment.""" | |
537 | pass |
|
537 | pass | |
538 |
|
538 | |||
539 | def init_encoding(self): |
|
539 | def init_encoding(self): | |
540 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
540 | # Get system encoding at startup time. Certain terminals (like Emacs | |
541 | # under Win32 have it set to None, and we need to have a known valid |
|
541 | # under Win32 have it set to None, and we need to have a known valid | |
542 | # encoding to use in the raw_input() method |
|
542 | # encoding to use in the raw_input() method | |
543 | try: |
|
543 | try: | |
544 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
544 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
545 | except AttributeError: |
|
545 | except AttributeError: | |
546 | self.stdin_encoding = 'ascii' |
|
546 | self.stdin_encoding = 'ascii' | |
547 |
|
547 | |||
548 | def init_syntax_highlighting(self): |
|
548 | def init_syntax_highlighting(self): | |
549 | # Python source parser/formatter for syntax highlighting |
|
549 | # Python source parser/formatter for syntax highlighting | |
550 | pyformat = PyColorize.Parser().format |
|
550 | pyformat = PyColorize.Parser().format | |
551 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
551 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
552 |
|
552 | |||
553 | def init_pushd_popd_magic(self): |
|
553 | def init_pushd_popd_magic(self): | |
554 | # for pushd/popd management |
|
554 | # for pushd/popd management | |
555 | self.home_dir = get_home_dir() |
|
555 | self.home_dir = get_home_dir() | |
556 |
|
556 | |||
557 | self.dir_stack = [] |
|
557 | self.dir_stack = [] | |
558 |
|
558 | |||
559 | def init_logger(self): |
|
559 | def init_logger(self): | |
560 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
560 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
561 | logmode='rotate') |
|
561 | logmode='rotate') | |
562 |
|
562 | |||
563 | def init_logstart(self): |
|
563 | def init_logstart(self): | |
564 | """Initialize logging in case it was requested at the command line. |
|
564 | """Initialize logging in case it was requested at the command line. | |
565 | """ |
|
565 | """ | |
566 | if self.logappend: |
|
566 | if self.logappend: | |
567 | self.magic_logstart(self.logappend + ' append') |
|
567 | self.magic_logstart(self.logappend + ' append') | |
568 | elif self.logfile: |
|
568 | elif self.logfile: | |
569 | self.magic_logstart(self.logfile) |
|
569 | self.magic_logstart(self.logfile) | |
570 | elif self.logstart: |
|
570 | elif self.logstart: | |
571 | self.magic_logstart() |
|
571 | self.magic_logstart() | |
572 |
|
572 | |||
573 | def init_builtins(self): |
|
573 | def init_builtins(self): | |
574 | self.builtin_trap = BuiltinTrap(shell=self) |
|
574 | self.builtin_trap = BuiltinTrap(shell=self) | |
575 |
|
575 | |||
576 | def init_inspector(self): |
|
576 | def init_inspector(self): | |
577 | # Object inspector |
|
577 | # Object inspector | |
578 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
578 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
579 | PyColorize.ANSICodeColors, |
|
579 | PyColorize.ANSICodeColors, | |
580 | 'NoColor', |
|
580 | 'NoColor', | |
581 | self.object_info_string_level) |
|
581 | self.object_info_string_level) | |
582 |
|
582 | |||
583 | def init_io(self): |
|
583 | def init_io(self): | |
584 | # This will just use sys.stdout and sys.stderr. If you want to |
|
584 | # This will just use sys.stdout and sys.stderr. If you want to | |
585 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
585 | # override sys.stdout and sys.stderr themselves, you need to do that | |
586 | # *before* instantiating this class, because io holds onto |
|
586 | # *before* instantiating this class, because io holds onto | |
587 | # references to the underlying streams. |
|
587 | # references to the underlying streams. | |
588 | if sys.platform == 'win32' and self.has_readline: |
|
588 | if sys.platform == 'win32' and self.has_readline: | |
589 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
589 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) | |
590 | else: |
|
590 | else: | |
591 | io.stdout = io.IOStream(sys.stdout) |
|
591 | io.stdout = io.IOStream(sys.stdout) | |
592 | io.stderr = io.IOStream(sys.stderr) |
|
592 | io.stderr = io.IOStream(sys.stderr) | |
593 |
|
593 | |||
594 | def init_prompts(self): |
|
594 | def init_prompts(self): | |
595 | # TODO: This is a pass for now because the prompts are managed inside |
|
595 | # TODO: This is a pass for now because the prompts are managed inside | |
596 | # the DisplayHook. Once there is a separate prompt manager, this |
|
596 | # the DisplayHook. Once there is a separate prompt manager, this | |
597 | # will initialize that object and all prompt related information. |
|
597 | # will initialize that object and all prompt related information. | |
598 | pass |
|
598 | pass | |
599 |
|
599 | |||
600 | def init_display_formatter(self): |
|
600 | def init_display_formatter(self): | |
601 | self.display_formatter = DisplayFormatter(config=self.config) |
|
601 | self.display_formatter = DisplayFormatter(config=self.config) | |
602 | self.configurables.append(self.display_formatter) |
|
602 | self.configurables.append(self.display_formatter) | |
603 |
|
603 | |||
604 | def init_display_pub(self): |
|
604 | def init_display_pub(self): | |
605 | self.display_pub = self.display_pub_class(config=self.config) |
|
605 | self.display_pub = self.display_pub_class(config=self.config) | |
606 | self.configurables.append(self.display_pub) |
|
606 | self.configurables.append(self.display_pub) | |
607 |
|
607 | |||
608 | def init_displayhook(self): |
|
608 | def init_displayhook(self): | |
609 | # Initialize displayhook, set in/out prompts and printing system |
|
609 | # Initialize displayhook, set in/out prompts and printing system | |
610 | self.displayhook = self.displayhook_class( |
|
610 | self.displayhook = self.displayhook_class( | |
611 | config=self.config, |
|
611 | config=self.config, | |
612 | shell=self, |
|
612 | shell=self, | |
613 | cache_size=self.cache_size, |
|
613 | cache_size=self.cache_size, | |
614 | input_sep = self.separate_in, |
|
614 | input_sep = self.separate_in, | |
615 | output_sep = self.separate_out, |
|
615 | output_sep = self.separate_out, | |
616 | output_sep2 = self.separate_out2, |
|
616 | output_sep2 = self.separate_out2, | |
617 | ps1 = self.prompt_in1, |
|
617 | ps1 = self.prompt_in1, | |
618 | ps2 = self.prompt_in2, |
|
618 | ps2 = self.prompt_in2, | |
619 | ps_out = self.prompt_out, |
|
619 | ps_out = self.prompt_out, | |
620 | pad_left = self.prompts_pad_left |
|
620 | pad_left = self.prompts_pad_left | |
621 | ) |
|
621 | ) | |
622 | self.configurables.append(self.displayhook) |
|
622 | self.configurables.append(self.displayhook) | |
623 | # This is a context manager that installs/revmoes the displayhook at |
|
623 | # This is a context manager that installs/revmoes the displayhook at | |
624 | # the appropriate time. |
|
624 | # the appropriate time. | |
625 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
625 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
626 |
|
626 | |||
627 | def init_reload_doctest(self): |
|
627 | def init_reload_doctest(self): | |
628 | # Do a proper resetting of doctest, including the necessary displayhook |
|
628 | # Do a proper resetting of doctest, including the necessary displayhook | |
629 | # monkeypatching |
|
629 | # monkeypatching | |
630 | try: |
|
630 | try: | |
631 | doctest_reload() |
|
631 | doctest_reload() | |
632 | except ImportError: |
|
632 | except ImportError: | |
633 | warn("doctest module does not exist.") |
|
633 | warn("doctest module does not exist.") | |
634 |
|
634 | |||
635 | #------------------------------------------------------------------------- |
|
635 | #------------------------------------------------------------------------- | |
636 | # Things related to injections into the sys module |
|
636 | # Things related to injections into the sys module | |
637 | #------------------------------------------------------------------------- |
|
637 | #------------------------------------------------------------------------- | |
638 |
|
638 | |||
639 | def save_sys_module_state(self): |
|
639 | def save_sys_module_state(self): | |
640 | """Save the state of hooks in the sys module. |
|
640 | """Save the state of hooks in the sys module. | |
641 |
|
641 | |||
642 | This has to be called after self.user_module is created. |
|
642 | This has to be called after self.user_module is created. | |
643 | """ |
|
643 | """ | |
644 | self._orig_sys_module_state = {} |
|
644 | self._orig_sys_module_state = {} | |
645 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
645 | self._orig_sys_module_state['stdin'] = sys.stdin | |
646 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
646 | self._orig_sys_module_state['stdout'] = sys.stdout | |
647 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
647 | self._orig_sys_module_state['stderr'] = sys.stderr | |
648 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
648 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
649 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
649 | self._orig_sys_modules_main_name = self.user_module.__name__ | |
650 |
|
650 | |||
651 | def restore_sys_module_state(self): |
|
651 | def restore_sys_module_state(self): | |
652 | """Restore the state of the sys module.""" |
|
652 | """Restore the state of the sys module.""" | |
653 | try: |
|
653 | try: | |
654 | for k, v in self._orig_sys_module_state.iteritems(): |
|
654 | for k, v in self._orig_sys_module_state.iteritems(): | |
655 | setattr(sys, k, v) |
|
655 | setattr(sys, k, v) | |
656 | except AttributeError: |
|
656 | except AttributeError: | |
657 | pass |
|
657 | pass | |
658 | # Reset what what done in self.init_sys_modules |
|
658 | # Reset what what done in self.init_sys_modules | |
659 | sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name |
|
659 | sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name | |
660 |
|
660 | |||
661 | #------------------------------------------------------------------------- |
|
661 | #------------------------------------------------------------------------- | |
662 | # Things related to hooks |
|
662 | # Things related to hooks | |
663 | #------------------------------------------------------------------------- |
|
663 | #------------------------------------------------------------------------- | |
664 |
|
664 | |||
665 | def init_hooks(self): |
|
665 | def init_hooks(self): | |
666 | # hooks holds pointers used for user-side customizations |
|
666 | # hooks holds pointers used for user-side customizations | |
667 | self.hooks = Struct() |
|
667 | self.hooks = Struct() | |
668 |
|
668 | |||
669 | self.strdispatchers = {} |
|
669 | self.strdispatchers = {} | |
670 |
|
670 | |||
671 | # Set all default hooks, defined in the IPython.hooks module. |
|
671 | # Set all default hooks, defined in the IPython.hooks module. | |
672 | hooks = IPython.core.hooks |
|
672 | hooks = IPython.core.hooks | |
673 | for hook_name in hooks.__all__: |
|
673 | for hook_name in hooks.__all__: | |
674 | # default hooks have priority 100, i.e. low; user hooks should have |
|
674 | # default hooks have priority 100, i.e. low; user hooks should have | |
675 | # 0-100 priority |
|
675 | # 0-100 priority | |
676 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
676 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
677 |
|
677 | |||
678 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
678 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
679 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
679 | """set_hook(name,hook) -> sets an internal IPython hook. | |
680 |
|
680 | |||
681 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
681 | IPython exposes some of its internal API as user-modifiable hooks. By | |
682 | adding your function to one of these hooks, you can modify IPython's |
|
682 | adding your function to one of these hooks, you can modify IPython's | |
683 | behavior to call at runtime your own routines.""" |
|
683 | behavior to call at runtime your own routines.""" | |
684 |
|
684 | |||
685 | # At some point in the future, this should validate the hook before it |
|
685 | # At some point in the future, this should validate the hook before it | |
686 | # accepts it. Probably at least check that the hook takes the number |
|
686 | # accepts it. Probably at least check that the hook takes the number | |
687 | # of args it's supposed to. |
|
687 | # of args it's supposed to. | |
688 |
|
688 | |||
689 | f = types.MethodType(hook,self) |
|
689 | f = types.MethodType(hook,self) | |
690 |
|
690 | |||
691 | # check if the hook is for strdispatcher first |
|
691 | # check if the hook is for strdispatcher first | |
692 | if str_key is not None: |
|
692 | if str_key is not None: | |
693 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
693 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
694 | sdp.add_s(str_key, f, priority ) |
|
694 | sdp.add_s(str_key, f, priority ) | |
695 | self.strdispatchers[name] = sdp |
|
695 | self.strdispatchers[name] = sdp | |
696 | return |
|
696 | return | |
697 | if re_key is not None: |
|
697 | if re_key is not None: | |
698 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
698 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
699 | sdp.add_re(re.compile(re_key), f, priority ) |
|
699 | sdp.add_re(re.compile(re_key), f, priority ) | |
700 | self.strdispatchers[name] = sdp |
|
700 | self.strdispatchers[name] = sdp | |
701 | return |
|
701 | return | |
702 |
|
702 | |||
703 | dp = getattr(self.hooks, name, None) |
|
703 | dp = getattr(self.hooks, name, None) | |
704 | if name not in IPython.core.hooks.__all__: |
|
704 | if name not in IPython.core.hooks.__all__: | |
705 | print "Warning! Hook '%s' is not one of %s" % \ |
|
705 | print "Warning! Hook '%s' is not one of %s" % \ | |
706 | (name, IPython.core.hooks.__all__ ) |
|
706 | (name, IPython.core.hooks.__all__ ) | |
707 | if not dp: |
|
707 | if not dp: | |
708 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
708 | dp = IPython.core.hooks.CommandChainDispatcher() | |
709 |
|
709 | |||
710 | try: |
|
710 | try: | |
711 | dp.add(f,priority) |
|
711 | dp.add(f,priority) | |
712 | except AttributeError: |
|
712 | except AttributeError: | |
713 | # it was not commandchain, plain old func - replace |
|
713 | # it was not commandchain, plain old func - replace | |
714 | dp = f |
|
714 | dp = f | |
715 |
|
715 | |||
716 | setattr(self.hooks,name, dp) |
|
716 | setattr(self.hooks,name, dp) | |
717 |
|
717 | |||
718 | def register_post_execute(self, func): |
|
718 | def register_post_execute(self, func): | |
719 | """Register a function for calling after code execution. |
|
719 | """Register a function for calling after code execution. | |
720 | """ |
|
720 | """ | |
721 | if not callable(func): |
|
721 | if not callable(func): | |
722 | raise ValueError('argument %s must be callable' % func) |
|
722 | raise ValueError('argument %s must be callable' % func) | |
723 | self._post_execute[func] = True |
|
723 | self._post_execute[func] = True | |
724 |
|
724 | |||
725 | #------------------------------------------------------------------------- |
|
725 | #------------------------------------------------------------------------- | |
726 | # Things related to the "main" module |
|
726 | # Things related to the "main" module | |
727 | #------------------------------------------------------------------------- |
|
727 | #------------------------------------------------------------------------- | |
728 |
|
728 | |||
729 | def new_main_mod(self,ns=None): |
|
729 | def new_main_mod(self,ns=None): | |
730 | """Return a new 'main' module object for user code execution. |
|
730 | """Return a new 'main' module object for user code execution. | |
731 | """ |
|
731 | """ | |
732 | main_mod = self._user_main_module |
|
732 | main_mod = self._user_main_module | |
733 | init_fakemod_dict(main_mod,ns) |
|
733 | init_fakemod_dict(main_mod,ns) | |
734 | return main_mod |
|
734 | return main_mod | |
735 |
|
735 | |||
736 | def cache_main_mod(self,ns,fname): |
|
736 | def cache_main_mod(self,ns,fname): | |
737 | """Cache a main module's namespace. |
|
737 | """Cache a main module's namespace. | |
738 |
|
738 | |||
739 | When scripts are executed via %run, we must keep a reference to the |
|
739 | When scripts are executed via %run, we must keep a reference to the | |
740 | namespace of their __main__ module (a FakeModule instance) around so |
|
740 | namespace of their __main__ module (a FakeModule instance) around so | |
741 | that Python doesn't clear it, rendering objects defined therein |
|
741 | that Python doesn't clear it, rendering objects defined therein | |
742 | useless. |
|
742 | useless. | |
743 |
|
743 | |||
744 | This method keeps said reference in a private dict, keyed by the |
|
744 | This method keeps said reference in a private dict, keyed by the | |
745 | absolute path of the module object (which corresponds to the script |
|
745 | absolute path of the module object (which corresponds to the script | |
746 | path). This way, for multiple executions of the same script we only |
|
746 | path). This way, for multiple executions of the same script we only | |
747 | keep one copy of the namespace (the last one), thus preventing memory |
|
747 | keep one copy of the namespace (the last one), thus preventing memory | |
748 | leaks from old references while allowing the objects from the last |
|
748 | leaks from old references while allowing the objects from the last | |
749 | execution to be accessible. |
|
749 | execution to be accessible. | |
750 |
|
750 | |||
751 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
751 | Note: we can not allow the actual FakeModule instances to be deleted, | |
752 | because of how Python tears down modules (it hard-sets all their |
|
752 | because of how Python tears down modules (it hard-sets all their | |
753 | references to None without regard for reference counts). This method |
|
753 | references to None without regard for reference counts). This method | |
754 | must therefore make a *copy* of the given namespace, to allow the |
|
754 | must therefore make a *copy* of the given namespace, to allow the | |
755 | original module's __dict__ to be cleared and reused. |
|
755 | original module's __dict__ to be cleared and reused. | |
756 |
|
756 | |||
757 |
|
757 | |||
758 | Parameters |
|
758 | Parameters | |
759 | ---------- |
|
759 | ---------- | |
760 | ns : a namespace (a dict, typically) |
|
760 | ns : a namespace (a dict, typically) | |
761 |
|
761 | |||
762 | fname : str |
|
762 | fname : str | |
763 | Filename associated with the namespace. |
|
763 | Filename associated with the namespace. | |
764 |
|
764 | |||
765 | Examples |
|
765 | Examples | |
766 | -------- |
|
766 | -------- | |
767 |
|
767 | |||
768 | In [10]: import IPython |
|
768 | In [10]: import IPython | |
769 |
|
769 | |||
770 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
770 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
771 |
|
771 | |||
772 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
772 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
773 | Out[12]: True |
|
773 | Out[12]: True | |
774 | """ |
|
774 | """ | |
775 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
775 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
776 |
|
776 | |||
777 | def clear_main_mod_cache(self): |
|
777 | def clear_main_mod_cache(self): | |
778 | """Clear the cache of main modules. |
|
778 | """Clear the cache of main modules. | |
779 |
|
779 | |||
780 | Mainly for use by utilities like %reset. |
|
780 | Mainly for use by utilities like %reset. | |
781 |
|
781 | |||
782 | Examples |
|
782 | Examples | |
783 | -------- |
|
783 | -------- | |
784 |
|
784 | |||
785 | In [15]: import IPython |
|
785 | In [15]: import IPython | |
786 |
|
786 | |||
787 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
787 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
788 |
|
788 | |||
789 | In [17]: len(_ip._main_ns_cache) > 0 |
|
789 | In [17]: len(_ip._main_ns_cache) > 0 | |
790 | Out[17]: True |
|
790 | Out[17]: True | |
791 |
|
791 | |||
792 | In [18]: _ip.clear_main_mod_cache() |
|
792 | In [18]: _ip.clear_main_mod_cache() | |
793 |
|
793 | |||
794 | In [19]: len(_ip._main_ns_cache) == 0 |
|
794 | In [19]: len(_ip._main_ns_cache) == 0 | |
795 | Out[19]: True |
|
795 | Out[19]: True | |
796 | """ |
|
796 | """ | |
797 | self._main_ns_cache.clear() |
|
797 | self._main_ns_cache.clear() | |
798 |
|
798 | |||
799 | #------------------------------------------------------------------------- |
|
799 | #------------------------------------------------------------------------- | |
800 | # Things related to debugging |
|
800 | # Things related to debugging | |
801 | #------------------------------------------------------------------------- |
|
801 | #------------------------------------------------------------------------- | |
802 |
|
802 | |||
803 | def init_pdb(self): |
|
803 | def init_pdb(self): | |
804 | # Set calling of pdb on exceptions |
|
804 | # Set calling of pdb on exceptions | |
805 | # self.call_pdb is a property |
|
805 | # self.call_pdb is a property | |
806 | self.call_pdb = self.pdb |
|
806 | self.call_pdb = self.pdb | |
807 |
|
807 | |||
808 | def _get_call_pdb(self): |
|
808 | def _get_call_pdb(self): | |
809 | return self._call_pdb |
|
809 | return self._call_pdb | |
810 |
|
810 | |||
811 | def _set_call_pdb(self,val): |
|
811 | def _set_call_pdb(self,val): | |
812 |
|
812 | |||
813 | if val not in (0,1,False,True): |
|
813 | if val not in (0,1,False,True): | |
814 | raise ValueError,'new call_pdb value must be boolean' |
|
814 | raise ValueError,'new call_pdb value must be boolean' | |
815 |
|
815 | |||
816 | # store value in instance |
|
816 | # store value in instance | |
817 | self._call_pdb = val |
|
817 | self._call_pdb = val | |
818 |
|
818 | |||
819 | # notify the actual exception handlers |
|
819 | # notify the actual exception handlers | |
820 | self.InteractiveTB.call_pdb = val |
|
820 | self.InteractiveTB.call_pdb = val | |
821 |
|
821 | |||
822 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
822 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
823 | 'Control auto-activation of pdb at exceptions') |
|
823 | 'Control auto-activation of pdb at exceptions') | |
824 |
|
824 | |||
825 | def debugger(self,force=False): |
|
825 | def debugger(self,force=False): | |
826 | """Call the pydb/pdb debugger. |
|
826 | """Call the pydb/pdb debugger. | |
827 |
|
827 | |||
828 | Keywords: |
|
828 | Keywords: | |
829 |
|
829 | |||
830 | - force(False): by default, this routine checks the instance call_pdb |
|
830 | - force(False): by default, this routine checks the instance call_pdb | |
831 | flag and does not actually invoke the debugger if the flag is false. |
|
831 | flag and does not actually invoke the debugger if the flag is false. | |
832 | The 'force' option forces the debugger to activate even if the flag |
|
832 | The 'force' option forces the debugger to activate even if the flag | |
833 | is false. |
|
833 | is false. | |
834 | """ |
|
834 | """ | |
835 |
|
835 | |||
836 | if not (force or self.call_pdb): |
|
836 | if not (force or self.call_pdb): | |
837 | return |
|
837 | return | |
838 |
|
838 | |||
839 | if not hasattr(sys,'last_traceback'): |
|
839 | if not hasattr(sys,'last_traceback'): | |
840 | error('No traceback has been produced, nothing to debug.') |
|
840 | error('No traceback has been produced, nothing to debug.') | |
841 | return |
|
841 | return | |
842 |
|
842 | |||
843 | # use pydb if available |
|
843 | # use pydb if available | |
844 | if debugger.has_pydb: |
|
844 | if debugger.has_pydb: | |
845 | from pydb import pm |
|
845 | from pydb import pm | |
846 | else: |
|
846 | else: | |
847 | # fallback to our internal debugger |
|
847 | # fallback to our internal debugger | |
848 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
848 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
849 |
|
849 | |||
850 | with self.readline_no_record: |
|
850 | with self.readline_no_record: | |
851 | pm() |
|
851 | pm() | |
852 |
|
852 | |||
853 | #------------------------------------------------------------------------- |
|
853 | #------------------------------------------------------------------------- | |
854 | # Things related to IPython's various namespaces |
|
854 | # Things related to IPython's various namespaces | |
855 | #------------------------------------------------------------------------- |
|
855 | #------------------------------------------------------------------------- | |
856 |
|
856 | |||
857 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
857 | def init_create_namespaces(self, user_module=None, user_ns=None): | |
858 | # Create the namespace where the user will operate. user_ns is |
|
858 | # Create the namespace where the user will operate. user_ns is | |
859 | # normally the only one used, and it is passed to the exec calls as |
|
859 | # normally the only one used, and it is passed to the exec calls as | |
860 | # the locals argument. But we do carry a user_global_ns namespace |
|
860 | # the locals argument. But we do carry a user_global_ns namespace | |
861 | # given as the exec 'globals' argument, This is useful in embedding |
|
861 | # given as the exec 'globals' argument, This is useful in embedding | |
862 | # situations where the ipython shell opens in a context where the |
|
862 | # situations where the ipython shell opens in a context where the | |
863 | # distinction between locals and globals is meaningful. For |
|
863 | # distinction between locals and globals is meaningful. For | |
864 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
864 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
865 |
|
865 | |||
866 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
866 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
867 | # level as a dict instead of a module. This is a manual fix, but I |
|
867 | # level as a dict instead of a module. This is a manual fix, but I | |
868 | # should really track down where the problem is coming from. Alex |
|
868 | # should really track down where the problem is coming from. Alex | |
869 | # Schmolck reported this problem first. |
|
869 | # Schmolck reported this problem first. | |
870 |
|
870 | |||
871 | # A useful post by Alex Martelli on this topic: |
|
871 | # A useful post by Alex Martelli on this topic: | |
872 | # Re: inconsistent value from __builtins__ |
|
872 | # Re: inconsistent value from __builtins__ | |
873 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
873 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
874 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
874 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
875 | # Gruppen: comp.lang.python |
|
875 | # Gruppen: comp.lang.python | |
876 |
|
876 | |||
877 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
877 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
878 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
878 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
879 | # > <type 'dict'> |
|
879 | # > <type 'dict'> | |
880 | # > >>> print type(__builtins__) |
|
880 | # > >>> print type(__builtins__) | |
881 | # > <type 'module'> |
|
881 | # > <type 'module'> | |
882 | # > Is this difference in return value intentional? |
|
882 | # > Is this difference in return value intentional? | |
883 |
|
883 | |||
884 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
884 | # Well, it's documented that '__builtins__' can be either a dictionary | |
885 | # or a module, and it's been that way for a long time. Whether it's |
|
885 | # or a module, and it's been that way for a long time. Whether it's | |
886 | # intentional (or sensible), I don't know. In any case, the idea is |
|
886 | # intentional (or sensible), I don't know. In any case, the idea is | |
887 | # that if you need to access the built-in namespace directly, you |
|
887 | # that if you need to access the built-in namespace directly, you | |
888 | # should start with "import __builtin__" (note, no 's') which will |
|
888 | # should start with "import __builtin__" (note, no 's') which will | |
889 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
889 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
890 |
|
890 | |||
891 | # These routines return properly built dicts as needed by the rest of |
|
891 | # These routines return properly built dicts as needed by the rest of | |
892 | # the code, and can also be used by extension writers to generate |
|
892 | # the code, and can also be used by extension writers to generate | |
893 | # properly initialized namespaces. |
|
893 | # properly initialized namespaces. | |
894 | self.user_module = self.prepare_user_module(user_module) |
|
894 | self.user_module = self.prepare_user_module(user_module) | |
895 |
|
895 | |||
896 | if user_ns is None: |
|
896 | if user_ns is None: | |
897 | user_ns = self.user_module.__dict__ |
|
897 | user_ns = self.user_module.__dict__ | |
898 | self.user_ns = user_ns |
|
898 | self.user_ns = user_ns | |
899 |
|
899 | |||
900 | # An auxiliary namespace that checks what parts of the user_ns were |
|
900 | # An auxiliary namespace that checks what parts of the user_ns were | |
901 | # loaded at startup, so we can list later only variables defined in |
|
901 | # loaded at startup, so we can list later only variables defined in | |
902 | # actual interactive use. Since it is always a subset of user_ns, it |
|
902 | # actual interactive use. Since it is always a subset of user_ns, it | |
903 | # doesn't need to be separately tracked in the ns_table. |
|
903 | # doesn't need to be separately tracked in the ns_table. | |
904 | self.user_ns_hidden = set() |
|
904 | self.user_ns_hidden = set() | |
905 |
|
905 | |||
906 | # A namespace to keep track of internal data structures to prevent |
|
|||
907 | # them from cluttering user-visible stuff. Will be updated later |
|
|||
908 | self.internal_ns = {} |
|
|||
909 |
|
||||
910 | # Now that FakeModule produces a real module, we've run into a nasty |
|
906 | # Now that FakeModule produces a real module, we've run into a nasty | |
911 | # problem: after script execution (via %run), the module where the user |
|
907 | # problem: after script execution (via %run), the module where the user | |
912 | # code ran is deleted. Now that this object is a true module (needed |
|
908 | # code ran is deleted. Now that this object is a true module (needed | |
913 | # so docetst and other tools work correctly), the Python module |
|
909 | # so docetst and other tools work correctly), the Python module | |
914 | # teardown mechanism runs over it, and sets to None every variable |
|
910 | # teardown mechanism runs over it, and sets to None every variable | |
915 | # present in that module. Top-level references to objects from the |
|
911 | # present in that module. Top-level references to objects from the | |
916 | # script survive, because the user_ns is updated with them. However, |
|
912 | # script survive, because the user_ns is updated with them. However, | |
917 | # calling functions defined in the script that use other things from |
|
913 | # calling functions defined in the script that use other things from | |
918 | # the script will fail, because the function's closure had references |
|
914 | # the script will fail, because the function's closure had references | |
919 | # to the original objects, which are now all None. So we must protect |
|
915 | # to the original objects, which are now all None. So we must protect | |
920 | # these modules from deletion by keeping a cache. |
|
916 | # these modules from deletion by keeping a cache. | |
921 | # |
|
917 | # | |
922 | # To avoid keeping stale modules around (we only need the one from the |
|
918 | # To avoid keeping stale modules around (we only need the one from the | |
923 | # last run), we use a dict keyed with the full path to the script, so |
|
919 | # last run), we use a dict keyed with the full path to the script, so | |
924 | # only the last version of the module is held in the cache. Note, |
|
920 | # only the last version of the module is held in the cache. Note, | |
925 | # however, that we must cache the module *namespace contents* (their |
|
921 | # however, that we must cache the module *namespace contents* (their | |
926 | # __dict__). Because if we try to cache the actual modules, old ones |
|
922 | # __dict__). Because if we try to cache the actual modules, old ones | |
927 | # (uncached) could be destroyed while still holding references (such as |
|
923 | # (uncached) could be destroyed while still holding references (such as | |
928 | # those held by GUI objects that tend to be long-lived)> |
|
924 | # those held by GUI objects that tend to be long-lived)> | |
929 | # |
|
925 | # | |
930 | # The %reset command will flush this cache. See the cache_main_mod() |
|
926 | # The %reset command will flush this cache. See the cache_main_mod() | |
931 | # and clear_main_mod_cache() methods for details on use. |
|
927 | # and clear_main_mod_cache() methods for details on use. | |
932 |
|
928 | |||
933 | # This is the cache used for 'main' namespaces |
|
929 | # This is the cache used for 'main' namespaces | |
934 | self._main_ns_cache = {} |
|
930 | self._main_ns_cache = {} | |
935 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
931 | # And this is the single instance of FakeModule whose __dict__ we keep | |
936 | # copying and clearing for reuse on each %run |
|
932 | # copying and clearing for reuse on each %run | |
937 | self._user_main_module = FakeModule() |
|
933 | self._user_main_module = FakeModule() | |
938 |
|
934 | |||
939 | # A table holding all the namespaces IPython deals with, so that |
|
935 | # A table holding all the namespaces IPython deals with, so that | |
940 | # introspection facilities can search easily. |
|
936 | # introspection facilities can search easily. | |
941 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
937 | self.ns_table = {'user_global':self.user_module.__dict__, | |
942 | 'user_local':user_ns, |
|
938 | 'user_local':user_ns, | |
943 | 'internal':self.internal_ns, |
|
|||
944 | 'builtin':builtin_mod.__dict__ |
|
939 | 'builtin':builtin_mod.__dict__ | |
945 | } |
|
940 | } | |
946 |
|
941 | |||
947 | # Similarly, track all namespaces where references can be held and that |
|
|||
948 | # we can safely clear (so it can NOT include builtin). This one can be |
|
|||
949 | # a simple list. Note that the main execution namespaces, user_ns and |
|
|||
950 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
|||
951 | # causes errors in object __del__ methods. Instead, the reset() method |
|
|||
952 | # clears them manually and carefully. |
|
|||
953 | self.ns_refs_table = [ self.internal_ns, self._main_ns_cache ] |
|
|||
954 |
|
||||
955 | @property |
|
942 | @property | |
956 | def user_global_ns(self): |
|
943 | def user_global_ns(self): | |
957 | return self.user_module.__dict__ |
|
944 | return self.user_module.__dict__ | |
958 |
|
945 | |||
959 | def prepare_user_module(self, user_module=None): |
|
946 | def prepare_user_module(self, user_module=None): | |
960 | """Prepares a module for use as the interactive __main__ module in |
|
947 | """Prepares a module for use as the interactive __main__ module in | |
961 | which user code is run. |
|
948 | which user code is run. | |
962 |
|
949 | |||
963 | Parameters |
|
950 | Parameters | |
964 | ---------- |
|
951 | ---------- | |
965 | user_module : module, optional |
|
952 | user_module : module, optional | |
966 | The current user module in which IPython is being run. If None, |
|
953 | The current user module in which IPython is being run. If None, | |
967 | a clean module will be created. |
|
954 | a clean module will be created. | |
968 |
|
955 | |||
969 | Returns |
|
956 | Returns | |
970 | ------- |
|
957 | ------- | |
971 | A module object. |
|
958 | A module object. | |
972 | """ |
|
959 | """ | |
973 | if user_module is None: |
|
960 | if user_module is None: | |
974 | user_module = types.ModuleType("__main__", |
|
961 | user_module = types.ModuleType("__main__", | |
975 | doc="Automatically created module for IPython interactive environment") |
|
962 | doc="Automatically created module for IPython interactive environment") | |
976 |
|
963 | |||
977 | # We must ensure that __builtin__ (without the final 's') is always |
|
964 | # We must ensure that __builtin__ (without the final 's') is always | |
978 | # available and pointing to the __builtin__ *module*. For more details: |
|
965 | # available and pointing to the __builtin__ *module*. For more details: | |
979 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
966 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
980 | user_module.__dict__.setdefault('__builtin__',__builtin__) |
|
967 | user_module.__dict__.setdefault('__builtin__',__builtin__) | |
981 | user_module.__dict__.setdefault('__builtins__',__builtin__) |
|
968 | user_module.__dict__.setdefault('__builtins__',__builtin__) | |
982 |
|
969 | |||
983 | return user_module |
|
970 | return user_module | |
984 |
|
971 | |||
985 | def init_sys_modules(self): |
|
972 | def init_sys_modules(self): | |
986 | # We need to insert into sys.modules something that looks like a |
|
973 | # We need to insert into sys.modules something that looks like a | |
987 | # module but which accesses the IPython namespace, for shelve and |
|
974 | # module but which accesses the IPython namespace, for shelve and | |
988 | # pickle to work interactively. Normally they rely on getting |
|
975 | # pickle to work interactively. Normally they rely on getting | |
989 | # everything out of __main__, but for embedding purposes each IPython |
|
976 | # everything out of __main__, but for embedding purposes each IPython | |
990 | # instance has its own private namespace, so we can't go shoving |
|
977 | # instance has its own private namespace, so we can't go shoving | |
991 | # everything into __main__. |
|
978 | # everything into __main__. | |
992 |
|
979 | |||
993 | # note, however, that we should only do this for non-embedded |
|
980 | # note, however, that we should only do this for non-embedded | |
994 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
981 | # ipythons, which really mimic the __main__.__dict__ with their own | |
995 | # namespace. Embedded instances, on the other hand, should not do |
|
982 | # namespace. Embedded instances, on the other hand, should not do | |
996 | # this because they need to manage the user local/global namespaces |
|
983 | # this because they need to manage the user local/global namespaces | |
997 | # only, but they live within a 'normal' __main__ (meaning, they |
|
984 | # only, but they live within a 'normal' __main__ (meaning, they | |
998 | # shouldn't overtake the execution environment of the script they're |
|
985 | # shouldn't overtake the execution environment of the script they're | |
999 | # embedded in). |
|
986 | # embedded in). | |
1000 |
|
987 | |||
1001 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
988 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
1002 | main_name = self.user_module.__name__ |
|
989 | main_name = self.user_module.__name__ | |
1003 | sys.modules[main_name] = self.user_module |
|
990 | sys.modules[main_name] = self.user_module | |
1004 |
|
991 | |||
1005 | def init_user_ns(self): |
|
992 | def init_user_ns(self): | |
1006 | """Initialize all user-visible namespaces to their minimum defaults. |
|
993 | """Initialize all user-visible namespaces to their minimum defaults. | |
1007 |
|
994 | |||
1008 | Certain history lists are also initialized here, as they effectively |
|
995 | Certain history lists are also initialized here, as they effectively | |
1009 | act as user namespaces. |
|
996 | act as user namespaces. | |
1010 |
|
997 | |||
1011 | Notes |
|
998 | Notes | |
1012 | ----- |
|
999 | ----- | |
1013 | All data structures here are only filled in, they are NOT reset by this |
|
1000 | All data structures here are only filled in, they are NOT reset by this | |
1014 | method. If they were not empty before, data will simply be added to |
|
1001 | method. If they were not empty before, data will simply be added to | |
1015 | therm. |
|
1002 | therm. | |
1016 | """ |
|
1003 | """ | |
1017 | # This function works in two parts: first we put a few things in |
|
1004 | # This function works in two parts: first we put a few things in | |
1018 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1005 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
1019 | # initial variables aren't shown by %who. After the sync, we add the |
|
1006 | # initial variables aren't shown by %who. After the sync, we add the | |
1020 | # rest of what we *do* want the user to see with %who even on a new |
|
1007 | # rest of what we *do* want the user to see with %who even on a new | |
1021 | # session (probably nothing, so theye really only see their own stuff) |
|
1008 | # session (probably nothing, so theye really only see their own stuff) | |
1022 |
|
1009 | |||
1023 | # The user dict must *always* have a __builtin__ reference to the |
|
1010 | # The user dict must *always* have a __builtin__ reference to the | |
1024 | # Python standard __builtin__ namespace, which must be imported. |
|
1011 | # Python standard __builtin__ namespace, which must be imported. | |
1025 | # This is so that certain operations in prompt evaluation can be |
|
1012 | # This is so that certain operations in prompt evaluation can be | |
1026 | # reliably executed with builtins. Note that we can NOT use |
|
1013 | # reliably executed with builtins. Note that we can NOT use | |
1027 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1014 | # __builtins__ (note the 's'), because that can either be a dict or a | |
1028 | # module, and can even mutate at runtime, depending on the context |
|
1015 | # module, and can even mutate at runtime, depending on the context | |
1029 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1016 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1030 | # always a module object, though it must be explicitly imported. |
|
1017 | # always a module object, though it must be explicitly imported. | |
1031 |
|
1018 | |||
1032 | # For more details: |
|
1019 | # For more details: | |
1033 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1020 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1034 | ns = dict() |
|
1021 | ns = dict() | |
1035 |
|
1022 | |||
1036 | # Put 'help' in the user namespace |
|
1023 | # Put 'help' in the user namespace | |
1037 | try: |
|
1024 | try: | |
1038 | from site import _Helper |
|
1025 | from site import _Helper | |
1039 | ns['help'] = _Helper() |
|
1026 | ns['help'] = _Helper() | |
1040 | except ImportError: |
|
1027 | except ImportError: | |
1041 | warn('help() not available - check site.py') |
|
1028 | warn('help() not available - check site.py') | |
1042 |
|
1029 | |||
1043 | # make global variables for user access to the histories |
|
1030 | # make global variables for user access to the histories | |
1044 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1031 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1045 | ns['_oh'] = self.history_manager.output_hist |
|
1032 | ns['_oh'] = self.history_manager.output_hist | |
1046 | ns['_dh'] = self.history_manager.dir_hist |
|
1033 | ns['_dh'] = self.history_manager.dir_hist | |
1047 |
|
1034 | |||
1048 | ns['_sh'] = shadowns |
|
1035 | ns['_sh'] = shadowns | |
1049 |
|
1036 | |||
1050 | # user aliases to input and output histories. These shouldn't show up |
|
1037 | # user aliases to input and output histories. These shouldn't show up | |
1051 | # in %who, as they can have very large reprs. |
|
1038 | # in %who, as they can have very large reprs. | |
1052 | ns['In'] = self.history_manager.input_hist_parsed |
|
1039 | ns['In'] = self.history_manager.input_hist_parsed | |
1053 | ns['Out'] = self.history_manager.output_hist |
|
1040 | ns['Out'] = self.history_manager.output_hist | |
1054 |
|
1041 | |||
1055 | # Store myself as the public api!!! |
|
1042 | # Store myself as the public api!!! | |
1056 | ns['get_ipython'] = self.get_ipython |
|
1043 | ns['get_ipython'] = self.get_ipython | |
1057 |
|
1044 | |||
1058 | ns['exit'] = self.exiter |
|
1045 | ns['exit'] = self.exiter | |
1059 | ns['quit'] = self.exiter |
|
1046 | ns['quit'] = self.exiter | |
1060 |
|
1047 | |||
1061 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1048 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1062 | # by %who |
|
1049 | # by %who | |
1063 | self.user_ns_hidden.update(ns) |
|
1050 | self.user_ns_hidden.update(ns) | |
1064 |
|
1051 | |||
1065 | # Anything put into ns now would show up in %who. Think twice before |
|
1052 | # Anything put into ns now would show up in %who. Think twice before | |
1066 | # putting anything here, as we really want %who to show the user their |
|
1053 | # putting anything here, as we really want %who to show the user their | |
1067 | # stuff, not our variables. |
|
1054 | # stuff, not our variables. | |
1068 |
|
1055 | |||
1069 | # Finally, update the real user's namespace |
|
1056 | # Finally, update the real user's namespace | |
1070 | self.user_ns.update(ns) |
|
1057 | self.user_ns.update(ns) | |
1071 |
|
1058 | |||
1072 | def reset(self, new_session=True): |
|
1059 | def reset(self, new_session=True): | |
1073 | """Clear all internal namespaces, and attempt to release references to |
|
1060 | """Clear all internal namespaces, and attempt to release references to | |
1074 | user objects. |
|
1061 | user objects. | |
1075 |
|
1062 | |||
1076 | If new_session is True, a new history session will be opened. |
|
1063 | If new_session is True, a new history session will be opened. | |
1077 | """ |
|
1064 | """ | |
1078 | # Clear histories |
|
1065 | # Clear histories | |
1079 | self.history_manager.reset(new_session) |
|
1066 | self.history_manager.reset(new_session) | |
1080 | # Reset counter used to index all histories |
|
1067 | # Reset counter used to index all histories | |
1081 | if new_session: |
|
1068 | if new_session: | |
1082 | self.execution_count = 1 |
|
1069 | self.execution_count = 1 | |
1083 |
|
1070 | |||
1084 | # Flush cached output items |
|
1071 | # Flush cached output items | |
1085 | if self.displayhook.do_full_cache: |
|
1072 | if self.displayhook.do_full_cache: | |
1086 | self.displayhook.flush() |
|
1073 | self.displayhook.flush() | |
1087 |
|
1074 | |||
1088 | # Restore the user namespaces to minimal usability |
|
|||
1089 | for ns in self.ns_refs_table: |
|
|||
1090 | ns.clear() |
|
|||
1091 |
|
||||
1092 | # The main execution namespaces must be cleared very carefully, |
|
1075 | # The main execution namespaces must be cleared very carefully, | |
1093 | # skipping the deletion of the builtin-related keys, because doing so |
|
1076 | # skipping the deletion of the builtin-related keys, because doing so | |
1094 | # would cause errors in many object's __del__ methods. |
|
1077 | # would cause errors in many object's __del__ methods. | |
1095 | for ns in [self.user_ns, self.user_global_ns]: |
|
1078 | for ns in [self.user_ns, self.user_global_ns]: | |
1096 | drop_keys = set(ns.keys()) |
|
1079 | drop_keys = set(ns.keys()) | |
1097 | drop_keys.discard('__builtin__') |
|
1080 | drop_keys.discard('__builtin__') | |
1098 | drop_keys.discard('__builtins__') |
|
1081 | drop_keys.discard('__builtins__') | |
1099 | for k in drop_keys: |
|
1082 | for k in drop_keys: | |
1100 | del ns[k] |
|
1083 | del ns[k] | |
1101 |
|
1084 | |||
1102 | # Restore the user namespaces to minimal usability |
|
1085 | # Restore the user namespaces to minimal usability | |
1103 | self.init_user_ns() |
|
1086 | self.init_user_ns() | |
1104 |
|
1087 | |||
1105 | # Restore the default and user aliases |
|
1088 | # Restore the default and user aliases | |
1106 | self.alias_manager.clear_aliases() |
|
1089 | self.alias_manager.clear_aliases() | |
1107 | self.alias_manager.init_aliases() |
|
1090 | self.alias_manager.init_aliases() | |
1108 |
|
1091 | |||
1109 | # Flush the private list of module references kept for script |
|
1092 | # Flush the private list of module references kept for script | |
1110 | # execution protection |
|
1093 | # execution protection | |
1111 | self.clear_main_mod_cache() |
|
1094 | self.clear_main_mod_cache() | |
1112 |
|
1095 | |||
1113 | # Clear out the namespace from the last %run |
|
1096 | # Clear out the namespace from the last %run | |
1114 | self.new_main_mod() |
|
1097 | self.new_main_mod() | |
1115 |
|
1098 | |||
1116 | def del_var(self, varname, by_name=False): |
|
1099 | def del_var(self, varname, by_name=False): | |
1117 | """Delete a variable from the various namespaces, so that, as |
|
1100 | """Delete a variable from the various namespaces, so that, as | |
1118 | far as possible, we're not keeping any hidden references to it. |
|
1101 | far as possible, we're not keeping any hidden references to it. | |
1119 |
|
1102 | |||
1120 | Parameters |
|
1103 | Parameters | |
1121 | ---------- |
|
1104 | ---------- | |
1122 | varname : str |
|
1105 | varname : str | |
1123 | The name of the variable to delete. |
|
1106 | The name of the variable to delete. | |
1124 | by_name : bool |
|
1107 | by_name : bool | |
1125 | If True, delete variables with the given name in each |
|
1108 | If True, delete variables with the given name in each | |
1126 | namespace. If False (default), find the variable in the user |
|
1109 | namespace. If False (default), find the variable in the user | |
1127 | namespace, and delete references to it. |
|
1110 | namespace, and delete references to it. | |
1128 | """ |
|
1111 | """ | |
1129 | if varname in ('__builtin__', '__builtins__'): |
|
1112 | if varname in ('__builtin__', '__builtins__'): | |
1130 | raise ValueError("Refusing to delete %s" % varname) |
|
1113 | raise ValueError("Refusing to delete %s" % varname) | |
1131 | ns_refs = self.ns_refs_table + [self.user_ns, |
|
1114 | ||
1132 | self.user_global_ns, self._user_main_module.__dict__] +\ |
|
1115 | ns_refs = [self.user_ns, self.user_global_ns, | |
1133 | self._main_ns_cache.values() |
|
1116 | self._user_main_module.__dict__] + self._main_ns_cache.values() | |
1134 |
|
1117 | |||
1135 | if by_name: # Delete by name |
|
1118 | if by_name: # Delete by name | |
1136 | for ns in ns_refs: |
|
1119 | for ns in ns_refs: | |
1137 | try: |
|
1120 | try: | |
1138 | del ns[varname] |
|
1121 | del ns[varname] | |
1139 | except KeyError: |
|
1122 | except KeyError: | |
1140 | pass |
|
1123 | pass | |
1141 | else: # Delete by object |
|
1124 | else: # Delete by object | |
1142 | try: |
|
1125 | try: | |
1143 | obj = self.user_ns[varname] |
|
1126 | obj = self.user_ns[varname] | |
1144 | except KeyError: |
|
1127 | except KeyError: | |
1145 | raise NameError("name '%s' is not defined" % varname) |
|
1128 | raise NameError("name '%s' is not defined" % varname) | |
1146 | # Also check in output history |
|
1129 | # Also check in output history | |
1147 | ns_refs.append(self.history_manager.output_hist) |
|
1130 | ns_refs.append(self.history_manager.output_hist) | |
1148 | for ns in ns_refs: |
|
1131 | for ns in ns_refs: | |
1149 | to_delete = [n for n, o in ns.iteritems() if o is obj] |
|
1132 | to_delete = [n for n, o in ns.iteritems() if o is obj] | |
1150 | for name in to_delete: |
|
1133 | for name in to_delete: | |
1151 | del ns[name] |
|
1134 | del ns[name] | |
1152 |
|
1135 | |||
1153 | # displayhook keeps extra references, but not in a dictionary |
|
1136 | # displayhook keeps extra references, but not in a dictionary | |
1154 | for name in ('_', '__', '___'): |
|
1137 | for name in ('_', '__', '___'): | |
1155 | if getattr(self.displayhook, name) is obj: |
|
1138 | if getattr(self.displayhook, name) is obj: | |
1156 | setattr(self.displayhook, name, None) |
|
1139 | setattr(self.displayhook, name, None) | |
1157 |
|
1140 | |||
1158 | def reset_selective(self, regex=None): |
|
1141 | def reset_selective(self, regex=None): | |
1159 | """Clear selective variables from internal namespaces based on a |
|
1142 | """Clear selective variables from internal namespaces based on a | |
1160 | specified regular expression. |
|
1143 | specified regular expression. | |
1161 |
|
1144 | |||
1162 | Parameters |
|
1145 | Parameters | |
1163 | ---------- |
|
1146 | ---------- | |
1164 | regex : string or compiled pattern, optional |
|
1147 | regex : string or compiled pattern, optional | |
1165 | A regular expression pattern that will be used in searching |
|
1148 | A regular expression pattern that will be used in searching | |
1166 | variable names in the users namespaces. |
|
1149 | variable names in the users namespaces. | |
1167 | """ |
|
1150 | """ | |
1168 | if regex is not None: |
|
1151 | if regex is not None: | |
1169 | try: |
|
1152 | try: | |
1170 | m = re.compile(regex) |
|
1153 | m = re.compile(regex) | |
1171 | except TypeError: |
|
1154 | except TypeError: | |
1172 | raise TypeError('regex must be a string or compiled pattern') |
|
1155 | raise TypeError('regex must be a string or compiled pattern') | |
1173 | # Search for keys in each namespace that match the given regex |
|
1156 | # Search for keys in each namespace that match the given regex | |
1174 | # If a match is found, delete the key/value pair. |
|
1157 | # If a match is found, delete the key/value pair. | |
1175 |
for ns in self. |
|
1158 | for ns in [self.user_ns, self.user_global_ns]: | |
1176 | for var in ns: |
|
1159 | for var in ns: | |
1177 | if m.search(var): |
|
1160 | if m.search(var): | |
1178 | del ns[var] |
|
1161 | del ns[var] | |
1179 |
|
1162 | |||
1180 | def push(self, variables, interactive=True): |
|
1163 | def push(self, variables, interactive=True): | |
1181 | """Inject a group of variables into the IPython user namespace. |
|
1164 | """Inject a group of variables into the IPython user namespace. | |
1182 |
|
1165 | |||
1183 | Parameters |
|
1166 | Parameters | |
1184 | ---------- |
|
1167 | ---------- | |
1185 | variables : dict, str or list/tuple of str |
|
1168 | variables : dict, str or list/tuple of str | |
1186 | The variables to inject into the user's namespace. If a dict, a |
|
1169 | The variables to inject into the user's namespace. If a dict, a | |
1187 | simple update is done. If a str, the string is assumed to have |
|
1170 | simple update is done. If a str, the string is assumed to have | |
1188 | variable names separated by spaces. A list/tuple of str can also |
|
1171 | variable names separated by spaces. A list/tuple of str can also | |
1189 | be used to give the variable names. If just the variable names are |
|
1172 | be used to give the variable names. If just the variable names are | |
1190 | give (list/tuple/str) then the variable values looked up in the |
|
1173 | give (list/tuple/str) then the variable values looked up in the | |
1191 | callers frame. |
|
1174 | callers frame. | |
1192 | interactive : bool |
|
1175 | interactive : bool | |
1193 | If True (default), the variables will be listed with the ``who`` |
|
1176 | If True (default), the variables will be listed with the ``who`` | |
1194 | magic. |
|
1177 | magic. | |
1195 | """ |
|
1178 | """ | |
1196 | vdict = None |
|
1179 | vdict = None | |
1197 |
|
1180 | |||
1198 | # We need a dict of name/value pairs to do namespace updates. |
|
1181 | # We need a dict of name/value pairs to do namespace updates. | |
1199 | if isinstance(variables, dict): |
|
1182 | if isinstance(variables, dict): | |
1200 | vdict = variables |
|
1183 | vdict = variables | |
1201 | elif isinstance(variables, (basestring, list, tuple)): |
|
1184 | elif isinstance(variables, (basestring, list, tuple)): | |
1202 | if isinstance(variables, basestring): |
|
1185 | if isinstance(variables, basestring): | |
1203 | vlist = variables.split() |
|
1186 | vlist = variables.split() | |
1204 | else: |
|
1187 | else: | |
1205 | vlist = variables |
|
1188 | vlist = variables | |
1206 | vdict = {} |
|
1189 | vdict = {} | |
1207 | cf = sys._getframe(1) |
|
1190 | cf = sys._getframe(1) | |
1208 | for name in vlist: |
|
1191 | for name in vlist: | |
1209 | try: |
|
1192 | try: | |
1210 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1193 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1211 | except: |
|
1194 | except: | |
1212 | print ('Could not get variable %s from %s' % |
|
1195 | print ('Could not get variable %s from %s' % | |
1213 | (name,cf.f_code.co_name)) |
|
1196 | (name,cf.f_code.co_name)) | |
1214 | else: |
|
1197 | else: | |
1215 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1198 | raise ValueError('variables must be a dict/str/list/tuple') | |
1216 |
|
1199 | |||
1217 | # Propagate variables to user namespace |
|
1200 | # Propagate variables to user namespace | |
1218 | self.user_ns.update(vdict) |
|
1201 | self.user_ns.update(vdict) | |
1219 |
|
1202 | |||
1220 | # And configure interactive visibility |
|
1203 | # And configure interactive visibility | |
1221 | user_ns_hidden = self.user_ns_hidden |
|
1204 | user_ns_hidden = self.user_ns_hidden | |
1222 | if interactive: |
|
1205 | if interactive: | |
1223 | for name in vdict: |
|
1206 | for name in vdict: | |
1224 | user_ns_hidden.discard(name) |
|
1207 | user_ns_hidden.discard(name) | |
1225 | else: |
|
1208 | else: | |
1226 | for name in vdict: |
|
1209 | for name in vdict: | |
1227 | user_ns_hidden.add(name) |
|
1210 | user_ns_hidden.add(name) | |
1228 |
|
1211 | |||
1229 | def drop_by_id(self, variables): |
|
1212 | def drop_by_id(self, variables): | |
1230 | """Remove a dict of variables from the user namespace, if they are the |
|
1213 | """Remove a dict of variables from the user namespace, if they are the | |
1231 | same as the values in the dictionary. |
|
1214 | same as the values in the dictionary. | |
1232 |
|
1215 | |||
1233 | This is intended for use by extensions: variables that they've added can |
|
1216 | This is intended for use by extensions: variables that they've added can | |
1234 | be taken back out if they are unloaded, without removing any that the |
|
1217 | be taken back out if they are unloaded, without removing any that the | |
1235 | user has overwritten. |
|
1218 | user has overwritten. | |
1236 |
|
1219 | |||
1237 | Parameters |
|
1220 | Parameters | |
1238 | ---------- |
|
1221 | ---------- | |
1239 | variables : dict |
|
1222 | variables : dict | |
1240 | A dictionary mapping object names (as strings) to the objects. |
|
1223 | A dictionary mapping object names (as strings) to the objects. | |
1241 | """ |
|
1224 | """ | |
1242 | for name, obj in variables.iteritems(): |
|
1225 | for name, obj in variables.iteritems(): | |
1243 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1226 | if name in self.user_ns and self.user_ns[name] is obj: | |
1244 | del self.user_ns[name] |
|
1227 | del self.user_ns[name] | |
1245 | self.user_ns_hidden.discard(name) |
|
1228 | self.user_ns_hidden.discard(name) | |
1246 |
|
1229 | |||
1247 | #------------------------------------------------------------------------- |
|
1230 | #------------------------------------------------------------------------- | |
1248 | # Things related to object introspection |
|
1231 | # Things related to object introspection | |
1249 | #------------------------------------------------------------------------- |
|
1232 | #------------------------------------------------------------------------- | |
1250 |
|
1233 | |||
1251 | def _ofind(self, oname, namespaces=None): |
|
1234 | def _ofind(self, oname, namespaces=None): | |
1252 | """Find an object in the available namespaces. |
|
1235 | """Find an object in the available namespaces. | |
1253 |
|
1236 | |||
1254 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1237 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1255 |
|
1238 | |||
1256 | Has special code to detect magic functions. |
|
1239 | Has special code to detect magic functions. | |
1257 | """ |
|
1240 | """ | |
1258 | oname = oname.strip() |
|
1241 | oname = oname.strip() | |
1259 | #print '1- oname: <%r>' % oname # dbg |
|
1242 | #print '1- oname: <%r>' % oname # dbg | |
1260 | if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True): |
|
1243 | if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True): | |
1261 | return dict(found=False) |
|
1244 | return dict(found=False) | |
1262 |
|
1245 | |||
1263 | alias_ns = None |
|
1246 | alias_ns = None | |
1264 | if namespaces is None: |
|
1247 | if namespaces is None: | |
1265 | # Namespaces to search in: |
|
1248 | # Namespaces to search in: | |
1266 | # Put them in a list. The order is important so that we |
|
1249 | # Put them in a list. The order is important so that we | |
1267 | # find things in the same order that Python finds them. |
|
1250 | # find things in the same order that Python finds them. | |
1268 | namespaces = [ ('Interactive', self.user_ns), |
|
1251 | namespaces = [ ('Interactive', self.user_ns), | |
1269 |
('I |
|
1252 | ('Interactive (global)', self.user_global_ns), | |
1270 | ('Python builtin', builtin_mod.__dict__), |
|
1253 | ('Python builtin', builtin_mod.__dict__), | |
1271 | ('Alias', self.alias_manager.alias_table), |
|
1254 | ('Alias', self.alias_manager.alias_table), | |
1272 | ] |
|
1255 | ] | |
1273 | alias_ns = self.alias_manager.alias_table |
|
1256 | alias_ns = self.alias_manager.alias_table | |
1274 |
|
1257 | |||
1275 | # initialize results to 'null' |
|
1258 | # initialize results to 'null' | |
1276 | found = False; obj = None; ospace = None; ds = None; |
|
1259 | found = False; obj = None; ospace = None; ds = None; | |
1277 | ismagic = False; isalias = False; parent = None |
|
1260 | ismagic = False; isalias = False; parent = None | |
1278 |
|
1261 | |||
1279 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1262 | # We need to special-case 'print', which as of python2.6 registers as a | |
1280 | # function but should only be treated as one if print_function was |
|
1263 | # function but should only be treated as one if print_function was | |
1281 | # loaded with a future import. In this case, just bail. |
|
1264 | # loaded with a future import. In this case, just bail. | |
1282 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1265 | if (oname == 'print' and not py3compat.PY3 and not \ | |
1283 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1266 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1284 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1267 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1285 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1268 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1286 |
|
1269 | |||
1287 | # Look for the given name by splitting it in parts. If the head is |
|
1270 | # Look for the given name by splitting it in parts. If the head is | |
1288 | # found, then we look for all the remaining parts as members, and only |
|
1271 | # found, then we look for all the remaining parts as members, and only | |
1289 | # declare success if we can find them all. |
|
1272 | # declare success if we can find them all. | |
1290 | oname_parts = oname.split('.') |
|
1273 | oname_parts = oname.split('.') | |
1291 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1274 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1292 | for nsname,ns in namespaces: |
|
1275 | for nsname,ns in namespaces: | |
1293 | try: |
|
1276 | try: | |
1294 | obj = ns[oname_head] |
|
1277 | obj = ns[oname_head] | |
1295 | except KeyError: |
|
1278 | except KeyError: | |
1296 | continue |
|
1279 | continue | |
1297 | else: |
|
1280 | else: | |
1298 | #print 'oname_rest:', oname_rest # dbg |
|
1281 | #print 'oname_rest:', oname_rest # dbg | |
1299 | for part in oname_rest: |
|
1282 | for part in oname_rest: | |
1300 | try: |
|
1283 | try: | |
1301 | parent = obj |
|
1284 | parent = obj | |
1302 | obj = getattr(obj,part) |
|
1285 | obj = getattr(obj,part) | |
1303 | except: |
|
1286 | except: | |
1304 | # Blanket except b/c some badly implemented objects |
|
1287 | # Blanket except b/c some badly implemented objects | |
1305 | # allow __getattr__ to raise exceptions other than |
|
1288 | # allow __getattr__ to raise exceptions other than | |
1306 | # AttributeError, which then crashes IPython. |
|
1289 | # AttributeError, which then crashes IPython. | |
1307 | break |
|
1290 | break | |
1308 | else: |
|
1291 | else: | |
1309 | # If we finish the for loop (no break), we got all members |
|
1292 | # If we finish the for loop (no break), we got all members | |
1310 | found = True |
|
1293 | found = True | |
1311 | ospace = nsname |
|
1294 | ospace = nsname | |
1312 | if ns == alias_ns: |
|
1295 | if ns == alias_ns: | |
1313 | isalias = True |
|
1296 | isalias = True | |
1314 | break # namespace loop |
|
1297 | break # namespace loop | |
1315 |
|
1298 | |||
1316 | # Try to see if it's magic |
|
1299 | # Try to see if it's magic | |
1317 | if not found: |
|
1300 | if not found: | |
1318 | if oname.startswith(ESC_MAGIC): |
|
1301 | if oname.startswith(ESC_MAGIC): | |
1319 | oname = oname[1:] |
|
1302 | oname = oname[1:] | |
1320 | obj = getattr(self,'magic_'+oname,None) |
|
1303 | obj = getattr(self,'magic_'+oname,None) | |
1321 | if obj is not None: |
|
1304 | if obj is not None: | |
1322 | found = True |
|
1305 | found = True | |
1323 | ospace = 'IPython internal' |
|
1306 | ospace = 'IPython internal' | |
1324 | ismagic = True |
|
1307 | ismagic = True | |
1325 |
|
1308 | |||
1326 | # Last try: special-case some literals like '', [], {}, etc: |
|
1309 | # Last try: special-case some literals like '', [], {}, etc: | |
1327 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1310 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1328 | obj = eval(oname_head) |
|
1311 | obj = eval(oname_head) | |
1329 | found = True |
|
1312 | found = True | |
1330 | ospace = 'Interactive' |
|
1313 | ospace = 'Interactive' | |
1331 |
|
1314 | |||
1332 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1315 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1333 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1316 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1334 |
|
1317 | |||
1335 | def _ofind_property(self, oname, info): |
|
1318 | def _ofind_property(self, oname, info): | |
1336 | """Second part of object finding, to look for property details.""" |
|
1319 | """Second part of object finding, to look for property details.""" | |
1337 | if info.found: |
|
1320 | if info.found: | |
1338 | # Get the docstring of the class property if it exists. |
|
1321 | # Get the docstring of the class property if it exists. | |
1339 | path = oname.split('.') |
|
1322 | path = oname.split('.') | |
1340 | root = '.'.join(path[:-1]) |
|
1323 | root = '.'.join(path[:-1]) | |
1341 | if info.parent is not None: |
|
1324 | if info.parent is not None: | |
1342 | try: |
|
1325 | try: | |
1343 | target = getattr(info.parent, '__class__') |
|
1326 | target = getattr(info.parent, '__class__') | |
1344 | # The object belongs to a class instance. |
|
1327 | # The object belongs to a class instance. | |
1345 | try: |
|
1328 | try: | |
1346 | target = getattr(target, path[-1]) |
|
1329 | target = getattr(target, path[-1]) | |
1347 | # The class defines the object. |
|
1330 | # The class defines the object. | |
1348 | if isinstance(target, property): |
|
1331 | if isinstance(target, property): | |
1349 | oname = root + '.__class__.' + path[-1] |
|
1332 | oname = root + '.__class__.' + path[-1] | |
1350 | info = Struct(self._ofind(oname)) |
|
1333 | info = Struct(self._ofind(oname)) | |
1351 | except AttributeError: pass |
|
1334 | except AttributeError: pass | |
1352 | except AttributeError: pass |
|
1335 | except AttributeError: pass | |
1353 |
|
1336 | |||
1354 | # We return either the new info or the unmodified input if the object |
|
1337 | # We return either the new info or the unmodified input if the object | |
1355 | # hadn't been found |
|
1338 | # hadn't been found | |
1356 | return info |
|
1339 | return info | |
1357 |
|
1340 | |||
1358 | def _object_find(self, oname, namespaces=None): |
|
1341 | def _object_find(self, oname, namespaces=None): | |
1359 | """Find an object and return a struct with info about it.""" |
|
1342 | """Find an object and return a struct with info about it.""" | |
1360 | inf = Struct(self._ofind(oname, namespaces)) |
|
1343 | inf = Struct(self._ofind(oname, namespaces)) | |
1361 | return Struct(self._ofind_property(oname, inf)) |
|
1344 | return Struct(self._ofind_property(oname, inf)) | |
1362 |
|
1345 | |||
1363 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1346 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1364 | """Generic interface to the inspector system. |
|
1347 | """Generic interface to the inspector system. | |
1365 |
|
1348 | |||
1366 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1349 | This function is meant to be called by pdef, pdoc & friends.""" | |
1367 | info = self._object_find(oname) |
|
1350 | info = self._object_find(oname) | |
1368 | if info.found: |
|
1351 | if info.found: | |
1369 | pmethod = getattr(self.inspector, meth) |
|
1352 | pmethod = getattr(self.inspector, meth) | |
1370 | formatter = format_screen if info.ismagic else None |
|
1353 | formatter = format_screen if info.ismagic else None | |
1371 | if meth == 'pdoc': |
|
1354 | if meth == 'pdoc': | |
1372 | pmethod(info.obj, oname, formatter) |
|
1355 | pmethod(info.obj, oname, formatter) | |
1373 | elif meth == 'pinfo': |
|
1356 | elif meth == 'pinfo': | |
1374 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1357 | pmethod(info.obj, oname, formatter, info, **kw) | |
1375 | else: |
|
1358 | else: | |
1376 | pmethod(info.obj, oname) |
|
1359 | pmethod(info.obj, oname) | |
1377 | else: |
|
1360 | else: | |
1378 | print 'Object `%s` not found.' % oname |
|
1361 | print 'Object `%s` not found.' % oname | |
1379 | return 'not found' # so callers can take other action |
|
1362 | return 'not found' # so callers can take other action | |
1380 |
|
1363 | |||
1381 | def object_inspect(self, oname): |
|
1364 | def object_inspect(self, oname): | |
1382 | with self.builtin_trap: |
|
1365 | with self.builtin_trap: | |
1383 | info = self._object_find(oname) |
|
1366 | info = self._object_find(oname) | |
1384 | if info.found: |
|
1367 | if info.found: | |
1385 | return self.inspector.info(info.obj, oname, info=info) |
|
1368 | return self.inspector.info(info.obj, oname, info=info) | |
1386 | else: |
|
1369 | else: | |
1387 | return oinspect.object_info(name=oname, found=False) |
|
1370 | return oinspect.object_info(name=oname, found=False) | |
1388 |
|
1371 | |||
1389 | #------------------------------------------------------------------------- |
|
1372 | #------------------------------------------------------------------------- | |
1390 | # Things related to history management |
|
1373 | # Things related to history management | |
1391 | #------------------------------------------------------------------------- |
|
1374 | #------------------------------------------------------------------------- | |
1392 |
|
1375 | |||
1393 | def init_history(self): |
|
1376 | def init_history(self): | |
1394 | """Sets up the command history, and starts regular autosaves.""" |
|
1377 | """Sets up the command history, and starts regular autosaves.""" | |
1395 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1378 | self.history_manager = HistoryManager(shell=self, config=self.config) | |
1396 | self.configurables.append(self.history_manager) |
|
1379 | self.configurables.append(self.history_manager) | |
1397 |
|
1380 | |||
1398 | #------------------------------------------------------------------------- |
|
1381 | #------------------------------------------------------------------------- | |
1399 | # Things related to exception handling and tracebacks (not debugging) |
|
1382 | # Things related to exception handling and tracebacks (not debugging) | |
1400 | #------------------------------------------------------------------------- |
|
1383 | #------------------------------------------------------------------------- | |
1401 |
|
1384 | |||
1402 | def init_traceback_handlers(self, custom_exceptions): |
|
1385 | def init_traceback_handlers(self, custom_exceptions): | |
1403 | # Syntax error handler. |
|
1386 | # Syntax error handler. | |
1404 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1387 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1405 |
|
1388 | |||
1406 | # The interactive one is initialized with an offset, meaning we always |
|
1389 | # The interactive one is initialized with an offset, meaning we always | |
1407 | # want to remove the topmost item in the traceback, which is our own |
|
1390 | # want to remove the topmost item in the traceback, which is our own | |
1408 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1391 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1409 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1392 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1410 | color_scheme='NoColor', |
|
1393 | color_scheme='NoColor', | |
1411 | tb_offset = 1, |
|
1394 | tb_offset = 1, | |
1412 | check_cache=self.compile.check_cache) |
|
1395 | check_cache=self.compile.check_cache) | |
1413 |
|
1396 | |||
1414 | # The instance will store a pointer to the system-wide exception hook, |
|
1397 | # The instance will store a pointer to the system-wide exception hook, | |
1415 | # so that runtime code (such as magics) can access it. This is because |
|
1398 | # so that runtime code (such as magics) can access it. This is because | |
1416 | # during the read-eval loop, it may get temporarily overwritten. |
|
1399 | # during the read-eval loop, it may get temporarily overwritten. | |
1417 | self.sys_excepthook = sys.excepthook |
|
1400 | self.sys_excepthook = sys.excepthook | |
1418 |
|
1401 | |||
1419 | # and add any custom exception handlers the user may have specified |
|
1402 | # and add any custom exception handlers the user may have specified | |
1420 | self.set_custom_exc(*custom_exceptions) |
|
1403 | self.set_custom_exc(*custom_exceptions) | |
1421 |
|
1404 | |||
1422 | # Set the exception mode |
|
1405 | # Set the exception mode | |
1423 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1406 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1424 |
|
1407 | |||
1425 | def set_custom_exc(self, exc_tuple, handler): |
|
1408 | def set_custom_exc(self, exc_tuple, handler): | |
1426 | """set_custom_exc(exc_tuple,handler) |
|
1409 | """set_custom_exc(exc_tuple,handler) | |
1427 |
|
1410 | |||
1428 | Set a custom exception handler, which will be called if any of the |
|
1411 | Set a custom exception handler, which will be called if any of the | |
1429 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1412 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1430 | run_code() method). |
|
1413 | run_code() method). | |
1431 |
|
1414 | |||
1432 | Parameters |
|
1415 | Parameters | |
1433 | ---------- |
|
1416 | ---------- | |
1434 |
|
1417 | |||
1435 | exc_tuple : tuple of exception classes |
|
1418 | exc_tuple : tuple of exception classes | |
1436 | A *tuple* of exception classes, for which to call the defined |
|
1419 | A *tuple* of exception classes, for which to call the defined | |
1437 | handler. It is very important that you use a tuple, and NOT A |
|
1420 | handler. It is very important that you use a tuple, and NOT A | |
1438 | LIST here, because of the way Python's except statement works. If |
|
1421 | LIST here, because of the way Python's except statement works. If | |
1439 | you only want to trap a single exception, use a singleton tuple:: |
|
1422 | you only want to trap a single exception, use a singleton tuple:: | |
1440 |
|
1423 | |||
1441 | exc_tuple == (MyCustomException,) |
|
1424 | exc_tuple == (MyCustomException,) | |
1442 |
|
1425 | |||
1443 | handler : callable |
|
1426 | handler : callable | |
1444 | handler must have the following signature:: |
|
1427 | handler must have the following signature:: | |
1445 |
|
1428 | |||
1446 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1429 | def my_handler(self, etype, value, tb, tb_offset=None): | |
1447 | ... |
|
1430 | ... | |
1448 | return structured_traceback |
|
1431 | return structured_traceback | |
1449 |
|
1432 | |||
1450 | Your handler must return a structured traceback (a list of strings), |
|
1433 | Your handler must return a structured traceback (a list of strings), | |
1451 | or None. |
|
1434 | or None. | |
1452 |
|
1435 | |||
1453 | This will be made into an instance method (via types.MethodType) |
|
1436 | This will be made into an instance method (via types.MethodType) | |
1454 | of IPython itself, and it will be called if any of the exceptions |
|
1437 | of IPython itself, and it will be called if any of the exceptions | |
1455 | listed in the exc_tuple are caught. If the handler is None, an |
|
1438 | listed in the exc_tuple are caught. If the handler is None, an | |
1456 | internal basic one is used, which just prints basic info. |
|
1439 | internal basic one is used, which just prints basic info. | |
1457 |
|
1440 | |||
1458 | To protect IPython from crashes, if your handler ever raises an |
|
1441 | To protect IPython from crashes, if your handler ever raises an | |
1459 | exception or returns an invalid result, it will be immediately |
|
1442 | exception or returns an invalid result, it will be immediately | |
1460 | disabled. |
|
1443 | disabled. | |
1461 |
|
1444 | |||
1462 | WARNING: by putting in your own exception handler into IPython's main |
|
1445 | WARNING: by putting in your own exception handler into IPython's main | |
1463 | execution loop, you run a very good chance of nasty crashes. This |
|
1446 | execution loop, you run a very good chance of nasty crashes. This | |
1464 | facility should only be used if you really know what you are doing.""" |
|
1447 | facility should only be used if you really know what you are doing.""" | |
1465 |
|
1448 | |||
1466 | assert type(exc_tuple)==type(()) , \ |
|
1449 | assert type(exc_tuple)==type(()) , \ | |
1467 | "The custom exceptions must be given AS A TUPLE." |
|
1450 | "The custom exceptions must be given AS A TUPLE." | |
1468 |
|
1451 | |||
1469 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1452 | def dummy_handler(self,etype,value,tb,tb_offset=None): | |
1470 | print '*** Simple custom exception handler ***' |
|
1453 | print '*** Simple custom exception handler ***' | |
1471 | print 'Exception type :',etype |
|
1454 | print 'Exception type :',etype | |
1472 | print 'Exception value:',value |
|
1455 | print 'Exception value:',value | |
1473 | print 'Traceback :',tb |
|
1456 | print 'Traceback :',tb | |
1474 | #print 'Source code :','\n'.join(self.buffer) |
|
1457 | #print 'Source code :','\n'.join(self.buffer) | |
1475 |
|
1458 | |||
1476 | def validate_stb(stb): |
|
1459 | def validate_stb(stb): | |
1477 | """validate structured traceback return type |
|
1460 | """validate structured traceback return type | |
1478 |
|
1461 | |||
1479 | return type of CustomTB *should* be a list of strings, but allow |
|
1462 | return type of CustomTB *should* be a list of strings, but allow | |
1480 | single strings or None, which are harmless. |
|
1463 | single strings or None, which are harmless. | |
1481 |
|
1464 | |||
1482 | This function will *always* return a list of strings, |
|
1465 | This function will *always* return a list of strings, | |
1483 | and will raise a TypeError if stb is inappropriate. |
|
1466 | and will raise a TypeError if stb is inappropriate. | |
1484 | """ |
|
1467 | """ | |
1485 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1468 | msg = "CustomTB must return list of strings, not %r" % stb | |
1486 | if stb is None: |
|
1469 | if stb is None: | |
1487 | return [] |
|
1470 | return [] | |
1488 | elif isinstance(stb, basestring): |
|
1471 | elif isinstance(stb, basestring): | |
1489 | return [stb] |
|
1472 | return [stb] | |
1490 | elif not isinstance(stb, list): |
|
1473 | elif not isinstance(stb, list): | |
1491 | raise TypeError(msg) |
|
1474 | raise TypeError(msg) | |
1492 | # it's a list |
|
1475 | # it's a list | |
1493 | for line in stb: |
|
1476 | for line in stb: | |
1494 | # check every element |
|
1477 | # check every element | |
1495 | if not isinstance(line, basestring): |
|
1478 | if not isinstance(line, basestring): | |
1496 | raise TypeError(msg) |
|
1479 | raise TypeError(msg) | |
1497 | return stb |
|
1480 | return stb | |
1498 |
|
1481 | |||
1499 | if handler is None: |
|
1482 | if handler is None: | |
1500 | wrapped = dummy_handler |
|
1483 | wrapped = dummy_handler | |
1501 | else: |
|
1484 | else: | |
1502 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1485 | def wrapped(self,etype,value,tb,tb_offset=None): | |
1503 | """wrap CustomTB handler, to protect IPython from user code |
|
1486 | """wrap CustomTB handler, to protect IPython from user code | |
1504 |
|
1487 | |||
1505 | This makes it harder (but not impossible) for custom exception |
|
1488 | This makes it harder (but not impossible) for custom exception | |
1506 | handlers to crash IPython. |
|
1489 | handlers to crash IPython. | |
1507 | """ |
|
1490 | """ | |
1508 | try: |
|
1491 | try: | |
1509 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1492 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) | |
1510 | return validate_stb(stb) |
|
1493 | return validate_stb(stb) | |
1511 | except: |
|
1494 | except: | |
1512 | # clear custom handler immediately |
|
1495 | # clear custom handler immediately | |
1513 | self.set_custom_exc((), None) |
|
1496 | self.set_custom_exc((), None) | |
1514 | print >> io.stderr, "Custom TB Handler failed, unregistering" |
|
1497 | print >> io.stderr, "Custom TB Handler failed, unregistering" | |
1515 | # show the exception in handler first |
|
1498 | # show the exception in handler first | |
1516 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1499 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) | |
1517 | print >> io.stdout, self.InteractiveTB.stb2text(stb) |
|
1500 | print >> io.stdout, self.InteractiveTB.stb2text(stb) | |
1518 | print >> io.stdout, "The original exception:" |
|
1501 | print >> io.stdout, "The original exception:" | |
1519 | stb = self.InteractiveTB.structured_traceback( |
|
1502 | stb = self.InteractiveTB.structured_traceback( | |
1520 | (etype,value,tb), tb_offset=tb_offset |
|
1503 | (etype,value,tb), tb_offset=tb_offset | |
1521 | ) |
|
1504 | ) | |
1522 | return stb |
|
1505 | return stb | |
1523 |
|
1506 | |||
1524 | self.CustomTB = types.MethodType(wrapped,self) |
|
1507 | self.CustomTB = types.MethodType(wrapped,self) | |
1525 | self.custom_exceptions = exc_tuple |
|
1508 | self.custom_exceptions = exc_tuple | |
1526 |
|
1509 | |||
1527 | def excepthook(self, etype, value, tb): |
|
1510 | def excepthook(self, etype, value, tb): | |
1528 | """One more defense for GUI apps that call sys.excepthook. |
|
1511 | """One more defense for GUI apps that call sys.excepthook. | |
1529 |
|
1512 | |||
1530 | GUI frameworks like wxPython trap exceptions and call |
|
1513 | GUI frameworks like wxPython trap exceptions and call | |
1531 | sys.excepthook themselves. I guess this is a feature that |
|
1514 | sys.excepthook themselves. I guess this is a feature that | |
1532 | enables them to keep running after exceptions that would |
|
1515 | enables them to keep running after exceptions that would | |
1533 | otherwise kill their mainloop. This is a bother for IPython |
|
1516 | otherwise kill their mainloop. This is a bother for IPython | |
1534 | which excepts to catch all of the program exceptions with a try: |
|
1517 | which excepts to catch all of the program exceptions with a try: | |
1535 | except: statement. |
|
1518 | except: statement. | |
1536 |
|
1519 | |||
1537 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1520 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1538 | any app directly invokes sys.excepthook, it will look to the user like |
|
1521 | any app directly invokes sys.excepthook, it will look to the user like | |
1539 | IPython crashed. In order to work around this, we can disable the |
|
1522 | IPython crashed. In order to work around this, we can disable the | |
1540 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1523 | CrashHandler and replace it with this excepthook instead, which prints a | |
1541 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1524 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1542 | call sys.excepthook will generate a regular-looking exception from |
|
1525 | call sys.excepthook will generate a regular-looking exception from | |
1543 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1526 | IPython, and the CrashHandler will only be triggered by real IPython | |
1544 | crashes. |
|
1527 | crashes. | |
1545 |
|
1528 | |||
1546 | This hook should be used sparingly, only in places which are not likely |
|
1529 | This hook should be used sparingly, only in places which are not likely | |
1547 | to be true IPython errors. |
|
1530 | to be true IPython errors. | |
1548 | """ |
|
1531 | """ | |
1549 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1532 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1550 |
|
1533 | |||
1551 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1534 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1552 | exception_only=False): |
|
1535 | exception_only=False): | |
1553 | """Display the exception that just occurred. |
|
1536 | """Display the exception that just occurred. | |
1554 |
|
1537 | |||
1555 | If nothing is known about the exception, this is the method which |
|
1538 | If nothing is known about the exception, this is the method which | |
1556 | should be used throughout the code for presenting user tracebacks, |
|
1539 | should be used throughout the code for presenting user tracebacks, | |
1557 | rather than directly invoking the InteractiveTB object. |
|
1540 | rather than directly invoking the InteractiveTB object. | |
1558 |
|
1541 | |||
1559 | A specific showsyntaxerror() also exists, but this method can take |
|
1542 | A specific showsyntaxerror() also exists, but this method can take | |
1560 | care of calling it if needed, so unless you are explicitly catching a |
|
1543 | care of calling it if needed, so unless you are explicitly catching a | |
1561 | SyntaxError exception, don't try to analyze the stack manually and |
|
1544 | SyntaxError exception, don't try to analyze the stack manually and | |
1562 | simply call this method.""" |
|
1545 | simply call this method.""" | |
1563 |
|
1546 | |||
1564 | try: |
|
1547 | try: | |
1565 | if exc_tuple is None: |
|
1548 | if exc_tuple is None: | |
1566 | etype, value, tb = sys.exc_info() |
|
1549 | etype, value, tb = sys.exc_info() | |
1567 | else: |
|
1550 | else: | |
1568 | etype, value, tb = exc_tuple |
|
1551 | etype, value, tb = exc_tuple | |
1569 |
|
1552 | |||
1570 | if etype is None: |
|
1553 | if etype is None: | |
1571 | if hasattr(sys, 'last_type'): |
|
1554 | if hasattr(sys, 'last_type'): | |
1572 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1555 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1573 | sys.last_traceback |
|
1556 | sys.last_traceback | |
1574 | else: |
|
1557 | else: | |
1575 | self.write_err('No traceback available to show.\n') |
|
1558 | self.write_err('No traceback available to show.\n') | |
1576 | return |
|
1559 | return | |
1577 |
|
1560 | |||
1578 | if etype is SyntaxError: |
|
1561 | if etype is SyntaxError: | |
1579 | # Though this won't be called by syntax errors in the input |
|
1562 | # Though this won't be called by syntax errors in the input | |
1580 | # line, there may be SyntaxError cases with imported code. |
|
1563 | # line, there may be SyntaxError cases with imported code. | |
1581 | self.showsyntaxerror(filename) |
|
1564 | self.showsyntaxerror(filename) | |
1582 | elif etype is UsageError: |
|
1565 | elif etype is UsageError: | |
1583 | self.write_err("UsageError: %s" % value) |
|
1566 | self.write_err("UsageError: %s" % value) | |
1584 | else: |
|
1567 | else: | |
1585 | # WARNING: these variables are somewhat deprecated and not |
|
1568 | # WARNING: these variables are somewhat deprecated and not | |
1586 | # necessarily safe to use in a threaded environment, but tools |
|
1569 | # necessarily safe to use in a threaded environment, but tools | |
1587 | # like pdb depend on their existence, so let's set them. If we |
|
1570 | # like pdb depend on their existence, so let's set them. If we | |
1588 | # find problems in the field, we'll need to revisit their use. |
|
1571 | # find problems in the field, we'll need to revisit their use. | |
1589 | sys.last_type = etype |
|
1572 | sys.last_type = etype | |
1590 | sys.last_value = value |
|
1573 | sys.last_value = value | |
1591 | sys.last_traceback = tb |
|
1574 | sys.last_traceback = tb | |
1592 | if etype in self.custom_exceptions: |
|
1575 | if etype in self.custom_exceptions: | |
1593 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1576 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1594 | else: |
|
1577 | else: | |
1595 | if exception_only: |
|
1578 | if exception_only: | |
1596 | stb = ['An exception has occurred, use %tb to see ' |
|
1579 | stb = ['An exception has occurred, use %tb to see ' | |
1597 | 'the full traceback.\n'] |
|
1580 | 'the full traceback.\n'] | |
1598 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1581 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1599 | value)) |
|
1582 | value)) | |
1600 | else: |
|
1583 | else: | |
1601 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1584 | stb = self.InteractiveTB.structured_traceback(etype, | |
1602 | value, tb, tb_offset=tb_offset) |
|
1585 | value, tb, tb_offset=tb_offset) | |
1603 |
|
1586 | |||
1604 | self._showtraceback(etype, value, stb) |
|
1587 | self._showtraceback(etype, value, stb) | |
1605 | if self.call_pdb: |
|
1588 | if self.call_pdb: | |
1606 | # drop into debugger |
|
1589 | # drop into debugger | |
1607 | self.debugger(force=True) |
|
1590 | self.debugger(force=True) | |
1608 | return |
|
1591 | return | |
1609 |
|
1592 | |||
1610 | # Actually show the traceback |
|
1593 | # Actually show the traceback | |
1611 | self._showtraceback(etype, value, stb) |
|
1594 | self._showtraceback(etype, value, stb) | |
1612 |
|
1595 | |||
1613 | except KeyboardInterrupt: |
|
1596 | except KeyboardInterrupt: | |
1614 | self.write_err("\nKeyboardInterrupt\n") |
|
1597 | self.write_err("\nKeyboardInterrupt\n") | |
1615 |
|
1598 | |||
1616 | def _showtraceback(self, etype, evalue, stb): |
|
1599 | def _showtraceback(self, etype, evalue, stb): | |
1617 | """Actually show a traceback. |
|
1600 | """Actually show a traceback. | |
1618 |
|
1601 | |||
1619 | Subclasses may override this method to put the traceback on a different |
|
1602 | Subclasses may override this method to put the traceback on a different | |
1620 | place, like a side channel. |
|
1603 | place, like a side channel. | |
1621 | """ |
|
1604 | """ | |
1622 | print >> io.stdout, self.InteractiveTB.stb2text(stb) |
|
1605 | print >> io.stdout, self.InteractiveTB.stb2text(stb) | |
1623 |
|
1606 | |||
1624 | def showsyntaxerror(self, filename=None): |
|
1607 | def showsyntaxerror(self, filename=None): | |
1625 | """Display the syntax error that just occurred. |
|
1608 | """Display the syntax error that just occurred. | |
1626 |
|
1609 | |||
1627 | This doesn't display a stack trace because there isn't one. |
|
1610 | This doesn't display a stack trace because there isn't one. | |
1628 |
|
1611 | |||
1629 | If a filename is given, it is stuffed in the exception instead |
|
1612 | If a filename is given, it is stuffed in the exception instead | |
1630 | of what was there before (because Python's parser always uses |
|
1613 | of what was there before (because Python's parser always uses | |
1631 | "<string>" when reading from a string). |
|
1614 | "<string>" when reading from a string). | |
1632 | """ |
|
1615 | """ | |
1633 | etype, value, last_traceback = sys.exc_info() |
|
1616 | etype, value, last_traceback = sys.exc_info() | |
1634 |
|
1617 | |||
1635 | # See note about these variables in showtraceback() above |
|
1618 | # See note about these variables in showtraceback() above | |
1636 | sys.last_type = etype |
|
1619 | sys.last_type = etype | |
1637 | sys.last_value = value |
|
1620 | sys.last_value = value | |
1638 | sys.last_traceback = last_traceback |
|
1621 | sys.last_traceback = last_traceback | |
1639 |
|
1622 | |||
1640 | if filename and etype is SyntaxError: |
|
1623 | if filename and etype is SyntaxError: | |
1641 | # Work hard to stuff the correct filename in the exception |
|
1624 | # Work hard to stuff the correct filename in the exception | |
1642 | try: |
|
1625 | try: | |
1643 | msg, (dummy_filename, lineno, offset, line) = value |
|
1626 | msg, (dummy_filename, lineno, offset, line) = value | |
1644 | except: |
|
1627 | except: | |
1645 | # Not the format we expect; leave it alone |
|
1628 | # Not the format we expect; leave it alone | |
1646 | pass |
|
1629 | pass | |
1647 | else: |
|
1630 | else: | |
1648 | # Stuff in the right filename |
|
1631 | # Stuff in the right filename | |
1649 | try: |
|
1632 | try: | |
1650 | # Assume SyntaxError is a class exception |
|
1633 | # Assume SyntaxError is a class exception | |
1651 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1634 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1652 | except: |
|
1635 | except: | |
1653 | # If that failed, assume SyntaxError is a string |
|
1636 | # If that failed, assume SyntaxError is a string | |
1654 | value = msg, (filename, lineno, offset, line) |
|
1637 | value = msg, (filename, lineno, offset, line) | |
1655 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1638 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1656 | self._showtraceback(etype, value, stb) |
|
1639 | self._showtraceback(etype, value, stb) | |
1657 |
|
1640 | |||
1658 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1641 | # This is overridden in TerminalInteractiveShell to show a message about | |
1659 | # the %paste magic. |
|
1642 | # the %paste magic. | |
1660 | def showindentationerror(self): |
|
1643 | def showindentationerror(self): | |
1661 | """Called by run_cell when there's an IndentationError in code entered |
|
1644 | """Called by run_cell when there's an IndentationError in code entered | |
1662 | at the prompt. |
|
1645 | at the prompt. | |
1663 |
|
1646 | |||
1664 | This is overridden in TerminalInteractiveShell to show a message about |
|
1647 | This is overridden in TerminalInteractiveShell to show a message about | |
1665 | the %paste magic.""" |
|
1648 | the %paste magic.""" | |
1666 | self.showsyntaxerror() |
|
1649 | self.showsyntaxerror() | |
1667 |
|
1650 | |||
1668 | #------------------------------------------------------------------------- |
|
1651 | #------------------------------------------------------------------------- | |
1669 | # Things related to readline |
|
1652 | # Things related to readline | |
1670 | #------------------------------------------------------------------------- |
|
1653 | #------------------------------------------------------------------------- | |
1671 |
|
1654 | |||
1672 | def init_readline(self): |
|
1655 | def init_readline(self): | |
1673 | """Command history completion/saving/reloading.""" |
|
1656 | """Command history completion/saving/reloading.""" | |
1674 |
|
1657 | |||
1675 | if self.readline_use: |
|
1658 | if self.readline_use: | |
1676 | import IPython.utils.rlineimpl as readline |
|
1659 | import IPython.utils.rlineimpl as readline | |
1677 |
|
1660 | |||
1678 | self.rl_next_input = None |
|
1661 | self.rl_next_input = None | |
1679 | self.rl_do_indent = False |
|
1662 | self.rl_do_indent = False | |
1680 |
|
1663 | |||
1681 | if not self.readline_use or not readline.have_readline: |
|
1664 | if not self.readline_use or not readline.have_readline: | |
1682 | self.has_readline = False |
|
1665 | self.has_readline = False | |
1683 | self.readline = None |
|
1666 | self.readline = None | |
1684 | # Set a number of methods that depend on readline to be no-op |
|
1667 | # Set a number of methods that depend on readline to be no-op | |
1685 | self.readline_no_record = no_op_context |
|
1668 | self.readline_no_record = no_op_context | |
1686 | self.set_readline_completer = no_op |
|
1669 | self.set_readline_completer = no_op | |
1687 | self.set_custom_completer = no_op |
|
1670 | self.set_custom_completer = no_op | |
1688 | self.set_completer_frame = no_op |
|
1671 | self.set_completer_frame = no_op | |
1689 | if self.readline_use: |
|
1672 | if self.readline_use: | |
1690 | warn('Readline services not available or not loaded.') |
|
1673 | warn('Readline services not available or not loaded.') | |
1691 | else: |
|
1674 | else: | |
1692 | self.has_readline = True |
|
1675 | self.has_readline = True | |
1693 | self.readline = readline |
|
1676 | self.readline = readline | |
1694 | sys.modules['readline'] = readline |
|
1677 | sys.modules['readline'] = readline | |
1695 |
|
1678 | |||
1696 | # Platform-specific configuration |
|
1679 | # Platform-specific configuration | |
1697 | if os.name == 'nt': |
|
1680 | if os.name == 'nt': | |
1698 | # FIXME - check with Frederick to see if we can harmonize |
|
1681 | # FIXME - check with Frederick to see if we can harmonize | |
1699 | # naming conventions with pyreadline to avoid this |
|
1682 | # naming conventions with pyreadline to avoid this | |
1700 | # platform-dependent check |
|
1683 | # platform-dependent check | |
1701 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1684 | self.readline_startup_hook = readline.set_pre_input_hook | |
1702 | else: |
|
1685 | else: | |
1703 | self.readline_startup_hook = readline.set_startup_hook |
|
1686 | self.readline_startup_hook = readline.set_startup_hook | |
1704 |
|
1687 | |||
1705 | # Load user's initrc file (readline config) |
|
1688 | # Load user's initrc file (readline config) | |
1706 | # Or if libedit is used, load editrc. |
|
1689 | # Or if libedit is used, load editrc. | |
1707 | inputrc_name = os.environ.get('INPUTRC') |
|
1690 | inputrc_name = os.environ.get('INPUTRC') | |
1708 | if inputrc_name is None: |
|
1691 | if inputrc_name is None: | |
1709 | inputrc_name = '.inputrc' |
|
1692 | inputrc_name = '.inputrc' | |
1710 | if readline.uses_libedit: |
|
1693 | if readline.uses_libedit: | |
1711 | inputrc_name = '.editrc' |
|
1694 | inputrc_name = '.editrc' | |
1712 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1695 | inputrc_name = os.path.join(self.home_dir, inputrc_name) | |
1713 | if os.path.isfile(inputrc_name): |
|
1696 | if os.path.isfile(inputrc_name): | |
1714 | try: |
|
1697 | try: | |
1715 | readline.read_init_file(inputrc_name) |
|
1698 | readline.read_init_file(inputrc_name) | |
1716 | except: |
|
1699 | except: | |
1717 | warn('Problems reading readline initialization file <%s>' |
|
1700 | warn('Problems reading readline initialization file <%s>' | |
1718 | % inputrc_name) |
|
1701 | % inputrc_name) | |
1719 |
|
1702 | |||
1720 | # Configure readline according to user's prefs |
|
1703 | # Configure readline according to user's prefs | |
1721 | # This is only done if GNU readline is being used. If libedit |
|
1704 | # This is only done if GNU readline is being used. If libedit | |
1722 | # is being used (as on Leopard) the readline config is |
|
1705 | # is being used (as on Leopard) the readline config is | |
1723 | # not run as the syntax for libedit is different. |
|
1706 | # not run as the syntax for libedit is different. | |
1724 | if not readline.uses_libedit: |
|
1707 | if not readline.uses_libedit: | |
1725 | for rlcommand in self.readline_parse_and_bind: |
|
1708 | for rlcommand in self.readline_parse_and_bind: | |
1726 | #print "loading rl:",rlcommand # dbg |
|
1709 | #print "loading rl:",rlcommand # dbg | |
1727 | readline.parse_and_bind(rlcommand) |
|
1710 | readline.parse_and_bind(rlcommand) | |
1728 |
|
1711 | |||
1729 | # Remove some chars from the delimiters list. If we encounter |
|
1712 | # Remove some chars from the delimiters list. If we encounter | |
1730 | # unicode chars, discard them. |
|
1713 | # unicode chars, discard them. | |
1731 | delims = readline.get_completer_delims() |
|
1714 | delims = readline.get_completer_delims() | |
1732 | if not py3compat.PY3: |
|
1715 | if not py3compat.PY3: | |
1733 | delims = delims.encode("ascii", "ignore") |
|
1716 | delims = delims.encode("ascii", "ignore") | |
1734 | for d in self.readline_remove_delims: |
|
1717 | for d in self.readline_remove_delims: | |
1735 | delims = delims.replace(d, "") |
|
1718 | delims = delims.replace(d, "") | |
1736 | delims = delims.replace(ESC_MAGIC, '') |
|
1719 | delims = delims.replace(ESC_MAGIC, '') | |
1737 | readline.set_completer_delims(delims) |
|
1720 | readline.set_completer_delims(delims) | |
1738 | # otherwise we end up with a monster history after a while: |
|
1721 | # otherwise we end up with a monster history after a while: | |
1739 | readline.set_history_length(self.history_length) |
|
1722 | readline.set_history_length(self.history_length) | |
1740 |
|
1723 | |||
1741 | self.refill_readline_hist() |
|
1724 | self.refill_readline_hist() | |
1742 | self.readline_no_record = ReadlineNoRecord(self) |
|
1725 | self.readline_no_record = ReadlineNoRecord(self) | |
1743 |
|
1726 | |||
1744 | # Configure auto-indent for all platforms |
|
1727 | # Configure auto-indent for all platforms | |
1745 | self.set_autoindent(self.autoindent) |
|
1728 | self.set_autoindent(self.autoindent) | |
1746 |
|
1729 | |||
1747 | def refill_readline_hist(self): |
|
1730 | def refill_readline_hist(self): | |
1748 | # Load the last 1000 lines from history |
|
1731 | # Load the last 1000 lines from history | |
1749 | self.readline.clear_history() |
|
1732 | self.readline.clear_history() | |
1750 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1733 | stdin_encoding = sys.stdin.encoding or "utf-8" | |
1751 | last_cell = u"" |
|
1734 | last_cell = u"" | |
1752 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1735 | for _, _, cell in self.history_manager.get_tail(1000, | |
1753 | include_latest=True): |
|
1736 | include_latest=True): | |
1754 | # Ignore blank lines and consecutive duplicates |
|
1737 | # Ignore blank lines and consecutive duplicates | |
1755 | cell = cell.rstrip() |
|
1738 | cell = cell.rstrip() | |
1756 | if cell and (cell != last_cell): |
|
1739 | if cell and (cell != last_cell): | |
1757 | if self.multiline_history: |
|
1740 | if self.multiline_history: | |
1758 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
1741 | self.readline.add_history(py3compat.unicode_to_str(cell, | |
1759 | stdin_encoding)) |
|
1742 | stdin_encoding)) | |
1760 | else: |
|
1743 | else: | |
1761 | for line in cell.splitlines(): |
|
1744 | for line in cell.splitlines(): | |
1762 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
1745 | self.readline.add_history(py3compat.unicode_to_str(line, | |
1763 | stdin_encoding)) |
|
1746 | stdin_encoding)) | |
1764 | last_cell = cell |
|
1747 | last_cell = cell | |
1765 |
|
1748 | |||
1766 | def set_next_input(self, s): |
|
1749 | def set_next_input(self, s): | |
1767 | """ Sets the 'default' input string for the next command line. |
|
1750 | """ Sets the 'default' input string for the next command line. | |
1768 |
|
1751 | |||
1769 | Requires readline. |
|
1752 | Requires readline. | |
1770 |
|
1753 | |||
1771 | Example: |
|
1754 | Example: | |
1772 |
|
1755 | |||
1773 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1756 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1774 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1757 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1775 | """ |
|
1758 | """ | |
1776 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1759 | self.rl_next_input = py3compat.cast_bytes_py2(s) | |
1777 |
|
1760 | |||
1778 | # Maybe move this to the terminal subclass? |
|
1761 | # Maybe move this to the terminal subclass? | |
1779 | def pre_readline(self): |
|
1762 | def pre_readline(self): | |
1780 | """readline hook to be used at the start of each line. |
|
1763 | """readline hook to be used at the start of each line. | |
1781 |
|
1764 | |||
1782 | Currently it handles auto-indent only.""" |
|
1765 | Currently it handles auto-indent only.""" | |
1783 |
|
1766 | |||
1784 | if self.rl_do_indent: |
|
1767 | if self.rl_do_indent: | |
1785 | self.readline.insert_text(self._indent_current_str()) |
|
1768 | self.readline.insert_text(self._indent_current_str()) | |
1786 | if self.rl_next_input is not None: |
|
1769 | if self.rl_next_input is not None: | |
1787 | self.readline.insert_text(self.rl_next_input) |
|
1770 | self.readline.insert_text(self.rl_next_input) | |
1788 | self.rl_next_input = None |
|
1771 | self.rl_next_input = None | |
1789 |
|
1772 | |||
1790 | def _indent_current_str(self): |
|
1773 | def _indent_current_str(self): | |
1791 | """return the current level of indentation as a string""" |
|
1774 | """return the current level of indentation as a string""" | |
1792 | return self.input_splitter.indent_spaces * ' ' |
|
1775 | return self.input_splitter.indent_spaces * ' ' | |
1793 |
|
1776 | |||
1794 | #------------------------------------------------------------------------- |
|
1777 | #------------------------------------------------------------------------- | |
1795 | # Things related to text completion |
|
1778 | # Things related to text completion | |
1796 | #------------------------------------------------------------------------- |
|
1779 | #------------------------------------------------------------------------- | |
1797 |
|
1780 | |||
1798 | def init_completer(self): |
|
1781 | def init_completer(self): | |
1799 | """Initialize the completion machinery. |
|
1782 | """Initialize the completion machinery. | |
1800 |
|
1783 | |||
1801 | This creates completion machinery that can be used by client code, |
|
1784 | This creates completion machinery that can be used by client code, | |
1802 | either interactively in-process (typically triggered by the readline |
|
1785 | either interactively in-process (typically triggered by the readline | |
1803 | library), programatically (such as in test suites) or out-of-prcess |
|
1786 | library), programatically (such as in test suites) or out-of-prcess | |
1804 | (typically over the network by remote frontends). |
|
1787 | (typically over the network by remote frontends). | |
1805 | """ |
|
1788 | """ | |
1806 | from IPython.core.completer import IPCompleter |
|
1789 | from IPython.core.completer import IPCompleter | |
1807 | from IPython.core.completerlib import (module_completer, |
|
1790 | from IPython.core.completerlib import (module_completer, | |
1808 | magic_run_completer, cd_completer) |
|
1791 | magic_run_completer, cd_completer) | |
1809 |
|
1792 | |||
1810 | self.Completer = IPCompleter(shell=self, |
|
1793 | self.Completer = IPCompleter(shell=self, | |
1811 | namespace=self.user_ns, |
|
1794 | namespace=self.user_ns, | |
1812 | global_namespace=self.user_global_ns, |
|
1795 | global_namespace=self.user_global_ns, | |
1813 | alias_table=self.alias_manager.alias_table, |
|
1796 | alias_table=self.alias_manager.alias_table, | |
1814 | use_readline=self.has_readline, |
|
1797 | use_readline=self.has_readline, | |
1815 | config=self.config, |
|
1798 | config=self.config, | |
1816 | ) |
|
1799 | ) | |
1817 | self.configurables.append(self.Completer) |
|
1800 | self.configurables.append(self.Completer) | |
1818 |
|
1801 | |||
1819 | # Add custom completers to the basic ones built into IPCompleter |
|
1802 | # Add custom completers to the basic ones built into IPCompleter | |
1820 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1803 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1821 | self.strdispatchers['complete_command'] = sdisp |
|
1804 | self.strdispatchers['complete_command'] = sdisp | |
1822 | self.Completer.custom_completers = sdisp |
|
1805 | self.Completer.custom_completers = sdisp | |
1823 |
|
1806 | |||
1824 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1807 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1825 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1808 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1826 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1809 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1827 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1810 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1828 |
|
1811 | |||
1829 | # Only configure readline if we truly are using readline. IPython can |
|
1812 | # Only configure readline if we truly are using readline. IPython can | |
1830 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1813 | # do tab-completion over the network, in GUIs, etc, where readline | |
1831 | # itself may be absent |
|
1814 | # itself may be absent | |
1832 | if self.has_readline: |
|
1815 | if self.has_readline: | |
1833 | self.set_readline_completer() |
|
1816 | self.set_readline_completer() | |
1834 |
|
1817 | |||
1835 | def complete(self, text, line=None, cursor_pos=None): |
|
1818 | def complete(self, text, line=None, cursor_pos=None): | |
1836 | """Return the completed text and a list of completions. |
|
1819 | """Return the completed text and a list of completions. | |
1837 |
|
1820 | |||
1838 | Parameters |
|
1821 | Parameters | |
1839 | ---------- |
|
1822 | ---------- | |
1840 |
|
1823 | |||
1841 | text : string |
|
1824 | text : string | |
1842 | A string of text to be completed on. It can be given as empty and |
|
1825 | A string of text to be completed on. It can be given as empty and | |
1843 | instead a line/position pair are given. In this case, the |
|
1826 | instead a line/position pair are given. In this case, the | |
1844 | completer itself will split the line like readline does. |
|
1827 | completer itself will split the line like readline does. | |
1845 |
|
1828 | |||
1846 | line : string, optional |
|
1829 | line : string, optional | |
1847 | The complete line that text is part of. |
|
1830 | The complete line that text is part of. | |
1848 |
|
1831 | |||
1849 | cursor_pos : int, optional |
|
1832 | cursor_pos : int, optional | |
1850 | The position of the cursor on the input line. |
|
1833 | The position of the cursor on the input line. | |
1851 |
|
1834 | |||
1852 | Returns |
|
1835 | Returns | |
1853 | ------- |
|
1836 | ------- | |
1854 | text : string |
|
1837 | text : string | |
1855 | The actual text that was completed. |
|
1838 | The actual text that was completed. | |
1856 |
|
1839 | |||
1857 | matches : list |
|
1840 | matches : list | |
1858 | A sorted list with all possible completions. |
|
1841 | A sorted list with all possible completions. | |
1859 |
|
1842 | |||
1860 | The optional arguments allow the completion to take more context into |
|
1843 | The optional arguments allow the completion to take more context into | |
1861 | account, and are part of the low-level completion API. |
|
1844 | account, and are part of the low-level completion API. | |
1862 |
|
1845 | |||
1863 | This is a wrapper around the completion mechanism, similar to what |
|
1846 | This is a wrapper around the completion mechanism, similar to what | |
1864 | readline does at the command line when the TAB key is hit. By |
|
1847 | readline does at the command line when the TAB key is hit. By | |
1865 | exposing it as a method, it can be used by other non-readline |
|
1848 | exposing it as a method, it can be used by other non-readline | |
1866 | environments (such as GUIs) for text completion. |
|
1849 | environments (such as GUIs) for text completion. | |
1867 |
|
1850 | |||
1868 | Simple usage example: |
|
1851 | Simple usage example: | |
1869 |
|
1852 | |||
1870 | In [1]: x = 'hello' |
|
1853 | In [1]: x = 'hello' | |
1871 |
|
1854 | |||
1872 | In [2]: _ip.complete('x.l') |
|
1855 | In [2]: _ip.complete('x.l') | |
1873 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1856 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1874 | """ |
|
1857 | """ | |
1875 |
|
1858 | |||
1876 | # Inject names into __builtin__ so we can complete on the added names. |
|
1859 | # Inject names into __builtin__ so we can complete on the added names. | |
1877 | with self.builtin_trap: |
|
1860 | with self.builtin_trap: | |
1878 | return self.Completer.complete(text, line, cursor_pos) |
|
1861 | return self.Completer.complete(text, line, cursor_pos) | |
1879 |
|
1862 | |||
1880 | def set_custom_completer(self, completer, pos=0): |
|
1863 | def set_custom_completer(self, completer, pos=0): | |
1881 | """Adds a new custom completer function. |
|
1864 | """Adds a new custom completer function. | |
1882 |
|
1865 | |||
1883 | The position argument (defaults to 0) is the index in the completers |
|
1866 | The position argument (defaults to 0) is the index in the completers | |
1884 | list where you want the completer to be inserted.""" |
|
1867 | list where you want the completer to be inserted.""" | |
1885 |
|
1868 | |||
1886 | newcomp = types.MethodType(completer,self.Completer) |
|
1869 | newcomp = types.MethodType(completer,self.Completer) | |
1887 | self.Completer.matchers.insert(pos,newcomp) |
|
1870 | self.Completer.matchers.insert(pos,newcomp) | |
1888 |
|
1871 | |||
1889 | def set_readline_completer(self): |
|
1872 | def set_readline_completer(self): | |
1890 | """Reset readline's completer to be our own.""" |
|
1873 | """Reset readline's completer to be our own.""" | |
1891 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1874 | self.readline.set_completer(self.Completer.rlcomplete) | |
1892 |
|
1875 | |||
1893 | def set_completer_frame(self, frame=None): |
|
1876 | def set_completer_frame(self, frame=None): | |
1894 | """Set the frame of the completer.""" |
|
1877 | """Set the frame of the completer.""" | |
1895 | if frame: |
|
1878 | if frame: | |
1896 | self.Completer.namespace = frame.f_locals |
|
1879 | self.Completer.namespace = frame.f_locals | |
1897 | self.Completer.global_namespace = frame.f_globals |
|
1880 | self.Completer.global_namespace = frame.f_globals | |
1898 | else: |
|
1881 | else: | |
1899 | self.Completer.namespace = self.user_ns |
|
1882 | self.Completer.namespace = self.user_ns | |
1900 | self.Completer.global_namespace = self.user_global_ns |
|
1883 | self.Completer.global_namespace = self.user_global_ns | |
1901 |
|
1884 | |||
1902 | #------------------------------------------------------------------------- |
|
1885 | #------------------------------------------------------------------------- | |
1903 | # Things related to magics |
|
1886 | # Things related to magics | |
1904 | #------------------------------------------------------------------------- |
|
1887 | #------------------------------------------------------------------------- | |
1905 |
|
1888 | |||
1906 | def init_magics(self): |
|
1889 | def init_magics(self): | |
1907 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1890 | # FIXME: Move the color initialization to the DisplayHook, which | |
1908 | # should be split into a prompt manager and displayhook. We probably |
|
1891 | # should be split into a prompt manager and displayhook. We probably | |
1909 | # even need a centralize colors management object. |
|
1892 | # even need a centralize colors management object. | |
1910 | self.magic_colors(self.colors) |
|
1893 | self.magic_colors(self.colors) | |
1911 | # History was moved to a separate module |
|
1894 | # History was moved to a separate module | |
1912 | from . import history |
|
1895 | from . import history | |
1913 | history.init_ipython(self) |
|
1896 | history.init_ipython(self) | |
1914 |
|
1897 | |||
1915 | def magic(self, arg_s, next_input=None): |
|
1898 | def magic(self, arg_s, next_input=None): | |
1916 | """Call a magic function by name. |
|
1899 | """Call a magic function by name. | |
1917 |
|
1900 | |||
1918 | Input: a string containing the name of the magic function to call and |
|
1901 | Input: a string containing the name of the magic function to call and | |
1919 | any additional arguments to be passed to the magic. |
|
1902 | any additional arguments to be passed to the magic. | |
1920 |
|
1903 | |||
1921 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1904 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1922 | prompt: |
|
1905 | prompt: | |
1923 |
|
1906 | |||
1924 | In[1]: %name -opt foo bar |
|
1907 | In[1]: %name -opt foo bar | |
1925 |
|
1908 | |||
1926 | To call a magic without arguments, simply use magic('name'). |
|
1909 | To call a magic without arguments, simply use magic('name'). | |
1927 |
|
1910 | |||
1928 | This provides a proper Python function to call IPython's magics in any |
|
1911 | This provides a proper Python function to call IPython's magics in any | |
1929 | valid Python code you can type at the interpreter, including loops and |
|
1912 | valid Python code you can type at the interpreter, including loops and | |
1930 | compound statements. |
|
1913 | compound statements. | |
1931 | """ |
|
1914 | """ | |
1932 | # Allow setting the next input - this is used if the user does `a=abs?`. |
|
1915 | # Allow setting the next input - this is used if the user does `a=abs?`. | |
1933 | # We do this first so that magic functions can override it. |
|
1916 | # We do this first so that magic functions can override it. | |
1934 | if next_input: |
|
1917 | if next_input: | |
1935 | self.set_next_input(next_input) |
|
1918 | self.set_next_input(next_input) | |
1936 |
|
1919 | |||
1937 | args = arg_s.split(' ',1) |
|
1920 | args = arg_s.split(' ',1) | |
1938 | magic_name = args[0] |
|
1921 | magic_name = args[0] | |
1939 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1922 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1940 |
|
1923 | |||
1941 | try: |
|
1924 | try: | |
1942 | magic_args = args[1] |
|
1925 | magic_args = args[1] | |
1943 | except IndexError: |
|
1926 | except IndexError: | |
1944 | magic_args = '' |
|
1927 | magic_args = '' | |
1945 | fn = getattr(self,'magic_'+magic_name,None) |
|
1928 | fn = getattr(self,'magic_'+magic_name,None) | |
1946 | if fn is None: |
|
1929 | if fn is None: | |
1947 | error("Magic function `%s` not found." % magic_name) |
|
1930 | error("Magic function `%s` not found." % magic_name) | |
1948 | else: |
|
1931 | else: | |
1949 | magic_args = self.var_expand(magic_args,1) |
|
1932 | magic_args = self.var_expand(magic_args,1) | |
1950 | # Grab local namespace if we need it: |
|
1933 | # Grab local namespace if we need it: | |
1951 | if getattr(fn, "needs_local_scope", False): |
|
1934 | if getattr(fn, "needs_local_scope", False): | |
1952 | self._magic_locals = sys._getframe(1).f_locals |
|
1935 | self._magic_locals = sys._getframe(1).f_locals | |
1953 | with self.builtin_trap: |
|
1936 | with self.builtin_trap: | |
1954 | result = fn(magic_args) |
|
1937 | result = fn(magic_args) | |
1955 | # Ensure we're not keeping object references around: |
|
1938 | # Ensure we're not keeping object references around: | |
1956 | self._magic_locals = {} |
|
1939 | self._magic_locals = {} | |
1957 | return result |
|
1940 | return result | |
1958 |
|
1941 | |||
1959 | def define_magic(self, magicname, func): |
|
1942 | def define_magic(self, magicname, func): | |
1960 | """Expose own function as magic function for ipython |
|
1943 | """Expose own function as magic function for ipython | |
1961 |
|
1944 | |||
1962 | Example:: |
|
1945 | Example:: | |
1963 |
|
1946 | |||
1964 | def foo_impl(self,parameter_s=''): |
|
1947 | def foo_impl(self,parameter_s=''): | |
1965 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1948 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1966 | print 'Magic function. Passed parameter is between < >:' |
|
1949 | print 'Magic function. Passed parameter is between < >:' | |
1967 | print '<%s>' % parameter_s |
|
1950 | print '<%s>' % parameter_s | |
1968 | print 'The self object is:', self |
|
1951 | print 'The self object is:', self | |
1969 |
|
1952 | |||
1970 | ip.define_magic('foo',foo_impl) |
|
1953 | ip.define_magic('foo',foo_impl) | |
1971 | """ |
|
1954 | """ | |
1972 | im = types.MethodType(func,self) |
|
1955 | im = types.MethodType(func,self) | |
1973 | old = getattr(self, "magic_" + magicname, None) |
|
1956 | old = getattr(self, "magic_" + magicname, None) | |
1974 | setattr(self, "magic_" + magicname, im) |
|
1957 | setattr(self, "magic_" + magicname, im) | |
1975 | return old |
|
1958 | return old | |
1976 |
|
1959 | |||
1977 | #------------------------------------------------------------------------- |
|
1960 | #------------------------------------------------------------------------- | |
1978 | # Things related to macros |
|
1961 | # Things related to macros | |
1979 | #------------------------------------------------------------------------- |
|
1962 | #------------------------------------------------------------------------- | |
1980 |
|
1963 | |||
1981 | def define_macro(self, name, themacro): |
|
1964 | def define_macro(self, name, themacro): | |
1982 | """Define a new macro |
|
1965 | """Define a new macro | |
1983 |
|
1966 | |||
1984 | Parameters |
|
1967 | Parameters | |
1985 | ---------- |
|
1968 | ---------- | |
1986 | name : str |
|
1969 | name : str | |
1987 | The name of the macro. |
|
1970 | The name of the macro. | |
1988 | themacro : str or Macro |
|
1971 | themacro : str or Macro | |
1989 | The action to do upon invoking the macro. If a string, a new |
|
1972 | The action to do upon invoking the macro. If a string, a new | |
1990 | Macro object is created by passing the string to it. |
|
1973 | Macro object is created by passing the string to it. | |
1991 | """ |
|
1974 | """ | |
1992 |
|
1975 | |||
1993 | from IPython.core import macro |
|
1976 | from IPython.core import macro | |
1994 |
|
1977 | |||
1995 | if isinstance(themacro, basestring): |
|
1978 | if isinstance(themacro, basestring): | |
1996 | themacro = macro.Macro(themacro) |
|
1979 | themacro = macro.Macro(themacro) | |
1997 | if not isinstance(themacro, macro.Macro): |
|
1980 | if not isinstance(themacro, macro.Macro): | |
1998 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1981 | raise ValueError('A macro must be a string or a Macro instance.') | |
1999 | self.user_ns[name] = themacro |
|
1982 | self.user_ns[name] = themacro | |
2000 |
|
1983 | |||
2001 | #------------------------------------------------------------------------- |
|
1984 | #------------------------------------------------------------------------- | |
2002 | # Things related to the running of system commands |
|
1985 | # Things related to the running of system commands | |
2003 | #------------------------------------------------------------------------- |
|
1986 | #------------------------------------------------------------------------- | |
2004 |
|
1987 | |||
2005 | def system_piped(self, cmd): |
|
1988 | def system_piped(self, cmd): | |
2006 | """Call the given cmd in a subprocess, piping stdout/err |
|
1989 | """Call the given cmd in a subprocess, piping stdout/err | |
2007 |
|
1990 | |||
2008 | Parameters |
|
1991 | Parameters | |
2009 | ---------- |
|
1992 | ---------- | |
2010 | cmd : str |
|
1993 | cmd : str | |
2011 | Command to execute (can not end in '&', as background processes are |
|
1994 | Command to execute (can not end in '&', as background processes are | |
2012 | not supported. Should not be a command that expects input |
|
1995 | not supported. Should not be a command that expects input | |
2013 | other than simple text. |
|
1996 | other than simple text. | |
2014 | """ |
|
1997 | """ | |
2015 | if cmd.rstrip().endswith('&'): |
|
1998 | if cmd.rstrip().endswith('&'): | |
2016 | # this is *far* from a rigorous test |
|
1999 | # this is *far* from a rigorous test | |
2017 | # We do not support backgrounding processes because we either use |
|
2000 | # We do not support backgrounding processes because we either use | |
2018 | # pexpect or pipes to read from. Users can always just call |
|
2001 | # pexpect or pipes to read from. Users can always just call | |
2019 | # os.system() or use ip.system=ip.system_raw |
|
2002 | # os.system() or use ip.system=ip.system_raw | |
2020 | # if they really want a background process. |
|
2003 | # if they really want a background process. | |
2021 | raise OSError("Background processes not supported.") |
|
2004 | raise OSError("Background processes not supported.") | |
2022 |
|
2005 | |||
2023 | # we explicitly do NOT return the subprocess status code, because |
|
2006 | # we explicitly do NOT return the subprocess status code, because | |
2024 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2007 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2025 | # Instead, we store the exit_code in user_ns. |
|
2008 | # Instead, we store the exit_code in user_ns. | |
2026 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2)) |
|
2009 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2)) | |
2027 |
|
2010 | |||
2028 | def system_raw(self, cmd): |
|
2011 | def system_raw(self, cmd): | |
2029 | """Call the given cmd in a subprocess using os.system |
|
2012 | """Call the given cmd in a subprocess using os.system | |
2030 |
|
2013 | |||
2031 | Parameters |
|
2014 | Parameters | |
2032 | ---------- |
|
2015 | ---------- | |
2033 | cmd : str |
|
2016 | cmd : str | |
2034 | Command to execute. |
|
2017 | Command to execute. | |
2035 | """ |
|
2018 | """ | |
2036 | cmd = self.var_expand(cmd, depth=2) |
|
2019 | cmd = self.var_expand(cmd, depth=2) | |
2037 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2020 | # protect os.system from UNC paths on Windows, which it can't handle: | |
2038 | if sys.platform == 'win32': |
|
2021 | if sys.platform == 'win32': | |
2039 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2022 | from IPython.utils._process_win32 import AvoidUNCPath | |
2040 | with AvoidUNCPath() as path: |
|
2023 | with AvoidUNCPath() as path: | |
2041 | if path is not None: |
|
2024 | if path is not None: | |
2042 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2025 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
2043 | cmd = py3compat.unicode_to_str(cmd) |
|
2026 | cmd = py3compat.unicode_to_str(cmd) | |
2044 | ec = os.system(cmd) |
|
2027 | ec = os.system(cmd) | |
2045 | else: |
|
2028 | else: | |
2046 | cmd = py3compat.unicode_to_str(cmd) |
|
2029 | cmd = py3compat.unicode_to_str(cmd) | |
2047 | ec = os.system(cmd) |
|
2030 | ec = os.system(cmd) | |
2048 |
|
2031 | |||
2049 | # We explicitly do NOT return the subprocess status code, because |
|
2032 | # We explicitly do NOT return the subprocess status code, because | |
2050 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2033 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2051 | # Instead, we store the exit_code in user_ns. |
|
2034 | # Instead, we store the exit_code in user_ns. | |
2052 | self.user_ns['_exit_code'] = ec |
|
2035 | self.user_ns['_exit_code'] = ec | |
2053 |
|
2036 | |||
2054 | # use piped system by default, because it is better behaved |
|
2037 | # use piped system by default, because it is better behaved | |
2055 | system = system_piped |
|
2038 | system = system_piped | |
2056 |
|
2039 | |||
2057 | def getoutput(self, cmd, split=True): |
|
2040 | def getoutput(self, cmd, split=True): | |
2058 | """Get output (possibly including stderr) from a subprocess. |
|
2041 | """Get output (possibly including stderr) from a subprocess. | |
2059 |
|
2042 | |||
2060 | Parameters |
|
2043 | Parameters | |
2061 | ---------- |
|
2044 | ---------- | |
2062 | cmd : str |
|
2045 | cmd : str | |
2063 | Command to execute (can not end in '&', as background processes are |
|
2046 | Command to execute (can not end in '&', as background processes are | |
2064 | not supported. |
|
2047 | not supported. | |
2065 | split : bool, optional |
|
2048 | split : bool, optional | |
2066 |
|
2049 | |||
2067 | If True, split the output into an IPython SList. Otherwise, an |
|
2050 | If True, split the output into an IPython SList. Otherwise, an | |
2068 | IPython LSString is returned. These are objects similar to normal |
|
2051 | IPython LSString is returned. These are objects similar to normal | |
2069 | lists and strings, with a few convenience attributes for easier |
|
2052 | lists and strings, with a few convenience attributes for easier | |
2070 | manipulation of line-based output. You can use '?' on them for |
|
2053 | manipulation of line-based output. You can use '?' on them for | |
2071 | details. |
|
2054 | details. | |
2072 | """ |
|
2055 | """ | |
2073 | if cmd.rstrip().endswith('&'): |
|
2056 | if cmd.rstrip().endswith('&'): | |
2074 | # this is *far* from a rigorous test |
|
2057 | # this is *far* from a rigorous test | |
2075 | raise OSError("Background processes not supported.") |
|
2058 | raise OSError("Background processes not supported.") | |
2076 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
2059 | out = getoutput(self.var_expand(cmd, depth=2)) | |
2077 | if split: |
|
2060 | if split: | |
2078 | out = SList(out.splitlines()) |
|
2061 | out = SList(out.splitlines()) | |
2079 | else: |
|
2062 | else: | |
2080 | out = LSString(out) |
|
2063 | out = LSString(out) | |
2081 | return out |
|
2064 | return out | |
2082 |
|
2065 | |||
2083 | #------------------------------------------------------------------------- |
|
2066 | #------------------------------------------------------------------------- | |
2084 | # Things related to aliases |
|
2067 | # Things related to aliases | |
2085 | #------------------------------------------------------------------------- |
|
2068 | #------------------------------------------------------------------------- | |
2086 |
|
2069 | |||
2087 | def init_alias(self): |
|
2070 | def init_alias(self): | |
2088 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
2071 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
2089 | self.configurables.append(self.alias_manager) |
|
2072 | self.configurables.append(self.alias_manager) | |
2090 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
2073 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
2091 |
|
2074 | |||
2092 | #------------------------------------------------------------------------- |
|
2075 | #------------------------------------------------------------------------- | |
2093 | # Things related to extensions and plugins |
|
2076 | # Things related to extensions and plugins | |
2094 | #------------------------------------------------------------------------- |
|
2077 | #------------------------------------------------------------------------- | |
2095 |
|
2078 | |||
2096 | def init_extension_manager(self): |
|
2079 | def init_extension_manager(self): | |
2097 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
2080 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
2098 | self.configurables.append(self.extension_manager) |
|
2081 | self.configurables.append(self.extension_manager) | |
2099 |
|
2082 | |||
2100 | def init_plugin_manager(self): |
|
2083 | def init_plugin_manager(self): | |
2101 | self.plugin_manager = PluginManager(config=self.config) |
|
2084 | self.plugin_manager = PluginManager(config=self.config) | |
2102 | self.configurables.append(self.plugin_manager) |
|
2085 | self.configurables.append(self.plugin_manager) | |
2103 |
|
2086 | |||
2104 |
|
2087 | |||
2105 | #------------------------------------------------------------------------- |
|
2088 | #------------------------------------------------------------------------- | |
2106 | # Things related to payloads |
|
2089 | # Things related to payloads | |
2107 | #------------------------------------------------------------------------- |
|
2090 | #------------------------------------------------------------------------- | |
2108 |
|
2091 | |||
2109 | def init_payload(self): |
|
2092 | def init_payload(self): | |
2110 | self.payload_manager = PayloadManager(config=self.config) |
|
2093 | self.payload_manager = PayloadManager(config=self.config) | |
2111 | self.configurables.append(self.payload_manager) |
|
2094 | self.configurables.append(self.payload_manager) | |
2112 |
|
2095 | |||
2113 | #------------------------------------------------------------------------- |
|
2096 | #------------------------------------------------------------------------- | |
2114 | # Things related to the prefilter |
|
2097 | # Things related to the prefilter | |
2115 | #------------------------------------------------------------------------- |
|
2098 | #------------------------------------------------------------------------- | |
2116 |
|
2099 | |||
2117 | def init_prefilter(self): |
|
2100 | def init_prefilter(self): | |
2118 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
2101 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
2119 | self.configurables.append(self.prefilter_manager) |
|
2102 | self.configurables.append(self.prefilter_manager) | |
2120 | # Ultimately this will be refactored in the new interpreter code, but |
|
2103 | # Ultimately this will be refactored in the new interpreter code, but | |
2121 | # for now, we should expose the main prefilter method (there's legacy |
|
2104 | # for now, we should expose the main prefilter method (there's legacy | |
2122 | # code out there that may rely on this). |
|
2105 | # code out there that may rely on this). | |
2123 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2106 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2124 |
|
2107 | |||
2125 | def auto_rewrite_input(self, cmd): |
|
2108 | def auto_rewrite_input(self, cmd): | |
2126 | """Print to the screen the rewritten form of the user's command. |
|
2109 | """Print to the screen the rewritten form of the user's command. | |
2127 |
|
2110 | |||
2128 | This shows visual feedback by rewriting input lines that cause |
|
2111 | This shows visual feedback by rewriting input lines that cause | |
2129 | automatic calling to kick in, like:: |
|
2112 | automatic calling to kick in, like:: | |
2130 |
|
2113 | |||
2131 | /f x |
|
2114 | /f x | |
2132 |
|
2115 | |||
2133 | into:: |
|
2116 | into:: | |
2134 |
|
2117 | |||
2135 | ------> f(x) |
|
2118 | ------> f(x) | |
2136 |
|
2119 | |||
2137 | after the user's input prompt. This helps the user understand that the |
|
2120 | after the user's input prompt. This helps the user understand that the | |
2138 | input line was transformed automatically by IPython. |
|
2121 | input line was transformed automatically by IPython. | |
2139 | """ |
|
2122 | """ | |
2140 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
2123 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
2141 |
|
2124 | |||
2142 | try: |
|
2125 | try: | |
2143 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2126 | # plain ascii works better w/ pyreadline, on some machines, so | |
2144 | # we use it and only print uncolored rewrite if we have unicode |
|
2127 | # we use it and only print uncolored rewrite if we have unicode | |
2145 | rw = str(rw) |
|
2128 | rw = str(rw) | |
2146 | print >> io.stdout, rw |
|
2129 | print >> io.stdout, rw | |
2147 | except UnicodeEncodeError: |
|
2130 | except UnicodeEncodeError: | |
2148 | print "------> " + cmd |
|
2131 | print "------> " + cmd | |
2149 |
|
2132 | |||
2150 | #------------------------------------------------------------------------- |
|
2133 | #------------------------------------------------------------------------- | |
2151 | # Things related to extracting values/expressions from kernel and user_ns |
|
2134 | # Things related to extracting values/expressions from kernel and user_ns | |
2152 | #------------------------------------------------------------------------- |
|
2135 | #------------------------------------------------------------------------- | |
2153 |
|
2136 | |||
2154 | def _simple_error(self): |
|
2137 | def _simple_error(self): | |
2155 | etype, value = sys.exc_info()[:2] |
|
2138 | etype, value = sys.exc_info()[:2] | |
2156 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
2139 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
2157 |
|
2140 | |||
2158 | def user_variables(self, names): |
|
2141 | def user_variables(self, names): | |
2159 | """Get a list of variable names from the user's namespace. |
|
2142 | """Get a list of variable names from the user's namespace. | |
2160 |
|
2143 | |||
2161 | Parameters |
|
2144 | Parameters | |
2162 | ---------- |
|
2145 | ---------- | |
2163 | names : list of strings |
|
2146 | names : list of strings | |
2164 | A list of names of variables to be read from the user namespace. |
|
2147 | A list of names of variables to be read from the user namespace. | |
2165 |
|
2148 | |||
2166 | Returns |
|
2149 | Returns | |
2167 | ------- |
|
2150 | ------- | |
2168 | A dict, keyed by the input names and with the repr() of each value. |
|
2151 | A dict, keyed by the input names and with the repr() of each value. | |
2169 | """ |
|
2152 | """ | |
2170 | out = {} |
|
2153 | out = {} | |
2171 | user_ns = self.user_ns |
|
2154 | user_ns = self.user_ns | |
2172 | for varname in names: |
|
2155 | for varname in names: | |
2173 | try: |
|
2156 | try: | |
2174 | value = repr(user_ns[varname]) |
|
2157 | value = repr(user_ns[varname]) | |
2175 | except: |
|
2158 | except: | |
2176 | value = self._simple_error() |
|
2159 | value = self._simple_error() | |
2177 | out[varname] = value |
|
2160 | out[varname] = value | |
2178 | return out |
|
2161 | return out | |
2179 |
|
2162 | |||
2180 | def user_expressions(self, expressions): |
|
2163 | def user_expressions(self, expressions): | |
2181 | """Evaluate a dict of expressions in the user's namespace. |
|
2164 | """Evaluate a dict of expressions in the user's namespace. | |
2182 |
|
2165 | |||
2183 | Parameters |
|
2166 | Parameters | |
2184 | ---------- |
|
2167 | ---------- | |
2185 | expressions : dict |
|
2168 | expressions : dict | |
2186 | A dict with string keys and string values. The expression values |
|
2169 | A dict with string keys and string values. The expression values | |
2187 | should be valid Python expressions, each of which will be evaluated |
|
2170 | should be valid Python expressions, each of which will be evaluated | |
2188 | in the user namespace. |
|
2171 | in the user namespace. | |
2189 |
|
2172 | |||
2190 | Returns |
|
2173 | Returns | |
2191 | ------- |
|
2174 | ------- | |
2192 | A dict, keyed like the input expressions dict, with the repr() of each |
|
2175 | A dict, keyed like the input expressions dict, with the repr() of each | |
2193 | value. |
|
2176 | value. | |
2194 | """ |
|
2177 | """ | |
2195 | out = {} |
|
2178 | out = {} | |
2196 | user_ns = self.user_ns |
|
2179 | user_ns = self.user_ns | |
2197 | global_ns = self.user_global_ns |
|
2180 | global_ns = self.user_global_ns | |
2198 | for key, expr in expressions.iteritems(): |
|
2181 | for key, expr in expressions.iteritems(): | |
2199 | try: |
|
2182 | try: | |
2200 | value = repr(eval(expr, global_ns, user_ns)) |
|
2183 | value = repr(eval(expr, global_ns, user_ns)) | |
2201 | except: |
|
2184 | except: | |
2202 | value = self._simple_error() |
|
2185 | value = self._simple_error() | |
2203 | out[key] = value |
|
2186 | out[key] = value | |
2204 | return out |
|
2187 | return out | |
2205 |
|
2188 | |||
2206 | #------------------------------------------------------------------------- |
|
2189 | #------------------------------------------------------------------------- | |
2207 | # Things related to the running of code |
|
2190 | # Things related to the running of code | |
2208 | #------------------------------------------------------------------------- |
|
2191 | #------------------------------------------------------------------------- | |
2209 |
|
2192 | |||
2210 | def ex(self, cmd): |
|
2193 | def ex(self, cmd): | |
2211 | """Execute a normal python statement in user namespace.""" |
|
2194 | """Execute a normal python statement in user namespace.""" | |
2212 | with self.builtin_trap: |
|
2195 | with self.builtin_trap: | |
2213 | exec cmd in self.user_global_ns, self.user_ns |
|
2196 | exec cmd in self.user_global_ns, self.user_ns | |
2214 |
|
2197 | |||
2215 | def ev(self, expr): |
|
2198 | def ev(self, expr): | |
2216 | """Evaluate python expression expr in user namespace. |
|
2199 | """Evaluate python expression expr in user namespace. | |
2217 |
|
2200 | |||
2218 | Returns the result of evaluation |
|
2201 | Returns the result of evaluation | |
2219 | """ |
|
2202 | """ | |
2220 | with self.builtin_trap: |
|
2203 | with self.builtin_trap: | |
2221 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2204 | return eval(expr, self.user_global_ns, self.user_ns) | |
2222 |
|
2205 | |||
2223 | def safe_execfile(self, fname, *where, **kw): |
|
2206 | def safe_execfile(self, fname, *where, **kw): | |
2224 | """A safe version of the builtin execfile(). |
|
2207 | """A safe version of the builtin execfile(). | |
2225 |
|
2208 | |||
2226 | This version will never throw an exception, but instead print |
|
2209 | This version will never throw an exception, but instead print | |
2227 | helpful error messages to the screen. This only works on pure |
|
2210 | helpful error messages to the screen. This only works on pure | |
2228 | Python files with the .py extension. |
|
2211 | Python files with the .py extension. | |
2229 |
|
2212 | |||
2230 | Parameters |
|
2213 | Parameters | |
2231 | ---------- |
|
2214 | ---------- | |
2232 | fname : string |
|
2215 | fname : string | |
2233 | The name of the file to be executed. |
|
2216 | The name of the file to be executed. | |
2234 | where : tuple |
|
2217 | where : tuple | |
2235 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2218 | One or two namespaces, passed to execfile() as (globals,locals). | |
2236 | If only one is given, it is passed as both. |
|
2219 | If only one is given, it is passed as both. | |
2237 | exit_ignore : bool (False) |
|
2220 | exit_ignore : bool (False) | |
2238 | If True, then silence SystemExit for non-zero status (it is always |
|
2221 | If True, then silence SystemExit for non-zero status (it is always | |
2239 | silenced for zero status, as it is so common). |
|
2222 | silenced for zero status, as it is so common). | |
2240 | raise_exceptions : bool (False) |
|
2223 | raise_exceptions : bool (False) | |
2241 | If True raise exceptions everywhere. Meant for testing. |
|
2224 | If True raise exceptions everywhere. Meant for testing. | |
2242 |
|
2225 | |||
2243 | """ |
|
2226 | """ | |
2244 | kw.setdefault('exit_ignore', False) |
|
2227 | kw.setdefault('exit_ignore', False) | |
2245 | kw.setdefault('raise_exceptions', False) |
|
2228 | kw.setdefault('raise_exceptions', False) | |
2246 |
|
2229 | |||
2247 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2230 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2248 |
|
2231 | |||
2249 | # Make sure we can open the file |
|
2232 | # Make sure we can open the file | |
2250 | try: |
|
2233 | try: | |
2251 | with open(fname) as thefile: |
|
2234 | with open(fname) as thefile: | |
2252 | pass |
|
2235 | pass | |
2253 | except: |
|
2236 | except: | |
2254 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2237 | warn('Could not open file <%s> for safe execution.' % fname) | |
2255 | return |
|
2238 | return | |
2256 |
|
2239 | |||
2257 | # Find things also in current directory. This is needed to mimic the |
|
2240 | # Find things also in current directory. This is needed to mimic the | |
2258 | # behavior of running a script from the system command line, where |
|
2241 | # behavior of running a script from the system command line, where | |
2259 | # Python inserts the script's directory into sys.path |
|
2242 | # Python inserts the script's directory into sys.path | |
2260 | dname = os.path.dirname(fname) |
|
2243 | dname = os.path.dirname(fname) | |
2261 |
|
2244 | |||
2262 | with prepended_to_syspath(dname): |
|
2245 | with prepended_to_syspath(dname): | |
2263 | try: |
|
2246 | try: | |
2264 | py3compat.execfile(fname,*where) |
|
2247 | py3compat.execfile(fname,*where) | |
2265 | except SystemExit, status: |
|
2248 | except SystemExit, status: | |
2266 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2249 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2267 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2250 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2268 | # these are considered normal by the OS: |
|
2251 | # these are considered normal by the OS: | |
2269 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2252 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2270 | # 0 |
|
2253 | # 0 | |
2271 | # > python -c'import sys;sys.exit()'; echo $? |
|
2254 | # > python -c'import sys;sys.exit()'; echo $? | |
2272 | # 0 |
|
2255 | # 0 | |
2273 | # For other exit status, we show the exception unless |
|
2256 | # For other exit status, we show the exception unless | |
2274 | # explicitly silenced, but only in short form. |
|
2257 | # explicitly silenced, but only in short form. | |
2275 | if kw['raise_exceptions']: |
|
2258 | if kw['raise_exceptions']: | |
2276 | raise |
|
2259 | raise | |
2277 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2260 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2278 | self.showtraceback(exception_only=True) |
|
2261 | self.showtraceback(exception_only=True) | |
2279 | except: |
|
2262 | except: | |
2280 | if kw['raise_exceptions']: |
|
2263 | if kw['raise_exceptions']: | |
2281 | raise |
|
2264 | raise | |
2282 | self.showtraceback() |
|
2265 | self.showtraceback() | |
2283 |
|
2266 | |||
2284 | def safe_execfile_ipy(self, fname): |
|
2267 | def safe_execfile_ipy(self, fname): | |
2285 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2268 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2286 |
|
2269 | |||
2287 | Parameters |
|
2270 | Parameters | |
2288 | ---------- |
|
2271 | ---------- | |
2289 | fname : str |
|
2272 | fname : str | |
2290 | The name of the file to execute. The filename must have a |
|
2273 | The name of the file to execute. The filename must have a | |
2291 | .ipy extension. |
|
2274 | .ipy extension. | |
2292 | """ |
|
2275 | """ | |
2293 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2276 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2294 |
|
2277 | |||
2295 | # Make sure we can open the file |
|
2278 | # Make sure we can open the file | |
2296 | try: |
|
2279 | try: | |
2297 | with open(fname) as thefile: |
|
2280 | with open(fname) as thefile: | |
2298 | pass |
|
2281 | pass | |
2299 | except: |
|
2282 | except: | |
2300 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2283 | warn('Could not open file <%s> for safe execution.' % fname) | |
2301 | return |
|
2284 | return | |
2302 |
|
2285 | |||
2303 | # Find things also in current directory. This is needed to mimic the |
|
2286 | # Find things also in current directory. This is needed to mimic the | |
2304 | # behavior of running a script from the system command line, where |
|
2287 | # behavior of running a script from the system command line, where | |
2305 | # Python inserts the script's directory into sys.path |
|
2288 | # Python inserts the script's directory into sys.path | |
2306 | dname = os.path.dirname(fname) |
|
2289 | dname = os.path.dirname(fname) | |
2307 |
|
2290 | |||
2308 | with prepended_to_syspath(dname): |
|
2291 | with prepended_to_syspath(dname): | |
2309 | try: |
|
2292 | try: | |
2310 | with open(fname) as thefile: |
|
2293 | with open(fname) as thefile: | |
2311 | # self.run_cell currently captures all exceptions |
|
2294 | # self.run_cell currently captures all exceptions | |
2312 | # raised in user code. It would be nice if there were |
|
2295 | # raised in user code. It would be nice if there were | |
2313 | # versions of runlines, execfile that did raise, so |
|
2296 | # versions of runlines, execfile that did raise, so | |
2314 | # we could catch the errors. |
|
2297 | # we could catch the errors. | |
2315 | self.run_cell(thefile.read(), store_history=False) |
|
2298 | self.run_cell(thefile.read(), store_history=False) | |
2316 | except: |
|
2299 | except: | |
2317 | self.showtraceback() |
|
2300 | self.showtraceback() | |
2318 | warn('Unknown failure executing file: <%s>' % fname) |
|
2301 | warn('Unknown failure executing file: <%s>' % fname) | |
2319 |
|
2302 | |||
2320 | def run_cell(self, raw_cell, store_history=False): |
|
2303 | def run_cell(self, raw_cell, store_history=False): | |
2321 | """Run a complete IPython cell. |
|
2304 | """Run a complete IPython cell. | |
2322 |
|
2305 | |||
2323 | Parameters |
|
2306 | Parameters | |
2324 | ---------- |
|
2307 | ---------- | |
2325 | raw_cell : str |
|
2308 | raw_cell : str | |
2326 | The code (including IPython code such as %magic functions) to run. |
|
2309 | The code (including IPython code such as %magic functions) to run. | |
2327 | store_history : bool |
|
2310 | store_history : bool | |
2328 | If True, the raw and translated cell will be stored in IPython's |
|
2311 | If True, the raw and translated cell will be stored in IPython's | |
2329 | history. For user code calling back into IPython's machinery, this |
|
2312 | history. For user code calling back into IPython's machinery, this | |
2330 | should be set to False. |
|
2313 | should be set to False. | |
2331 | """ |
|
2314 | """ | |
2332 | if (not raw_cell) or raw_cell.isspace(): |
|
2315 | if (not raw_cell) or raw_cell.isspace(): | |
2333 | return |
|
2316 | return | |
2334 |
|
2317 | |||
2335 | for line in raw_cell.splitlines(): |
|
2318 | for line in raw_cell.splitlines(): | |
2336 | self.input_splitter.push(line) |
|
2319 | self.input_splitter.push(line) | |
2337 | cell = self.input_splitter.source_reset() |
|
2320 | cell = self.input_splitter.source_reset() | |
2338 |
|
2321 | |||
2339 | with self.builtin_trap: |
|
2322 | with self.builtin_trap: | |
2340 | prefilter_failed = False |
|
2323 | prefilter_failed = False | |
2341 | if len(cell.splitlines()) == 1: |
|
2324 | if len(cell.splitlines()) == 1: | |
2342 | try: |
|
2325 | try: | |
2343 | # use prefilter_lines to handle trailing newlines |
|
2326 | # use prefilter_lines to handle trailing newlines | |
2344 | # restore trailing newline for ast.parse |
|
2327 | # restore trailing newline for ast.parse | |
2345 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2328 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' | |
2346 | except AliasError as e: |
|
2329 | except AliasError as e: | |
2347 | error(e) |
|
2330 | error(e) | |
2348 | prefilter_failed = True |
|
2331 | prefilter_failed = True | |
2349 | except Exception: |
|
2332 | except Exception: | |
2350 | # don't allow prefilter errors to crash IPython |
|
2333 | # don't allow prefilter errors to crash IPython | |
2351 | self.showtraceback() |
|
2334 | self.showtraceback() | |
2352 | prefilter_failed = True |
|
2335 | prefilter_failed = True | |
2353 |
|
2336 | |||
2354 | # Store raw and processed history |
|
2337 | # Store raw and processed history | |
2355 | if store_history: |
|
2338 | if store_history: | |
2356 | self.history_manager.store_inputs(self.execution_count, |
|
2339 | self.history_manager.store_inputs(self.execution_count, | |
2357 | cell, raw_cell) |
|
2340 | cell, raw_cell) | |
2358 |
|
2341 | |||
2359 | self.logger.log(cell, raw_cell) |
|
2342 | self.logger.log(cell, raw_cell) | |
2360 |
|
2343 | |||
2361 | if not prefilter_failed: |
|
2344 | if not prefilter_failed: | |
2362 | # don't run if prefilter failed |
|
2345 | # don't run if prefilter failed | |
2363 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2346 | cell_name = self.compile.cache(cell, self.execution_count) | |
2364 |
|
2347 | |||
2365 | with self.display_trap: |
|
2348 | with self.display_trap: | |
2366 | try: |
|
2349 | try: | |
2367 | code_ast = self.compile.ast_parse(cell, filename=cell_name) |
|
2350 | code_ast = self.compile.ast_parse(cell, filename=cell_name) | |
2368 | except IndentationError: |
|
2351 | except IndentationError: | |
2369 | self.showindentationerror() |
|
2352 | self.showindentationerror() | |
2370 | self.execution_count += 1 |
|
2353 | self.execution_count += 1 | |
2371 | return None |
|
2354 | return None | |
2372 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2355 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2373 | MemoryError): |
|
2356 | MemoryError): | |
2374 | self.showsyntaxerror() |
|
2357 | self.showsyntaxerror() | |
2375 | self.execution_count += 1 |
|
2358 | self.execution_count += 1 | |
2376 | return None |
|
2359 | return None | |
2377 |
|
2360 | |||
2378 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2361 | self.run_ast_nodes(code_ast.body, cell_name, | |
2379 | interactivity="last_expr") |
|
2362 | interactivity="last_expr") | |
2380 |
|
2363 | |||
2381 | # Execute any registered post-execution functions. |
|
2364 | # Execute any registered post-execution functions. | |
2382 | for func, status in self._post_execute.iteritems(): |
|
2365 | for func, status in self._post_execute.iteritems(): | |
2383 | if not status: |
|
2366 | if not status: | |
2384 | continue |
|
2367 | continue | |
2385 | try: |
|
2368 | try: | |
2386 | func() |
|
2369 | func() | |
2387 | except KeyboardInterrupt: |
|
2370 | except KeyboardInterrupt: | |
2388 | print >> io.stderr, "\nKeyboardInterrupt" |
|
2371 | print >> io.stderr, "\nKeyboardInterrupt" | |
2389 | except Exception: |
|
2372 | except Exception: | |
2390 | print >> io.stderr, "Disabling failed post-execution function: %s" % func |
|
2373 | print >> io.stderr, "Disabling failed post-execution function: %s" % func | |
2391 | self.showtraceback() |
|
2374 | self.showtraceback() | |
2392 | # Deactivate failing function |
|
2375 | # Deactivate failing function | |
2393 | self._post_execute[func] = False |
|
2376 | self._post_execute[func] = False | |
2394 |
|
2377 | |||
2395 | if store_history: |
|
2378 | if store_history: | |
2396 | # Write output to the database. Does nothing unless |
|
2379 | # Write output to the database. Does nothing unless | |
2397 | # history output logging is enabled. |
|
2380 | # history output logging is enabled. | |
2398 | self.history_manager.store_output(self.execution_count) |
|
2381 | self.history_manager.store_output(self.execution_count) | |
2399 | # Each cell is a *single* input, regardless of how many lines it has |
|
2382 | # Each cell is a *single* input, regardless of how many lines it has | |
2400 | self.execution_count += 1 |
|
2383 | self.execution_count += 1 | |
2401 |
|
2384 | |||
2402 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): |
|
2385 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): | |
2403 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2386 | """Run a sequence of AST nodes. The execution mode depends on the | |
2404 | interactivity parameter. |
|
2387 | interactivity parameter. | |
2405 |
|
2388 | |||
2406 | Parameters |
|
2389 | Parameters | |
2407 | ---------- |
|
2390 | ---------- | |
2408 | nodelist : list |
|
2391 | nodelist : list | |
2409 | A sequence of AST nodes to run. |
|
2392 | A sequence of AST nodes to run. | |
2410 | cell_name : str |
|
2393 | cell_name : str | |
2411 | Will be passed to the compiler as the filename of the cell. Typically |
|
2394 | Will be passed to the compiler as the filename of the cell. Typically | |
2412 | the value returned by ip.compile.cache(cell). |
|
2395 | the value returned by ip.compile.cache(cell). | |
2413 | interactivity : str |
|
2396 | interactivity : str | |
2414 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2397 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
2415 | run interactively (displaying output from expressions). 'last_expr' |
|
2398 | run interactively (displaying output from expressions). 'last_expr' | |
2416 | will run the last node interactively only if it is an expression (i.e. |
|
2399 | will run the last node interactively only if it is an expression (i.e. | |
2417 | expressions in loops or other blocks are not displayed. Other values |
|
2400 | expressions in loops or other blocks are not displayed. Other values | |
2418 | for this parameter will raise a ValueError. |
|
2401 | for this parameter will raise a ValueError. | |
2419 | """ |
|
2402 | """ | |
2420 | if not nodelist: |
|
2403 | if not nodelist: | |
2421 | return |
|
2404 | return | |
2422 |
|
2405 | |||
2423 | if interactivity == 'last_expr': |
|
2406 | if interactivity == 'last_expr': | |
2424 | if isinstance(nodelist[-1], ast.Expr): |
|
2407 | if isinstance(nodelist[-1], ast.Expr): | |
2425 | interactivity = "last" |
|
2408 | interactivity = "last" | |
2426 | else: |
|
2409 | else: | |
2427 | interactivity = "none" |
|
2410 | interactivity = "none" | |
2428 |
|
2411 | |||
2429 | if interactivity == 'none': |
|
2412 | if interactivity == 'none': | |
2430 | to_run_exec, to_run_interactive = nodelist, [] |
|
2413 | to_run_exec, to_run_interactive = nodelist, [] | |
2431 | elif interactivity == 'last': |
|
2414 | elif interactivity == 'last': | |
2432 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2415 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2433 | elif interactivity == 'all': |
|
2416 | elif interactivity == 'all': | |
2434 | to_run_exec, to_run_interactive = [], nodelist |
|
2417 | to_run_exec, to_run_interactive = [], nodelist | |
2435 | else: |
|
2418 | else: | |
2436 | raise ValueError("Interactivity was %r" % interactivity) |
|
2419 | raise ValueError("Interactivity was %r" % interactivity) | |
2437 |
|
2420 | |||
2438 | exec_count = self.execution_count |
|
2421 | exec_count = self.execution_count | |
2439 |
|
2422 | |||
2440 | try: |
|
2423 | try: | |
2441 | for i, node in enumerate(to_run_exec): |
|
2424 | for i, node in enumerate(to_run_exec): | |
2442 | mod = ast.Module([node]) |
|
2425 | mod = ast.Module([node]) | |
2443 | code = self.compile(mod, cell_name, "exec") |
|
2426 | code = self.compile(mod, cell_name, "exec") | |
2444 | if self.run_code(code): |
|
2427 | if self.run_code(code): | |
2445 | return True |
|
2428 | return True | |
2446 |
|
2429 | |||
2447 | for i, node in enumerate(to_run_interactive): |
|
2430 | for i, node in enumerate(to_run_interactive): | |
2448 | mod = ast.Interactive([node]) |
|
2431 | mod = ast.Interactive([node]) | |
2449 | code = self.compile(mod, cell_name, "single") |
|
2432 | code = self.compile(mod, cell_name, "single") | |
2450 | if self.run_code(code): |
|
2433 | if self.run_code(code): | |
2451 | return True |
|
2434 | return True | |
2452 | except: |
|
2435 | except: | |
2453 | # It's possible to have exceptions raised here, typically by |
|
2436 | # It's possible to have exceptions raised here, typically by | |
2454 | # compilation of odd code (such as a naked 'return' outside a |
|
2437 | # compilation of odd code (such as a naked 'return' outside a | |
2455 | # function) that did parse but isn't valid. Typically the exception |
|
2438 | # function) that did parse but isn't valid. Typically the exception | |
2456 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2439 | # is a SyntaxError, but it's safest just to catch anything and show | |
2457 | # the user a traceback. |
|
2440 | # the user a traceback. | |
2458 |
|
2441 | |||
2459 | # We do only one try/except outside the loop to minimize the impact |
|
2442 | # We do only one try/except outside the loop to minimize the impact | |
2460 | # on runtime, and also because if any node in the node list is |
|
2443 | # on runtime, and also because if any node in the node list is | |
2461 | # broken, we should stop execution completely. |
|
2444 | # broken, we should stop execution completely. | |
2462 | self.showtraceback() |
|
2445 | self.showtraceback() | |
2463 |
|
2446 | |||
2464 | return False |
|
2447 | return False | |
2465 |
|
2448 | |||
2466 | def run_code(self, code_obj): |
|
2449 | def run_code(self, code_obj): | |
2467 | """Execute a code object. |
|
2450 | """Execute a code object. | |
2468 |
|
2451 | |||
2469 | When an exception occurs, self.showtraceback() is called to display a |
|
2452 | When an exception occurs, self.showtraceback() is called to display a | |
2470 | traceback. |
|
2453 | traceback. | |
2471 |
|
2454 | |||
2472 | Parameters |
|
2455 | Parameters | |
2473 | ---------- |
|
2456 | ---------- | |
2474 | code_obj : code object |
|
2457 | code_obj : code object | |
2475 | A compiled code object, to be executed |
|
2458 | A compiled code object, to be executed | |
2476 | post_execute : bool [default: True] |
|
2459 | post_execute : bool [default: True] | |
2477 | whether to call post_execute hooks after this particular execution. |
|
2460 | whether to call post_execute hooks after this particular execution. | |
2478 |
|
2461 | |||
2479 | Returns |
|
2462 | Returns | |
2480 | ------- |
|
2463 | ------- | |
2481 | False : successful execution. |
|
2464 | False : successful execution. | |
2482 | True : an error occurred. |
|
2465 | True : an error occurred. | |
2483 | """ |
|
2466 | """ | |
2484 |
|
2467 | |||
2485 | # Set our own excepthook in case the user code tries to call it |
|
2468 | # Set our own excepthook in case the user code tries to call it | |
2486 | # directly, so that the IPython crash handler doesn't get triggered |
|
2469 | # directly, so that the IPython crash handler doesn't get triggered | |
2487 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2470 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2488 |
|
2471 | |||
2489 | # we save the original sys.excepthook in the instance, in case config |
|
2472 | # we save the original sys.excepthook in the instance, in case config | |
2490 | # code (such as magics) needs access to it. |
|
2473 | # code (such as magics) needs access to it. | |
2491 | self.sys_excepthook = old_excepthook |
|
2474 | self.sys_excepthook = old_excepthook | |
2492 | outflag = 1 # happens in more places, so it's easier as default |
|
2475 | outflag = 1 # happens in more places, so it's easier as default | |
2493 | try: |
|
2476 | try: | |
2494 | try: |
|
2477 | try: | |
2495 | self.hooks.pre_run_code_hook() |
|
2478 | self.hooks.pre_run_code_hook() | |
2496 | #rprint('Running code', repr(code_obj)) # dbg |
|
2479 | #rprint('Running code', repr(code_obj)) # dbg | |
2497 | exec code_obj in self.user_global_ns, self.user_ns |
|
2480 | exec code_obj in self.user_global_ns, self.user_ns | |
2498 | finally: |
|
2481 | finally: | |
2499 | # Reset our crash handler in place |
|
2482 | # Reset our crash handler in place | |
2500 | sys.excepthook = old_excepthook |
|
2483 | sys.excepthook = old_excepthook | |
2501 | except SystemExit: |
|
2484 | except SystemExit: | |
2502 | self.showtraceback(exception_only=True) |
|
2485 | self.showtraceback(exception_only=True) | |
2503 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2486 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) | |
2504 | except self.custom_exceptions: |
|
2487 | except self.custom_exceptions: | |
2505 | etype,value,tb = sys.exc_info() |
|
2488 | etype,value,tb = sys.exc_info() | |
2506 | self.CustomTB(etype,value,tb) |
|
2489 | self.CustomTB(etype,value,tb) | |
2507 | except: |
|
2490 | except: | |
2508 | self.showtraceback() |
|
2491 | self.showtraceback() | |
2509 | else: |
|
2492 | else: | |
2510 | outflag = 0 |
|
2493 | outflag = 0 | |
2511 | if softspace(sys.stdout, 0): |
|
2494 | if softspace(sys.stdout, 0): | |
2512 |
|
2495 | |||
2513 |
|
2496 | |||
2514 | return outflag |
|
2497 | return outflag | |
2515 |
|
2498 | |||
2516 | # For backwards compatibility |
|
2499 | # For backwards compatibility | |
2517 | runcode = run_code |
|
2500 | runcode = run_code | |
2518 |
|
2501 | |||
2519 | #------------------------------------------------------------------------- |
|
2502 | #------------------------------------------------------------------------- | |
2520 | # Things related to GUI support and pylab |
|
2503 | # Things related to GUI support and pylab | |
2521 | #------------------------------------------------------------------------- |
|
2504 | #------------------------------------------------------------------------- | |
2522 |
|
2505 | |||
2523 | def enable_pylab(self, gui=None, import_all=True): |
|
2506 | def enable_pylab(self, gui=None, import_all=True): | |
2524 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2507 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2525 |
|
2508 | |||
2526 | #------------------------------------------------------------------------- |
|
2509 | #------------------------------------------------------------------------- | |
2527 | # Utilities |
|
2510 | # Utilities | |
2528 | #------------------------------------------------------------------------- |
|
2511 | #------------------------------------------------------------------------- | |
2529 |
|
2512 | |||
2530 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2513 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): | |
2531 | """Expand python variables in a string. |
|
2514 | """Expand python variables in a string. | |
2532 |
|
2515 | |||
2533 | The depth argument indicates how many frames above the caller should |
|
2516 | The depth argument indicates how many frames above the caller should | |
2534 | be walked to look for the local namespace where to expand variables. |
|
2517 | be walked to look for the local namespace where to expand variables. | |
2535 |
|
2518 | |||
2536 | The global namespace for expansion is always the user's interactive |
|
2519 | The global namespace for expansion is always the user's interactive | |
2537 | namespace. |
|
2520 | namespace. | |
2538 | """ |
|
2521 | """ | |
2539 | ns = self.user_ns.copy() |
|
2522 | ns = self.user_ns.copy() | |
2540 | ns.update(sys._getframe(depth+1).f_locals) |
|
2523 | ns.update(sys._getframe(depth+1).f_locals) | |
2541 | ns.pop('self', None) |
|
2524 | ns.pop('self', None) | |
2542 | return formatter.format(cmd, **ns) |
|
2525 | return formatter.format(cmd, **ns) | |
2543 |
|
2526 | |||
2544 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2527 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2545 | """Make a new tempfile and return its filename. |
|
2528 | """Make a new tempfile and return its filename. | |
2546 |
|
2529 | |||
2547 | This makes a call to tempfile.mktemp, but it registers the created |
|
2530 | This makes a call to tempfile.mktemp, but it registers the created | |
2548 | filename internally so ipython cleans it up at exit time. |
|
2531 | filename internally so ipython cleans it up at exit time. | |
2549 |
|
2532 | |||
2550 | Optional inputs: |
|
2533 | Optional inputs: | |
2551 |
|
2534 | |||
2552 | - data(None): if data is given, it gets written out to the temp file |
|
2535 | - data(None): if data is given, it gets written out to the temp file | |
2553 | immediately, and the file is closed again.""" |
|
2536 | immediately, and the file is closed again.""" | |
2554 |
|
2537 | |||
2555 | filename = tempfile.mktemp('.py', prefix) |
|
2538 | filename = tempfile.mktemp('.py', prefix) | |
2556 | self.tempfiles.append(filename) |
|
2539 | self.tempfiles.append(filename) | |
2557 |
|
2540 | |||
2558 | if data: |
|
2541 | if data: | |
2559 | tmp_file = open(filename,'w') |
|
2542 | tmp_file = open(filename,'w') | |
2560 | tmp_file.write(data) |
|
2543 | tmp_file.write(data) | |
2561 | tmp_file.close() |
|
2544 | tmp_file.close() | |
2562 | return filename |
|
2545 | return filename | |
2563 |
|
2546 | |||
2564 | # TODO: This should be removed when Term is refactored. |
|
2547 | # TODO: This should be removed when Term is refactored. | |
2565 | def write(self,data): |
|
2548 | def write(self,data): | |
2566 | """Write a string to the default output""" |
|
2549 | """Write a string to the default output""" | |
2567 | io.stdout.write(data) |
|
2550 | io.stdout.write(data) | |
2568 |
|
2551 | |||
2569 | # TODO: This should be removed when Term is refactored. |
|
2552 | # TODO: This should be removed when Term is refactored. | |
2570 | def write_err(self,data): |
|
2553 | def write_err(self,data): | |
2571 | """Write a string to the default error output""" |
|
2554 | """Write a string to the default error output""" | |
2572 | io.stderr.write(data) |
|
2555 | io.stderr.write(data) | |
2573 |
|
2556 | |||
2574 | def ask_yes_no(self, prompt, default=None): |
|
2557 | def ask_yes_no(self, prompt, default=None): | |
2575 | if self.quiet: |
|
2558 | if self.quiet: | |
2576 | return True |
|
2559 | return True | |
2577 | return ask_yes_no(prompt,default) |
|
2560 | return ask_yes_no(prompt,default) | |
2578 |
|
2561 | |||
2579 | def show_usage(self): |
|
2562 | def show_usage(self): | |
2580 | """Show a usage message""" |
|
2563 | """Show a usage message""" | |
2581 | page.page(IPython.core.usage.interactive_usage) |
|
2564 | page.page(IPython.core.usage.interactive_usage) | |
2582 |
|
2565 | |||
2583 | def find_user_code(self, target, raw=True): |
|
2566 | def find_user_code(self, target, raw=True): | |
2584 | """Get a code string from history, file, or a string or macro. |
|
2567 | """Get a code string from history, file, or a string or macro. | |
2585 |
|
2568 | |||
2586 | This is mainly used by magic functions. |
|
2569 | This is mainly used by magic functions. | |
2587 |
|
2570 | |||
2588 | Parameters |
|
2571 | Parameters | |
2589 | ---------- |
|
2572 | ---------- | |
2590 | target : str |
|
2573 | target : str | |
2591 | A string specifying code to retrieve. This will be tried respectively |
|
2574 | A string specifying code to retrieve. This will be tried respectively | |
2592 | as: ranges of input history (see %history for syntax), a filename, or |
|
2575 | as: ranges of input history (see %history for syntax), a filename, or | |
2593 | an expression evaluating to a string or Macro in the user namespace. |
|
2576 | an expression evaluating to a string or Macro in the user namespace. | |
2594 | raw : bool |
|
2577 | raw : bool | |
2595 | If true (default), retrieve raw history. Has no effect on the other |
|
2578 | If true (default), retrieve raw history. Has no effect on the other | |
2596 | retrieval mechanisms. |
|
2579 | retrieval mechanisms. | |
2597 |
|
2580 | |||
2598 | Returns |
|
2581 | Returns | |
2599 | ------- |
|
2582 | ------- | |
2600 | A string of code. |
|
2583 | A string of code. | |
2601 |
|
2584 | |||
2602 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2585 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
2603 | to an object of another type. In each case, .args[0] is a printable |
|
2586 | to an object of another type. In each case, .args[0] is a printable | |
2604 | message. |
|
2587 | message. | |
2605 | """ |
|
2588 | """ | |
2606 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2589 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
2607 | if code: |
|
2590 | if code: | |
2608 | return code |
|
2591 | return code | |
2609 | if os.path.isfile(target): # Read file |
|
2592 | if os.path.isfile(target): # Read file | |
2610 | return open(target, "r").read() |
|
2593 | return open(target, "r").read() | |
2611 |
|
2594 | |||
2612 | try: # User namespace |
|
2595 | try: # User namespace | |
2613 | codeobj = eval(target, self.user_ns) |
|
2596 | codeobj = eval(target, self.user_ns) | |
2614 | except Exception: |
|
2597 | except Exception: | |
2615 | raise ValueError(("'%s' was not found in history, as a file, nor in" |
|
2598 | raise ValueError(("'%s' was not found in history, as a file, nor in" | |
2616 | " the user namespace.") % target) |
|
2599 | " the user namespace.") % target) | |
2617 | if isinstance(codeobj, basestring): |
|
2600 | if isinstance(codeobj, basestring): | |
2618 | return codeobj |
|
2601 | return codeobj | |
2619 | elif isinstance(codeobj, Macro): |
|
2602 | elif isinstance(codeobj, Macro): | |
2620 | return codeobj.value |
|
2603 | return codeobj.value | |
2621 |
|
2604 | |||
2622 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2605 | raise TypeError("%s is neither a string nor a macro." % target, | |
2623 | codeobj) |
|
2606 | codeobj) | |
2624 |
|
2607 | |||
2625 | #------------------------------------------------------------------------- |
|
2608 | #------------------------------------------------------------------------- | |
2626 | # Things related to IPython exiting |
|
2609 | # Things related to IPython exiting | |
2627 | #------------------------------------------------------------------------- |
|
2610 | #------------------------------------------------------------------------- | |
2628 | def atexit_operations(self): |
|
2611 | def atexit_operations(self): | |
2629 | """This will be executed at the time of exit. |
|
2612 | """This will be executed at the time of exit. | |
2630 |
|
2613 | |||
2631 | Cleanup operations and saving of persistent data that is done |
|
2614 | Cleanup operations and saving of persistent data that is done | |
2632 | unconditionally by IPython should be performed here. |
|
2615 | unconditionally by IPython should be performed here. | |
2633 |
|
2616 | |||
2634 | For things that may depend on startup flags or platform specifics (such |
|
2617 | For things that may depend on startup flags or platform specifics (such | |
2635 | as having readline or not), register a separate atexit function in the |
|
2618 | as having readline or not), register a separate atexit function in the | |
2636 | code that has the appropriate information, rather than trying to |
|
2619 | code that has the appropriate information, rather than trying to | |
2637 | clutter |
|
2620 | clutter | |
2638 | """ |
|
2621 | """ | |
2639 | # Close the history session (this stores the end time and line count) |
|
2622 | # Close the history session (this stores the end time and line count) | |
2640 | # this must be *before* the tempfile cleanup, in case of temporary |
|
2623 | # this must be *before* the tempfile cleanup, in case of temporary | |
2641 | # history db |
|
2624 | # history db | |
2642 | self.history_manager.end_session() |
|
2625 | self.history_manager.end_session() | |
2643 |
|
2626 | |||
2644 | # Cleanup all tempfiles left around |
|
2627 | # Cleanup all tempfiles left around | |
2645 | for tfile in self.tempfiles: |
|
2628 | for tfile in self.tempfiles: | |
2646 | try: |
|
2629 | try: | |
2647 | os.unlink(tfile) |
|
2630 | os.unlink(tfile) | |
2648 | except OSError: |
|
2631 | except OSError: | |
2649 | pass |
|
2632 | pass | |
2650 |
|
2633 | |||
2651 | # Clear all user namespaces to release all references cleanly. |
|
2634 | # Clear all user namespaces to release all references cleanly. | |
2652 | self.reset(new_session=False) |
|
2635 | self.reset(new_session=False) | |
2653 |
|
2636 | |||
2654 | # Run user hooks |
|
2637 | # Run user hooks | |
2655 | self.hooks.shutdown_hook() |
|
2638 | self.hooks.shutdown_hook() | |
2656 |
|
2639 | |||
2657 | def cleanup(self): |
|
2640 | def cleanup(self): | |
2658 | self.restore_sys_module_state() |
|
2641 | self.restore_sys_module_state() | |
2659 |
|
2642 | |||
2660 |
|
2643 | |||
2661 | class InteractiveShellABC(object): |
|
2644 | class InteractiveShellABC(object): | |
2662 | """An abstract base class for InteractiveShell.""" |
|
2645 | """An abstract base class for InteractiveShell.""" | |
2663 | __metaclass__ = abc.ABCMeta |
|
2646 | __metaclass__ = abc.ABCMeta | |
2664 |
|
2647 | |||
2665 | InteractiveShellABC.register(InteractiveShell) |
|
2648 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,3678 +1,3677 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | # Copyright (C) 2008-2011 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ as builtin_mod |
|
18 | import __builtin__ as builtin_mod | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import imp |
|
22 | import imp | |
23 | import os |
|
23 | import os | |
24 | import sys |
|
24 | import sys | |
25 | import shutil |
|
25 | import shutil | |
26 | import re |
|
26 | import re | |
27 | import time |
|
27 | import time | |
28 | from StringIO import StringIO |
|
28 | from StringIO import StringIO | |
29 | from getopt import getopt,GetoptError |
|
29 | from getopt import getopt,GetoptError | |
30 | from pprint import pformat |
|
30 | from pprint import pformat | |
31 | from xmlrpclib import ServerProxy |
|
31 | from xmlrpclib import ServerProxy | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | import IPython |
|
44 | import IPython | |
45 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
46 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.core.profiledir import ProfileDir |
|
49 | from IPython.core.profiledir import ProfileDir | |
50 | from IPython.core.macro import Macro |
|
50 | from IPython.core.macro import Macro | |
51 | from IPython.core import magic_arguments, page |
|
51 | from IPython.core import magic_arguments, page | |
52 | from IPython.core.prefilter import ESC_MAGIC |
|
52 | from IPython.core.prefilter import ESC_MAGIC | |
53 | from IPython.lib.pylabtools import mpl_runner |
|
53 | from IPython.lib.pylabtools import mpl_runner | |
54 | from IPython.testing.skipdoctest import skip_doctest |
|
54 | from IPython.testing.skipdoctest import skip_doctest | |
55 | from IPython.utils import py3compat |
|
55 | from IPython.utils import py3compat | |
56 | from IPython.utils.io import file_read, nlprint |
|
56 | from IPython.utils.io import file_read, nlprint | |
57 | from IPython.utils.module_paths import find_mod |
|
57 | from IPython.utils.module_paths import find_mod | |
58 | from IPython.utils.path import get_py_filename, unquote_filename |
|
58 | from IPython.utils.path import get_py_filename, unquote_filename | |
59 | from IPython.utils.process import arg_split, abbrev_cwd |
|
59 | from IPython.utils.process import arg_split, abbrev_cwd | |
60 | from IPython.utils.terminal import set_term_title |
|
60 | from IPython.utils.terminal import set_term_title | |
61 | from IPython.utils.text import LSString, SList, format_screen |
|
61 | from IPython.utils.text import LSString, SList, format_screen | |
62 | from IPython.utils.timing import clock, clock2 |
|
62 | from IPython.utils.timing import clock, clock2 | |
63 | from IPython.utils.warn import warn, error |
|
63 | from IPython.utils.warn import warn, error | |
64 | from IPython.utils.ipstruct import Struct |
|
64 | from IPython.utils.ipstruct import Struct | |
65 | from IPython.config.application import Application |
|
65 | from IPython.config.application import Application | |
66 |
|
66 | |||
67 | #----------------------------------------------------------------------------- |
|
67 | #----------------------------------------------------------------------------- | |
68 | # Utility functions |
|
68 | # Utility functions | |
69 | #----------------------------------------------------------------------------- |
|
69 | #----------------------------------------------------------------------------- | |
70 |
|
70 | |||
71 | def on_off(tag): |
|
71 | def on_off(tag): | |
72 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
72 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
73 | return ['OFF','ON'][tag] |
|
73 | return ['OFF','ON'][tag] | |
74 |
|
74 | |||
75 | class Bunch: pass |
|
75 | class Bunch: pass | |
76 |
|
76 | |||
77 | def compress_dhist(dh): |
|
77 | def compress_dhist(dh): | |
78 | head, tail = dh[:-10], dh[-10:] |
|
78 | head, tail = dh[:-10], dh[-10:] | |
79 |
|
79 | |||
80 | newhead = [] |
|
80 | newhead = [] | |
81 | done = set() |
|
81 | done = set() | |
82 | for h in head: |
|
82 | for h in head: | |
83 | if h in done: |
|
83 | if h in done: | |
84 | continue |
|
84 | continue | |
85 | newhead.append(h) |
|
85 | newhead.append(h) | |
86 | done.add(h) |
|
86 | done.add(h) | |
87 |
|
87 | |||
88 | return newhead + tail |
|
88 | return newhead + tail | |
89 |
|
89 | |||
90 | def needs_local_scope(func): |
|
90 | def needs_local_scope(func): | |
91 | """Decorator to mark magic functions which need to local scope to run.""" |
|
91 | """Decorator to mark magic functions which need to local scope to run.""" | |
92 | func.needs_local_scope = True |
|
92 | func.needs_local_scope = True | |
93 | return func |
|
93 | return func | |
94 |
|
94 | |||
95 |
|
95 | |||
96 | # Used for exception handling in magic_edit |
|
96 | # Used for exception handling in magic_edit | |
97 | class MacroToEdit(ValueError): pass |
|
97 | class MacroToEdit(ValueError): pass | |
98 |
|
98 | |||
99 | #*************************************************************************** |
|
99 | #*************************************************************************** | |
100 | # Main class implementing Magic functionality |
|
100 | # Main class implementing Magic functionality | |
101 |
|
101 | |||
102 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
102 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
103 | # on construction of the main InteractiveShell object. Something odd is going |
|
103 | # on construction of the main InteractiveShell object. Something odd is going | |
104 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
104 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
105 | # eventually this needs to be clarified. |
|
105 | # eventually this needs to be clarified. | |
106 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
106 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
107 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
107 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
108 | # make Magic a configurable that InteractiveShell does not subclass. |
|
108 | # make Magic a configurable that InteractiveShell does not subclass. | |
109 |
|
109 | |||
110 | class Magic: |
|
110 | class Magic: | |
111 | """Magic functions for InteractiveShell. |
|
111 | """Magic functions for InteractiveShell. | |
112 |
|
112 | |||
113 | Shell functions which can be reached as %function_name. All magic |
|
113 | Shell functions which can be reached as %function_name. All magic | |
114 | functions should accept a string, which they can parse for their own |
|
114 | functions should accept a string, which they can parse for their own | |
115 | needs. This can make some functions easier to type, eg `%cd ../` |
|
115 | needs. This can make some functions easier to type, eg `%cd ../` | |
116 | vs. `%cd("../")` |
|
116 | vs. `%cd("../")` | |
117 |
|
117 | |||
118 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
118 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
119 | at the command line, but it is is needed in the definition. """ |
|
119 | at the command line, but it is is needed in the definition. """ | |
120 |
|
120 | |||
121 | # class globals |
|
121 | # class globals | |
122 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
122 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
123 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
123 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
124 |
|
124 | |||
125 |
|
125 | |||
126 | configurables = None |
|
126 | configurables = None | |
127 | #...................................................................... |
|
127 | #...................................................................... | |
128 | # some utility functions |
|
128 | # some utility functions | |
129 |
|
129 | |||
130 | def __init__(self,shell): |
|
130 | def __init__(self,shell): | |
131 |
|
131 | |||
132 | self.options_table = {} |
|
132 | self.options_table = {} | |
133 | if profile is None: |
|
133 | if profile is None: | |
134 | self.magic_prun = self.profile_missing_notice |
|
134 | self.magic_prun = self.profile_missing_notice | |
135 | self.shell = shell |
|
135 | self.shell = shell | |
136 | if self.configurables is None: |
|
136 | if self.configurables is None: | |
137 | self.configurables = [] |
|
137 | self.configurables = [] | |
138 |
|
138 | |||
139 | # namespace for holding state we may need |
|
139 | # namespace for holding state we may need | |
140 | self._magic_state = Bunch() |
|
140 | self._magic_state = Bunch() | |
141 |
|
141 | |||
142 | def profile_missing_notice(self, *args, **kwargs): |
|
142 | def profile_missing_notice(self, *args, **kwargs): | |
143 | error("""\ |
|
143 | error("""\ | |
144 | The profile module could not be found. It has been removed from the standard |
|
144 | The profile module could not be found. It has been removed from the standard | |
145 | python packages because of its non-free license. To use profiling, install the |
|
145 | python packages because of its non-free license. To use profiling, install the | |
146 | python-profiler package from non-free.""") |
|
146 | python-profiler package from non-free.""") | |
147 |
|
147 | |||
148 | def default_option(self,fn,optstr): |
|
148 | def default_option(self,fn,optstr): | |
149 | """Make an entry in the options_table for fn, with value optstr""" |
|
149 | """Make an entry in the options_table for fn, with value optstr""" | |
150 |
|
150 | |||
151 | if fn not in self.lsmagic(): |
|
151 | if fn not in self.lsmagic(): | |
152 | error("%s is not a magic function" % fn) |
|
152 | error("%s is not a magic function" % fn) | |
153 | self.options_table[fn] = optstr |
|
153 | self.options_table[fn] = optstr | |
154 |
|
154 | |||
155 | def lsmagic(self): |
|
155 | def lsmagic(self): | |
156 | """Return a list of currently available magic functions. |
|
156 | """Return a list of currently available magic functions. | |
157 |
|
157 | |||
158 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
158 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
159 | ['magic_ls','magic_cd',...]""" |
|
159 | ['magic_ls','magic_cd',...]""" | |
160 |
|
160 | |||
161 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
161 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
162 |
|
162 | |||
163 | # magics in class definition |
|
163 | # magics in class definition | |
164 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
164 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
165 | callable(Magic.__dict__[fn]) |
|
165 | callable(Magic.__dict__[fn]) | |
166 | # in instance namespace (run-time user additions) |
|
166 | # in instance namespace (run-time user additions) | |
167 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
167 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
168 | callable(self.__dict__[fn]) |
|
168 | callable(self.__dict__[fn]) | |
169 | # and bound magics by user (so they can access self): |
|
169 | # and bound magics by user (so they can access self): | |
170 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
170 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
171 | callable(self.__class__.__dict__[fn]) |
|
171 | callable(self.__class__.__dict__[fn]) | |
172 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
172 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
173 | filter(inst_magic,self.__dict__.keys()) + \ |
|
173 | filter(inst_magic,self.__dict__.keys()) + \ | |
174 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
174 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
175 | out = [] |
|
175 | out = [] | |
176 | for fn in set(magics): |
|
176 | for fn in set(magics): | |
177 | out.append(fn.replace('magic_','',1)) |
|
177 | out.append(fn.replace('magic_','',1)) | |
178 | out.sort() |
|
178 | out.sort() | |
179 | return out |
|
179 | return out | |
180 |
|
180 | |||
181 | def extract_input_lines(self, range_str, raw=False): |
|
181 | def extract_input_lines(self, range_str, raw=False): | |
182 | """Return as a string a set of input history slices. |
|
182 | """Return as a string a set of input history slices. | |
183 |
|
183 | |||
184 | Inputs: |
|
184 | Inputs: | |
185 |
|
185 | |||
186 | - range_str: the set of slices is given as a string, like |
|
186 | - range_str: the set of slices is given as a string, like | |
187 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions |
|
187 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions | |
188 | which get their arguments as strings. The number before the / is the |
|
188 | which get their arguments as strings. The number before the / is the | |
189 | session number: ~n goes n back from the current session. |
|
189 | session number: ~n goes n back from the current session. | |
190 |
|
190 | |||
191 | Optional inputs: |
|
191 | Optional inputs: | |
192 |
|
192 | |||
193 | - raw(False): by default, the processed input is used. If this is |
|
193 | - raw(False): by default, the processed input is used. If this is | |
194 | true, the raw input history is used instead. |
|
194 | true, the raw input history is used instead. | |
195 |
|
195 | |||
196 | Note that slices can be called with two notations: |
|
196 | Note that slices can be called with two notations: | |
197 |
|
197 | |||
198 | N:M -> standard python form, means including items N...(M-1). |
|
198 | N:M -> standard python form, means including items N...(M-1). | |
199 |
|
199 | |||
200 | N-M -> include items N..M (closed endpoint).""" |
|
200 | N-M -> include items N..M (closed endpoint).""" | |
201 | lines = self.shell.history_manager.\ |
|
201 | lines = self.shell.history_manager.\ | |
202 | get_range_by_str(range_str, raw=raw) |
|
202 | get_range_by_str(range_str, raw=raw) | |
203 | return "\n".join(x for _, _, x in lines) |
|
203 | return "\n".join(x for _, _, x in lines) | |
204 |
|
204 | |||
205 | def arg_err(self,func): |
|
205 | def arg_err(self,func): | |
206 | """Print docstring if incorrect arguments were passed""" |
|
206 | """Print docstring if incorrect arguments were passed""" | |
207 | print 'Error in arguments:' |
|
207 | print 'Error in arguments:' | |
208 | print oinspect.getdoc(func) |
|
208 | print oinspect.getdoc(func) | |
209 |
|
209 | |||
210 | def format_latex(self,strng): |
|
210 | def format_latex(self,strng): | |
211 | """Format a string for latex inclusion.""" |
|
211 | """Format a string for latex inclusion.""" | |
212 |
|
212 | |||
213 | # Characters that need to be escaped for latex: |
|
213 | # Characters that need to be escaped for latex: | |
214 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
214 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
215 | # Magic command names as headers: |
|
215 | # Magic command names as headers: | |
216 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
216 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
217 | re.MULTILINE) |
|
217 | re.MULTILINE) | |
218 | # Magic commands |
|
218 | # Magic commands | |
219 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
219 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
220 | re.MULTILINE) |
|
220 | re.MULTILINE) | |
221 | # Paragraph continue |
|
221 | # Paragraph continue | |
222 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
222 | par_re = re.compile(r'\\$',re.MULTILINE) | |
223 |
|
223 | |||
224 | # The "\n" symbol |
|
224 | # The "\n" symbol | |
225 | newline_re = re.compile(r'\\n') |
|
225 | newline_re = re.compile(r'\\n') | |
226 |
|
226 | |||
227 | # Now build the string for output: |
|
227 | # Now build the string for output: | |
228 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
228 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
229 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
229 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
230 | strng) |
|
230 | strng) | |
231 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
231 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
232 | strng = par_re.sub(r'\\\\',strng) |
|
232 | strng = par_re.sub(r'\\\\',strng) | |
233 | strng = escape_re.sub(r'\\\1',strng) |
|
233 | strng = escape_re.sub(r'\\\1',strng) | |
234 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
234 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
235 | return strng |
|
235 | return strng | |
236 |
|
236 | |||
237 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
237 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
238 | """Parse options passed to an argument string. |
|
238 | """Parse options passed to an argument string. | |
239 |
|
239 | |||
240 | The interface is similar to that of getopt(), but it returns back a |
|
240 | The interface is similar to that of getopt(), but it returns back a | |
241 | Struct with the options as keys and the stripped argument string still |
|
241 | Struct with the options as keys and the stripped argument string still | |
242 | as a string. |
|
242 | as a string. | |
243 |
|
243 | |||
244 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
244 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
245 | This allows us to easily expand variables, glob files, quote |
|
245 | This allows us to easily expand variables, glob files, quote | |
246 | arguments, etc. |
|
246 | arguments, etc. | |
247 |
|
247 | |||
248 | Options: |
|
248 | Options: | |
249 | -mode: default 'string'. If given as 'list', the argument string is |
|
249 | -mode: default 'string'. If given as 'list', the argument string is | |
250 | returned as a list (split on whitespace) instead of a string. |
|
250 | returned as a list (split on whitespace) instead of a string. | |
251 |
|
251 | |||
252 | -list_all: put all option values in lists. Normally only options |
|
252 | -list_all: put all option values in lists. Normally only options | |
253 | appearing more than once are put in a list. |
|
253 | appearing more than once are put in a list. | |
254 |
|
254 | |||
255 | -posix (True): whether to split the input line in POSIX mode or not, |
|
255 | -posix (True): whether to split the input line in POSIX mode or not, | |
256 | as per the conventions outlined in the shlex module from the |
|
256 | as per the conventions outlined in the shlex module from the | |
257 | standard library.""" |
|
257 | standard library.""" | |
258 |
|
258 | |||
259 | # inject default options at the beginning of the input line |
|
259 | # inject default options at the beginning of the input line | |
260 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
260 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
261 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
261 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
262 |
|
262 | |||
263 | mode = kw.get('mode','string') |
|
263 | mode = kw.get('mode','string') | |
264 | if mode not in ['string','list']: |
|
264 | if mode not in ['string','list']: | |
265 | raise ValueError,'incorrect mode given: %s' % mode |
|
265 | raise ValueError,'incorrect mode given: %s' % mode | |
266 | # Get options |
|
266 | # Get options | |
267 | list_all = kw.get('list_all',0) |
|
267 | list_all = kw.get('list_all',0) | |
268 | posix = kw.get('posix', os.name == 'posix') |
|
268 | posix = kw.get('posix', os.name == 'posix') | |
269 |
|
269 | |||
270 | # Check if we have more than one argument to warrant extra processing: |
|
270 | # Check if we have more than one argument to warrant extra processing: | |
271 | odict = {} # Dictionary with options |
|
271 | odict = {} # Dictionary with options | |
272 | args = arg_str.split() |
|
272 | args = arg_str.split() | |
273 | if len(args) >= 1: |
|
273 | if len(args) >= 1: | |
274 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
274 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
275 | # need to look for options |
|
275 | # need to look for options | |
276 | argv = arg_split(arg_str,posix) |
|
276 | argv = arg_split(arg_str,posix) | |
277 | # Do regular option processing |
|
277 | # Do regular option processing | |
278 | try: |
|
278 | try: | |
279 | opts,args = getopt(argv,opt_str,*long_opts) |
|
279 | opts,args = getopt(argv,opt_str,*long_opts) | |
280 | except GetoptError,e: |
|
280 | except GetoptError,e: | |
281 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
281 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
282 | " ".join(long_opts))) |
|
282 | " ".join(long_opts))) | |
283 | for o,a in opts: |
|
283 | for o,a in opts: | |
284 | if o.startswith('--'): |
|
284 | if o.startswith('--'): | |
285 | o = o[2:] |
|
285 | o = o[2:] | |
286 | else: |
|
286 | else: | |
287 | o = o[1:] |
|
287 | o = o[1:] | |
288 | try: |
|
288 | try: | |
289 | odict[o].append(a) |
|
289 | odict[o].append(a) | |
290 | except AttributeError: |
|
290 | except AttributeError: | |
291 | odict[o] = [odict[o],a] |
|
291 | odict[o] = [odict[o],a] | |
292 | except KeyError: |
|
292 | except KeyError: | |
293 | if list_all: |
|
293 | if list_all: | |
294 | odict[o] = [a] |
|
294 | odict[o] = [a] | |
295 | else: |
|
295 | else: | |
296 | odict[o] = a |
|
296 | odict[o] = a | |
297 |
|
297 | |||
298 | # Prepare opts,args for return |
|
298 | # Prepare opts,args for return | |
299 | opts = Struct(odict) |
|
299 | opts = Struct(odict) | |
300 | if mode == 'string': |
|
300 | if mode == 'string': | |
301 | args = ' '.join(args) |
|
301 | args = ' '.join(args) | |
302 |
|
302 | |||
303 | return opts,args |
|
303 | return opts,args | |
304 |
|
304 | |||
305 | #...................................................................... |
|
305 | #...................................................................... | |
306 | # And now the actual magic functions |
|
306 | # And now the actual magic functions | |
307 |
|
307 | |||
308 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
308 | # Functions for IPython shell work (vars,funcs, config, etc) | |
309 | def magic_lsmagic(self, parameter_s = ''): |
|
309 | def magic_lsmagic(self, parameter_s = ''): | |
310 | """List currently available magic functions.""" |
|
310 | """List currently available magic functions.""" | |
311 | mesc = ESC_MAGIC |
|
311 | mesc = ESC_MAGIC | |
312 | print 'Available magic functions:\n'+mesc+\ |
|
312 | print 'Available magic functions:\n'+mesc+\ | |
313 | (' '+mesc).join(self.lsmagic()) |
|
313 | (' '+mesc).join(self.lsmagic()) | |
314 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
314 | print '\n' + Magic.auto_status[self.shell.automagic] | |
315 | return None |
|
315 | return None | |
316 |
|
316 | |||
317 | def magic_magic(self, parameter_s = ''): |
|
317 | def magic_magic(self, parameter_s = ''): | |
318 | """Print information about the magic function system. |
|
318 | """Print information about the magic function system. | |
319 |
|
319 | |||
320 | Supported formats: -latex, -brief, -rest |
|
320 | Supported formats: -latex, -brief, -rest | |
321 | """ |
|
321 | """ | |
322 |
|
322 | |||
323 | mode = '' |
|
323 | mode = '' | |
324 | try: |
|
324 | try: | |
325 | if parameter_s.split()[0] == '-latex': |
|
325 | if parameter_s.split()[0] == '-latex': | |
326 | mode = 'latex' |
|
326 | mode = 'latex' | |
327 | if parameter_s.split()[0] == '-brief': |
|
327 | if parameter_s.split()[0] == '-brief': | |
328 | mode = 'brief' |
|
328 | mode = 'brief' | |
329 | if parameter_s.split()[0] == '-rest': |
|
329 | if parameter_s.split()[0] == '-rest': | |
330 | mode = 'rest' |
|
330 | mode = 'rest' | |
331 | rest_docs = [] |
|
331 | rest_docs = [] | |
332 | except: |
|
332 | except: | |
333 | pass |
|
333 | pass | |
334 |
|
334 | |||
335 | magic_docs = [] |
|
335 | magic_docs = [] | |
336 | for fname in self.lsmagic(): |
|
336 | for fname in self.lsmagic(): | |
337 | mname = 'magic_' + fname |
|
337 | mname = 'magic_' + fname | |
338 | for space in (Magic,self,self.__class__): |
|
338 | for space in (Magic,self,self.__class__): | |
339 | try: |
|
339 | try: | |
340 | fn = space.__dict__[mname] |
|
340 | fn = space.__dict__[mname] | |
341 | except KeyError: |
|
341 | except KeyError: | |
342 | pass |
|
342 | pass | |
343 | else: |
|
343 | else: | |
344 | break |
|
344 | break | |
345 | if mode == 'brief': |
|
345 | if mode == 'brief': | |
346 | # only first line |
|
346 | # only first line | |
347 | if fn.__doc__: |
|
347 | if fn.__doc__: | |
348 | fndoc = fn.__doc__.split('\n',1)[0] |
|
348 | fndoc = fn.__doc__.split('\n',1)[0] | |
349 | else: |
|
349 | else: | |
350 | fndoc = 'No documentation' |
|
350 | fndoc = 'No documentation' | |
351 | else: |
|
351 | else: | |
352 | if fn.__doc__: |
|
352 | if fn.__doc__: | |
353 | fndoc = fn.__doc__.rstrip() |
|
353 | fndoc = fn.__doc__.rstrip() | |
354 | else: |
|
354 | else: | |
355 | fndoc = 'No documentation' |
|
355 | fndoc = 'No documentation' | |
356 |
|
356 | |||
357 |
|
357 | |||
358 | if mode == 'rest': |
|
358 | if mode == 'rest': | |
359 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
359 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
360 | fname,fndoc)) |
|
360 | fname,fndoc)) | |
361 |
|
361 | |||
362 | else: |
|
362 | else: | |
363 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
363 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
364 | fname,fndoc)) |
|
364 | fname,fndoc)) | |
365 |
|
365 | |||
366 | magic_docs = ''.join(magic_docs) |
|
366 | magic_docs = ''.join(magic_docs) | |
367 |
|
367 | |||
368 | if mode == 'rest': |
|
368 | if mode == 'rest': | |
369 | return "".join(rest_docs) |
|
369 | return "".join(rest_docs) | |
370 |
|
370 | |||
371 | if mode == 'latex': |
|
371 | if mode == 'latex': | |
372 | print self.format_latex(magic_docs) |
|
372 | print self.format_latex(magic_docs) | |
373 | return |
|
373 | return | |
374 | else: |
|
374 | else: | |
375 | magic_docs = format_screen(magic_docs) |
|
375 | magic_docs = format_screen(magic_docs) | |
376 | if mode == 'brief': |
|
376 | if mode == 'brief': | |
377 | return magic_docs |
|
377 | return magic_docs | |
378 |
|
378 | |||
379 | outmsg = """ |
|
379 | outmsg = """ | |
380 | IPython's 'magic' functions |
|
380 | IPython's 'magic' functions | |
381 | =========================== |
|
381 | =========================== | |
382 |
|
382 | |||
383 | The magic function system provides a series of functions which allow you to |
|
383 | The magic function system provides a series of functions which allow you to | |
384 | control the behavior of IPython itself, plus a lot of system-type |
|
384 | control the behavior of IPython itself, plus a lot of system-type | |
385 | features. All these functions are prefixed with a % character, but parameters |
|
385 | features. All these functions are prefixed with a % character, but parameters | |
386 | are given without parentheses or quotes. |
|
386 | are given without parentheses or quotes. | |
387 |
|
387 | |||
388 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
388 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
389 | %automagic function), you don't need to type in the % explicitly. By default, |
|
389 | %automagic function), you don't need to type in the % explicitly. By default, | |
390 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
390 | IPython ships with automagic on, so you should only rarely need the % escape. | |
391 |
|
391 | |||
392 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
392 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
393 | to 'mydir', if it exists. |
|
393 | to 'mydir', if it exists. | |
394 |
|
394 | |||
395 | For a list of the available magic functions, use %lsmagic. For a description |
|
395 | For a list of the available magic functions, use %lsmagic. For a description | |
396 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
396 | of any of them, type %magic_name?, e.g. '%cd?'. | |
397 |
|
397 | |||
398 | Currently the magic system has the following functions:\n""" |
|
398 | Currently the magic system has the following functions:\n""" | |
399 |
|
399 | |||
400 | mesc = ESC_MAGIC |
|
400 | mesc = ESC_MAGIC | |
401 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
401 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
402 | "\n\n%s%s\n\n%s" % (outmsg, |
|
402 | "\n\n%s%s\n\n%s" % (outmsg, | |
403 | magic_docs,mesc,mesc, |
|
403 | magic_docs,mesc,mesc, | |
404 | (' '+mesc).join(self.lsmagic()), |
|
404 | (' '+mesc).join(self.lsmagic()), | |
405 | Magic.auto_status[self.shell.automagic] ) ) |
|
405 | Magic.auto_status[self.shell.automagic] ) ) | |
406 | page.page(outmsg) |
|
406 | page.page(outmsg) | |
407 |
|
407 | |||
408 | def magic_automagic(self, parameter_s = ''): |
|
408 | def magic_automagic(self, parameter_s = ''): | |
409 | """Make magic functions callable without having to type the initial %. |
|
409 | """Make magic functions callable without having to type the initial %. | |
410 |
|
410 | |||
411 | Without argumentsl toggles on/off (when off, you must call it as |
|
411 | Without argumentsl toggles on/off (when off, you must call it as | |
412 | %automagic, of course). With arguments it sets the value, and you can |
|
412 | %automagic, of course). With arguments it sets the value, and you can | |
413 | use any of (case insensitive): |
|
413 | use any of (case insensitive): | |
414 |
|
414 | |||
415 | - on,1,True: to activate |
|
415 | - on,1,True: to activate | |
416 |
|
416 | |||
417 | - off,0,False: to deactivate. |
|
417 | - off,0,False: to deactivate. | |
418 |
|
418 | |||
419 | Note that magic functions have lowest priority, so if there's a |
|
419 | Note that magic functions have lowest priority, so if there's a | |
420 | variable whose name collides with that of a magic fn, automagic won't |
|
420 | variable whose name collides with that of a magic fn, automagic won't | |
421 | work for that function (you get the variable instead). However, if you |
|
421 | work for that function (you get the variable instead). However, if you | |
422 | delete the variable (del var), the previously shadowed magic function |
|
422 | delete the variable (del var), the previously shadowed magic function | |
423 | becomes visible to automagic again.""" |
|
423 | becomes visible to automagic again.""" | |
424 |
|
424 | |||
425 | arg = parameter_s.lower() |
|
425 | arg = parameter_s.lower() | |
426 | if parameter_s in ('on','1','true'): |
|
426 | if parameter_s in ('on','1','true'): | |
427 | self.shell.automagic = True |
|
427 | self.shell.automagic = True | |
428 | elif parameter_s in ('off','0','false'): |
|
428 | elif parameter_s in ('off','0','false'): | |
429 | self.shell.automagic = False |
|
429 | self.shell.automagic = False | |
430 | else: |
|
430 | else: | |
431 | self.shell.automagic = not self.shell.automagic |
|
431 | self.shell.automagic = not self.shell.automagic | |
432 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
432 | print '\n' + Magic.auto_status[self.shell.automagic] | |
433 |
|
433 | |||
434 | @skip_doctest |
|
434 | @skip_doctest | |
435 | def magic_autocall(self, parameter_s = ''): |
|
435 | def magic_autocall(self, parameter_s = ''): | |
436 | """Make functions callable without having to type parentheses. |
|
436 | """Make functions callable without having to type parentheses. | |
437 |
|
437 | |||
438 | Usage: |
|
438 | Usage: | |
439 |
|
439 | |||
440 | %autocall [mode] |
|
440 | %autocall [mode] | |
441 |
|
441 | |||
442 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
442 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
443 | value is toggled on and off (remembering the previous state). |
|
443 | value is toggled on and off (remembering the previous state). | |
444 |
|
444 | |||
445 | In more detail, these values mean: |
|
445 | In more detail, these values mean: | |
446 |
|
446 | |||
447 | 0 -> fully disabled |
|
447 | 0 -> fully disabled | |
448 |
|
448 | |||
449 | 1 -> active, but do not apply if there are no arguments on the line. |
|
449 | 1 -> active, but do not apply if there are no arguments on the line. | |
450 |
|
450 | |||
451 | In this mode, you get: |
|
451 | In this mode, you get: | |
452 |
|
452 | |||
453 | In [1]: callable |
|
453 | In [1]: callable | |
454 | Out[1]: <built-in function callable> |
|
454 | Out[1]: <built-in function callable> | |
455 |
|
455 | |||
456 | In [2]: callable 'hello' |
|
456 | In [2]: callable 'hello' | |
457 | ------> callable('hello') |
|
457 | ------> callable('hello') | |
458 | Out[2]: False |
|
458 | Out[2]: False | |
459 |
|
459 | |||
460 | 2 -> Active always. Even if no arguments are present, the callable |
|
460 | 2 -> Active always. Even if no arguments are present, the callable | |
461 | object is called: |
|
461 | object is called: | |
462 |
|
462 | |||
463 | In [2]: float |
|
463 | In [2]: float | |
464 | ------> float() |
|
464 | ------> float() | |
465 | Out[2]: 0.0 |
|
465 | Out[2]: 0.0 | |
466 |
|
466 | |||
467 | Note that even with autocall off, you can still use '/' at the start of |
|
467 | Note that even with autocall off, you can still use '/' at the start of | |
468 | a line to treat the first argument on the command line as a function |
|
468 | a line to treat the first argument on the command line as a function | |
469 | and add parentheses to it: |
|
469 | and add parentheses to it: | |
470 |
|
470 | |||
471 | In [8]: /str 43 |
|
471 | In [8]: /str 43 | |
472 | ------> str(43) |
|
472 | ------> str(43) | |
473 | Out[8]: '43' |
|
473 | Out[8]: '43' | |
474 |
|
474 | |||
475 | # all-random (note for auto-testing) |
|
475 | # all-random (note for auto-testing) | |
476 | """ |
|
476 | """ | |
477 |
|
477 | |||
478 | if parameter_s: |
|
478 | if parameter_s: | |
479 | arg = int(parameter_s) |
|
479 | arg = int(parameter_s) | |
480 | else: |
|
480 | else: | |
481 | arg = 'toggle' |
|
481 | arg = 'toggle' | |
482 |
|
482 | |||
483 | if not arg in (0,1,2,'toggle'): |
|
483 | if not arg in (0,1,2,'toggle'): | |
484 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
484 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
485 | return |
|
485 | return | |
486 |
|
486 | |||
487 | if arg in (0,1,2): |
|
487 | if arg in (0,1,2): | |
488 | self.shell.autocall = arg |
|
488 | self.shell.autocall = arg | |
489 | else: # toggle |
|
489 | else: # toggle | |
490 | if self.shell.autocall: |
|
490 | if self.shell.autocall: | |
491 | self._magic_state.autocall_save = self.shell.autocall |
|
491 | self._magic_state.autocall_save = self.shell.autocall | |
492 | self.shell.autocall = 0 |
|
492 | self.shell.autocall = 0 | |
493 | else: |
|
493 | else: | |
494 | try: |
|
494 | try: | |
495 | self.shell.autocall = self._magic_state.autocall_save |
|
495 | self.shell.autocall = self._magic_state.autocall_save | |
496 | except AttributeError: |
|
496 | except AttributeError: | |
497 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
497 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
498 |
|
498 | |||
499 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
499 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
500 |
|
500 | |||
501 |
|
501 | |||
502 | def magic_page(self, parameter_s=''): |
|
502 | def magic_page(self, parameter_s=''): | |
503 | """Pretty print the object and display it through a pager. |
|
503 | """Pretty print the object and display it through a pager. | |
504 |
|
504 | |||
505 | %page [options] OBJECT |
|
505 | %page [options] OBJECT | |
506 |
|
506 | |||
507 | If no object is given, use _ (last output). |
|
507 | If no object is given, use _ (last output). | |
508 |
|
508 | |||
509 | Options: |
|
509 | Options: | |
510 |
|
510 | |||
511 | -r: page str(object), don't pretty-print it.""" |
|
511 | -r: page str(object), don't pretty-print it.""" | |
512 |
|
512 | |||
513 | # After a function contributed by Olivier Aubert, slightly modified. |
|
513 | # After a function contributed by Olivier Aubert, slightly modified. | |
514 |
|
514 | |||
515 | # Process options/args |
|
515 | # Process options/args | |
516 | opts,args = self.parse_options(parameter_s,'r') |
|
516 | opts,args = self.parse_options(parameter_s,'r') | |
517 | raw = 'r' in opts |
|
517 | raw = 'r' in opts | |
518 |
|
518 | |||
519 | oname = args and args or '_' |
|
519 | oname = args and args or '_' | |
520 | info = self._ofind(oname) |
|
520 | info = self._ofind(oname) | |
521 | if info['found']: |
|
521 | if info['found']: | |
522 | txt = (raw and str or pformat)( info['obj'] ) |
|
522 | txt = (raw and str or pformat)( info['obj'] ) | |
523 | page.page(txt) |
|
523 | page.page(txt) | |
524 | else: |
|
524 | else: | |
525 | print 'Object `%s` not found' % oname |
|
525 | print 'Object `%s` not found' % oname | |
526 |
|
526 | |||
527 | def magic_profile(self, parameter_s=''): |
|
527 | def magic_profile(self, parameter_s=''): | |
528 | """Print your currently active IPython profile.""" |
|
528 | """Print your currently active IPython profile.""" | |
529 | from IPython.core.application import BaseIPythonApplication |
|
529 | from IPython.core.application import BaseIPythonApplication | |
530 | if BaseIPythonApplication.initialized(): |
|
530 | if BaseIPythonApplication.initialized(): | |
531 | print BaseIPythonApplication.instance().profile |
|
531 | print BaseIPythonApplication.instance().profile | |
532 | else: |
|
532 | else: | |
533 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
533 | error("profile is an application-level value, but you don't appear to be in an IPython application") | |
534 |
|
534 | |||
535 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
535 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
536 | """Provide detailed information about an object. |
|
536 | """Provide detailed information about an object. | |
537 |
|
537 | |||
538 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
538 | '%pinfo object' is just a synonym for object? or ?object.""" | |
539 |
|
539 | |||
540 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
540 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
541 |
|
541 | |||
542 |
|
542 | |||
543 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
543 | # detail_level: 0 -> obj? , 1 -> obj?? | |
544 | detail_level = 0 |
|
544 | detail_level = 0 | |
545 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
545 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
546 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
546 | # happen if the user types 'pinfo foo?' at the cmd line. | |
547 | pinfo,qmark1,oname,qmark2 = \ |
|
547 | pinfo,qmark1,oname,qmark2 = \ | |
548 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
548 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
549 | if pinfo or qmark1 or qmark2: |
|
549 | if pinfo or qmark1 or qmark2: | |
550 | detail_level = 1 |
|
550 | detail_level = 1 | |
551 | if "*" in oname: |
|
551 | if "*" in oname: | |
552 | self.magic_psearch(oname) |
|
552 | self.magic_psearch(oname) | |
553 | else: |
|
553 | else: | |
554 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
554 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
555 | namespaces=namespaces) |
|
555 | namespaces=namespaces) | |
556 |
|
556 | |||
557 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
557 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
558 | """Provide extra detailed information about an object. |
|
558 | """Provide extra detailed information about an object. | |
559 |
|
559 | |||
560 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
560 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
561 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
561 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
562 | namespaces=namespaces) |
|
562 | namespaces=namespaces) | |
563 |
|
563 | |||
564 | @skip_doctest |
|
564 | @skip_doctest | |
565 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
565 | def magic_pdef(self, parameter_s='', namespaces=None): | |
566 | """Print the definition header for any callable object. |
|
566 | """Print the definition header for any callable object. | |
567 |
|
567 | |||
568 | If the object is a class, print the constructor information. |
|
568 | If the object is a class, print the constructor information. | |
569 |
|
569 | |||
570 | Examples |
|
570 | Examples | |
571 | -------- |
|
571 | -------- | |
572 | :: |
|
572 | :: | |
573 |
|
573 | |||
574 | In [3]: %pdef urllib.urlopen |
|
574 | In [3]: %pdef urllib.urlopen | |
575 | urllib.urlopen(url, data=None, proxies=None) |
|
575 | urllib.urlopen(url, data=None, proxies=None) | |
576 | """ |
|
576 | """ | |
577 | self._inspect('pdef',parameter_s, namespaces) |
|
577 | self._inspect('pdef',parameter_s, namespaces) | |
578 |
|
578 | |||
579 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
579 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
580 | """Print the docstring for an object. |
|
580 | """Print the docstring for an object. | |
581 |
|
581 | |||
582 | If the given object is a class, it will print both the class and the |
|
582 | If the given object is a class, it will print both the class and the | |
583 | constructor docstrings.""" |
|
583 | constructor docstrings.""" | |
584 | self._inspect('pdoc',parameter_s, namespaces) |
|
584 | self._inspect('pdoc',parameter_s, namespaces) | |
585 |
|
585 | |||
586 | def magic_psource(self, parameter_s='', namespaces=None): |
|
586 | def magic_psource(self, parameter_s='', namespaces=None): | |
587 | """Print (or run through pager) the source code for an object.""" |
|
587 | """Print (or run through pager) the source code for an object.""" | |
588 | self._inspect('psource',parameter_s, namespaces) |
|
588 | self._inspect('psource',parameter_s, namespaces) | |
589 |
|
589 | |||
590 | def magic_pfile(self, parameter_s=''): |
|
590 | def magic_pfile(self, parameter_s=''): | |
591 | """Print (or run through pager) the file where an object is defined. |
|
591 | """Print (or run through pager) the file where an object is defined. | |
592 |
|
592 | |||
593 | The file opens at the line where the object definition begins. IPython |
|
593 | The file opens at the line where the object definition begins. IPython | |
594 | will honor the environment variable PAGER if set, and otherwise will |
|
594 | will honor the environment variable PAGER if set, and otherwise will | |
595 | do its best to print the file in a convenient form. |
|
595 | do its best to print the file in a convenient form. | |
596 |
|
596 | |||
597 | If the given argument is not an object currently defined, IPython will |
|
597 | If the given argument is not an object currently defined, IPython will | |
598 | try to interpret it as a filename (automatically adding a .py extension |
|
598 | try to interpret it as a filename (automatically adding a .py extension | |
599 | if needed). You can thus use %pfile as a syntax highlighting code |
|
599 | if needed). You can thus use %pfile as a syntax highlighting code | |
600 | viewer.""" |
|
600 | viewer.""" | |
601 |
|
601 | |||
602 | # first interpret argument as an object name |
|
602 | # first interpret argument as an object name | |
603 | out = self._inspect('pfile',parameter_s) |
|
603 | out = self._inspect('pfile',parameter_s) | |
604 | # if not, try the input as a filename |
|
604 | # if not, try the input as a filename | |
605 | if out == 'not found': |
|
605 | if out == 'not found': | |
606 | try: |
|
606 | try: | |
607 | filename = get_py_filename(parameter_s) |
|
607 | filename = get_py_filename(parameter_s) | |
608 | except IOError,msg: |
|
608 | except IOError,msg: | |
609 | print msg |
|
609 | print msg | |
610 | return |
|
610 | return | |
611 | page.page(self.shell.inspector.format(file(filename).read())) |
|
611 | page.page(self.shell.inspector.format(file(filename).read())) | |
612 |
|
612 | |||
613 | def magic_psearch(self, parameter_s=''): |
|
613 | def magic_psearch(self, parameter_s=''): | |
614 | """Search for object in namespaces by wildcard. |
|
614 | """Search for object in namespaces by wildcard. | |
615 |
|
615 | |||
616 | %psearch [options] PATTERN [OBJECT TYPE] |
|
616 | %psearch [options] PATTERN [OBJECT TYPE] | |
617 |
|
617 | |||
618 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
618 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
619 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
619 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
620 | rest of the command line must be unchanged (options come first), so |
|
620 | rest of the command line must be unchanged (options come first), so | |
621 | for example the following forms are equivalent |
|
621 | for example the following forms are equivalent | |
622 |
|
622 | |||
623 | %psearch -i a* function |
|
623 | %psearch -i a* function | |
624 | -i a* function? |
|
624 | -i a* function? | |
625 | ?-i a* function |
|
625 | ?-i a* function | |
626 |
|
626 | |||
627 | Arguments: |
|
627 | Arguments: | |
628 |
|
628 | |||
629 | PATTERN |
|
629 | PATTERN | |
630 |
|
630 | |||
631 | where PATTERN is a string containing * as a wildcard similar to its |
|
631 | where PATTERN is a string containing * as a wildcard similar to its | |
632 | use in a shell. The pattern is matched in all namespaces on the |
|
632 | use in a shell. The pattern is matched in all namespaces on the | |
633 | search path. By default objects starting with a single _ are not |
|
633 | search path. By default objects starting with a single _ are not | |
634 | matched, many IPython generated objects have a single |
|
634 | matched, many IPython generated objects have a single | |
635 | underscore. The default is case insensitive matching. Matching is |
|
635 | underscore. The default is case insensitive matching. Matching is | |
636 | also done on the attributes of objects and not only on the objects |
|
636 | also done on the attributes of objects and not only on the objects | |
637 | in a module. |
|
637 | in a module. | |
638 |
|
638 | |||
639 | [OBJECT TYPE] |
|
639 | [OBJECT TYPE] | |
640 |
|
640 | |||
641 | Is the name of a python type from the types module. The name is |
|
641 | Is the name of a python type from the types module. The name is | |
642 | given in lowercase without the ending type, ex. StringType is |
|
642 | given in lowercase without the ending type, ex. StringType is | |
643 | written string. By adding a type here only objects matching the |
|
643 | written string. By adding a type here only objects matching the | |
644 | given type are matched. Using all here makes the pattern match all |
|
644 | given type are matched. Using all here makes the pattern match all | |
645 | types (this is the default). |
|
645 | types (this is the default). | |
646 |
|
646 | |||
647 | Options: |
|
647 | Options: | |
648 |
|
648 | |||
649 | -a: makes the pattern match even objects whose names start with a |
|
649 | -a: makes the pattern match even objects whose names start with a | |
650 | single underscore. These names are normally ommitted from the |
|
650 | single underscore. These names are normally ommitted from the | |
651 | search. |
|
651 | search. | |
652 |
|
652 | |||
653 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
653 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
654 | these options are given, the default is read from your configuration |
|
654 | these options are given, the default is read from your configuration | |
655 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
655 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |
656 | If this option is not specified in your configuration file, IPython's |
|
656 | If this option is not specified in your configuration file, IPython's | |
657 | internal default is to do a case sensitive search. |
|
657 | internal default is to do a case sensitive search. | |
658 |
|
658 | |||
659 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
659 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
660 | specifiy can be searched in any of the following namespaces: |
|
660 | specifiy can be searched in any of the following namespaces: | |
661 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
661 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
662 | 'builtin' and 'user' are the search defaults. Note that you should |
|
662 | 'builtin' and 'user' are the search defaults. Note that you should | |
663 | not use quotes when specifying namespaces. |
|
663 | not use quotes when specifying namespaces. | |
664 |
|
664 | |||
665 | 'Builtin' contains the python module builtin, 'user' contains all |
|
665 | 'Builtin' contains the python module builtin, 'user' contains all | |
666 | user data, 'alias' only contain the shell aliases and no python |
|
666 | user data, 'alias' only contain the shell aliases and no python | |
667 | objects, 'internal' contains objects used by IPython. The |
|
667 | objects, 'internal' contains objects used by IPython. The | |
668 | 'user_global' namespace is only used by embedded IPython instances, |
|
668 | 'user_global' namespace is only used by embedded IPython instances, | |
669 | and it contains module-level globals. You can add namespaces to the |
|
669 | and it contains module-level globals. You can add namespaces to the | |
670 | search with -s or exclude them with -e (these options can be given |
|
670 | search with -s or exclude them with -e (these options can be given | |
671 | more than once). |
|
671 | more than once). | |
672 |
|
672 | |||
673 | Examples: |
|
673 | Examples: | |
674 |
|
674 | |||
675 | %psearch a* -> objects beginning with an a |
|
675 | %psearch a* -> objects beginning with an a | |
676 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
676 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
677 | %psearch a* function -> all functions beginning with an a |
|
677 | %psearch a* function -> all functions beginning with an a | |
678 | %psearch re.e* -> objects beginning with an e in module re |
|
678 | %psearch re.e* -> objects beginning with an e in module re | |
679 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
679 | %psearch r*.e* -> objects that start with e in modules starting in r | |
680 | %psearch r*.* string -> all strings in modules beginning with r |
|
680 | %psearch r*.* string -> all strings in modules beginning with r | |
681 |
|
681 | |||
682 | Case sensitve search: |
|
682 | Case sensitve search: | |
683 |
|
683 | |||
684 | %psearch -c a* list all object beginning with lower case a |
|
684 | %psearch -c a* list all object beginning with lower case a | |
685 |
|
685 | |||
686 | Show objects beginning with a single _: |
|
686 | Show objects beginning with a single _: | |
687 |
|
687 | |||
688 | %psearch -a _* list objects beginning with a single underscore""" |
|
688 | %psearch -a _* list objects beginning with a single underscore""" | |
689 | try: |
|
689 | try: | |
690 | parameter_s.encode('ascii') |
|
690 | parameter_s.encode('ascii') | |
691 | except UnicodeEncodeError: |
|
691 | except UnicodeEncodeError: | |
692 | print 'Python identifiers can only contain ascii characters.' |
|
692 | print 'Python identifiers can only contain ascii characters.' | |
693 | return |
|
693 | return | |
694 |
|
694 | |||
695 | # default namespaces to be searched |
|
695 | # default namespaces to be searched | |
696 | def_search = ['user','builtin'] |
|
696 | def_search = ['user','builtin'] | |
697 |
|
697 | |||
698 | # Process options/args |
|
698 | # Process options/args | |
699 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
699 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
700 | opt = opts.get |
|
700 | opt = opts.get | |
701 | shell = self.shell |
|
701 | shell = self.shell | |
702 | psearch = shell.inspector.psearch |
|
702 | psearch = shell.inspector.psearch | |
703 |
|
703 | |||
704 | # select case options |
|
704 | # select case options | |
705 | if opts.has_key('i'): |
|
705 | if opts.has_key('i'): | |
706 | ignore_case = True |
|
706 | ignore_case = True | |
707 | elif opts.has_key('c'): |
|
707 | elif opts.has_key('c'): | |
708 | ignore_case = False |
|
708 | ignore_case = False | |
709 | else: |
|
709 | else: | |
710 | ignore_case = not shell.wildcards_case_sensitive |
|
710 | ignore_case = not shell.wildcards_case_sensitive | |
711 |
|
711 | |||
712 | # Build list of namespaces to search from user options |
|
712 | # Build list of namespaces to search from user options | |
713 | def_search.extend(opt('s',[])) |
|
713 | def_search.extend(opt('s',[])) | |
714 | ns_exclude = ns_exclude=opt('e',[]) |
|
714 | ns_exclude = ns_exclude=opt('e',[]) | |
715 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
715 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
716 |
|
716 | |||
717 | # Call the actual search |
|
717 | # Call the actual search | |
718 | try: |
|
718 | try: | |
719 | psearch(args,shell.ns_table,ns_search, |
|
719 | psearch(args,shell.ns_table,ns_search, | |
720 | show_all=opt('a'),ignore_case=ignore_case) |
|
720 | show_all=opt('a'),ignore_case=ignore_case) | |
721 | except: |
|
721 | except: | |
722 | shell.showtraceback() |
|
722 | shell.showtraceback() | |
723 |
|
723 | |||
724 | @skip_doctest |
|
724 | @skip_doctest | |
725 | def magic_who_ls(self, parameter_s=''): |
|
725 | def magic_who_ls(self, parameter_s=''): | |
726 | """Return a sorted list of all interactive variables. |
|
726 | """Return a sorted list of all interactive variables. | |
727 |
|
727 | |||
728 | If arguments are given, only variables of types matching these |
|
728 | If arguments are given, only variables of types matching these | |
729 | arguments are returned. |
|
729 | arguments are returned. | |
730 |
|
730 | |||
731 | Examples |
|
731 | Examples | |
732 | -------- |
|
732 | -------- | |
733 |
|
733 | |||
734 | Define two variables and list them with who_ls:: |
|
734 | Define two variables and list them with who_ls:: | |
735 |
|
735 | |||
736 | In [1]: alpha = 123 |
|
736 | In [1]: alpha = 123 | |
737 |
|
737 | |||
738 | In [2]: beta = 'test' |
|
738 | In [2]: beta = 'test' | |
739 |
|
739 | |||
740 | In [3]: %who_ls |
|
740 | In [3]: %who_ls | |
741 | Out[3]: ['alpha', 'beta'] |
|
741 | Out[3]: ['alpha', 'beta'] | |
742 |
|
742 | |||
743 | In [4]: %who_ls int |
|
743 | In [4]: %who_ls int | |
744 | Out[4]: ['alpha'] |
|
744 | Out[4]: ['alpha'] | |
745 |
|
745 | |||
746 | In [5]: %who_ls str |
|
746 | In [5]: %who_ls str | |
747 | Out[5]: ['beta'] |
|
747 | Out[5]: ['beta'] | |
748 | """ |
|
748 | """ | |
749 |
|
749 | |||
750 | user_ns = self.shell.user_ns |
|
750 | user_ns = self.shell.user_ns | |
751 | internal_ns = self.shell.internal_ns |
|
|||
752 | user_ns_hidden = self.shell.user_ns_hidden |
|
751 | user_ns_hidden = self.shell.user_ns_hidden | |
753 | out = [ i for i in user_ns |
|
752 | out = [ i for i in user_ns | |
754 | if not i.startswith('_') \ |
|
753 | if not i.startswith('_') \ | |
755 |
and not |
|
754 | and not i in user_ns_hidden ] | |
756 |
|
755 | |||
757 | typelist = parameter_s.split() |
|
756 | typelist = parameter_s.split() | |
758 | if typelist: |
|
757 | if typelist: | |
759 | typeset = set(typelist) |
|
758 | typeset = set(typelist) | |
760 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
759 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
761 |
|
760 | |||
762 | out.sort() |
|
761 | out.sort() | |
763 | return out |
|
762 | return out | |
764 |
|
763 | |||
765 | @skip_doctest |
|
764 | @skip_doctest | |
766 | def magic_who(self, parameter_s=''): |
|
765 | def magic_who(self, parameter_s=''): | |
767 | """Print all interactive variables, with some minimal formatting. |
|
766 | """Print all interactive variables, with some minimal formatting. | |
768 |
|
767 | |||
769 | If any arguments are given, only variables whose type matches one of |
|
768 | If any arguments are given, only variables whose type matches one of | |
770 | these are printed. For example: |
|
769 | these are printed. For example: | |
771 |
|
770 | |||
772 | %who function str |
|
771 | %who function str | |
773 |
|
772 | |||
774 | will only list functions and strings, excluding all other types of |
|
773 | will only list functions and strings, excluding all other types of | |
775 | variables. To find the proper type names, simply use type(var) at a |
|
774 | variables. To find the proper type names, simply use type(var) at a | |
776 | command line to see how python prints type names. For example: |
|
775 | command line to see how python prints type names. For example: | |
777 |
|
776 | |||
778 | In [1]: type('hello')\\ |
|
777 | In [1]: type('hello')\\ | |
779 | Out[1]: <type 'str'> |
|
778 | Out[1]: <type 'str'> | |
780 |
|
779 | |||
781 | indicates that the type name for strings is 'str'. |
|
780 | indicates that the type name for strings is 'str'. | |
782 |
|
781 | |||
783 | %who always excludes executed names loaded through your configuration |
|
782 | %who always excludes executed names loaded through your configuration | |
784 | file and things which are internal to IPython. |
|
783 | file and things which are internal to IPython. | |
785 |
|
784 | |||
786 | This is deliberate, as typically you may load many modules and the |
|
785 | This is deliberate, as typically you may load many modules and the | |
787 | purpose of %who is to show you only what you've manually defined. |
|
786 | purpose of %who is to show you only what you've manually defined. | |
788 |
|
787 | |||
789 | Examples |
|
788 | Examples | |
790 | -------- |
|
789 | -------- | |
791 |
|
790 | |||
792 | Define two variables and list them with who:: |
|
791 | Define two variables and list them with who:: | |
793 |
|
792 | |||
794 | In [1]: alpha = 123 |
|
793 | In [1]: alpha = 123 | |
795 |
|
794 | |||
796 | In [2]: beta = 'test' |
|
795 | In [2]: beta = 'test' | |
797 |
|
796 | |||
798 | In [3]: %who |
|
797 | In [3]: %who | |
799 | alpha beta |
|
798 | alpha beta | |
800 |
|
799 | |||
801 | In [4]: %who int |
|
800 | In [4]: %who int | |
802 | alpha |
|
801 | alpha | |
803 |
|
802 | |||
804 | In [5]: %who str |
|
803 | In [5]: %who str | |
805 | beta |
|
804 | beta | |
806 | """ |
|
805 | """ | |
807 |
|
806 | |||
808 | varlist = self.magic_who_ls(parameter_s) |
|
807 | varlist = self.magic_who_ls(parameter_s) | |
809 | if not varlist: |
|
808 | if not varlist: | |
810 | if parameter_s: |
|
809 | if parameter_s: | |
811 | print 'No variables match your requested type.' |
|
810 | print 'No variables match your requested type.' | |
812 | else: |
|
811 | else: | |
813 | print 'Interactive namespace is empty.' |
|
812 | print 'Interactive namespace is empty.' | |
814 | return |
|
813 | return | |
815 |
|
814 | |||
816 | # if we have variables, move on... |
|
815 | # if we have variables, move on... | |
817 | count = 0 |
|
816 | count = 0 | |
818 | for i in varlist: |
|
817 | for i in varlist: | |
819 | print i+'\t', |
|
818 | print i+'\t', | |
820 | count += 1 |
|
819 | count += 1 | |
821 | if count > 8: |
|
820 | if count > 8: | |
822 | count = 0 |
|
821 | count = 0 | |
823 |
|
822 | |||
824 |
|
823 | |||
825 |
|
824 | |||
826 | @skip_doctest |
|
825 | @skip_doctest | |
827 | def magic_whos(self, parameter_s=''): |
|
826 | def magic_whos(self, parameter_s=''): | |
828 | """Like %who, but gives some extra information about each variable. |
|
827 | """Like %who, but gives some extra information about each variable. | |
829 |
|
828 | |||
830 | The same type filtering of %who can be applied here. |
|
829 | The same type filtering of %who can be applied here. | |
831 |
|
830 | |||
832 | For all variables, the type is printed. Additionally it prints: |
|
831 | For all variables, the type is printed. Additionally it prints: | |
833 |
|
832 | |||
834 | - For {},[],(): their length. |
|
833 | - For {},[],(): their length. | |
835 |
|
834 | |||
836 | - For numpy arrays, a summary with shape, number of |
|
835 | - For numpy arrays, a summary with shape, number of | |
837 | elements, typecode and size in memory. |
|
836 | elements, typecode and size in memory. | |
838 |
|
837 | |||
839 | - Everything else: a string representation, snipping their middle if |
|
838 | - Everything else: a string representation, snipping their middle if | |
840 | too long. |
|
839 | too long. | |
841 |
|
840 | |||
842 | Examples |
|
841 | Examples | |
843 | -------- |
|
842 | -------- | |
844 |
|
843 | |||
845 | Define two variables and list them with whos:: |
|
844 | Define two variables and list them with whos:: | |
846 |
|
845 | |||
847 | In [1]: alpha = 123 |
|
846 | In [1]: alpha = 123 | |
848 |
|
847 | |||
849 | In [2]: beta = 'test' |
|
848 | In [2]: beta = 'test' | |
850 |
|
849 | |||
851 | In [3]: %whos |
|
850 | In [3]: %whos | |
852 | Variable Type Data/Info |
|
851 | Variable Type Data/Info | |
853 | -------------------------------- |
|
852 | -------------------------------- | |
854 | alpha int 123 |
|
853 | alpha int 123 | |
855 | beta str test |
|
854 | beta str test | |
856 | """ |
|
855 | """ | |
857 |
|
856 | |||
858 | varnames = self.magic_who_ls(parameter_s) |
|
857 | varnames = self.magic_who_ls(parameter_s) | |
859 | if not varnames: |
|
858 | if not varnames: | |
860 | if parameter_s: |
|
859 | if parameter_s: | |
861 | print 'No variables match your requested type.' |
|
860 | print 'No variables match your requested type.' | |
862 | else: |
|
861 | else: | |
863 | print 'Interactive namespace is empty.' |
|
862 | print 'Interactive namespace is empty.' | |
864 | return |
|
863 | return | |
865 |
|
864 | |||
866 | # if we have variables, move on... |
|
865 | # if we have variables, move on... | |
867 |
|
866 | |||
868 | # for these types, show len() instead of data: |
|
867 | # for these types, show len() instead of data: | |
869 | seq_types = ['dict', 'list', 'tuple'] |
|
868 | seq_types = ['dict', 'list', 'tuple'] | |
870 |
|
869 | |||
871 | # for numpy arrays, display summary info |
|
870 | # for numpy arrays, display summary info | |
872 | ndarray_type = None |
|
871 | ndarray_type = None | |
873 | if 'numpy' in sys.modules: |
|
872 | if 'numpy' in sys.modules: | |
874 | try: |
|
873 | try: | |
875 | from numpy import ndarray |
|
874 | from numpy import ndarray | |
876 | except ImportError: |
|
875 | except ImportError: | |
877 | pass |
|
876 | pass | |
878 | else: |
|
877 | else: | |
879 | ndarray_type = ndarray.__name__ |
|
878 | ndarray_type = ndarray.__name__ | |
880 |
|
879 | |||
881 | # Find all variable names and types so we can figure out column sizes |
|
880 | # Find all variable names and types so we can figure out column sizes | |
882 | def get_vars(i): |
|
881 | def get_vars(i): | |
883 | return self.shell.user_ns[i] |
|
882 | return self.shell.user_ns[i] | |
884 |
|
883 | |||
885 | # some types are well known and can be shorter |
|
884 | # some types are well known and can be shorter | |
886 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
885 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
887 | def type_name(v): |
|
886 | def type_name(v): | |
888 | tn = type(v).__name__ |
|
887 | tn = type(v).__name__ | |
889 | return abbrevs.get(tn,tn) |
|
888 | return abbrevs.get(tn,tn) | |
890 |
|
889 | |||
891 | varlist = map(get_vars,varnames) |
|
890 | varlist = map(get_vars,varnames) | |
892 |
|
891 | |||
893 | typelist = [] |
|
892 | typelist = [] | |
894 | for vv in varlist: |
|
893 | for vv in varlist: | |
895 | tt = type_name(vv) |
|
894 | tt = type_name(vv) | |
896 |
|
895 | |||
897 | if tt=='instance': |
|
896 | if tt=='instance': | |
898 | typelist.append( abbrevs.get(str(vv.__class__), |
|
897 | typelist.append( abbrevs.get(str(vv.__class__), | |
899 | str(vv.__class__))) |
|
898 | str(vv.__class__))) | |
900 | else: |
|
899 | else: | |
901 | typelist.append(tt) |
|
900 | typelist.append(tt) | |
902 |
|
901 | |||
903 | # column labels and # of spaces as separator |
|
902 | # column labels and # of spaces as separator | |
904 | varlabel = 'Variable' |
|
903 | varlabel = 'Variable' | |
905 | typelabel = 'Type' |
|
904 | typelabel = 'Type' | |
906 | datalabel = 'Data/Info' |
|
905 | datalabel = 'Data/Info' | |
907 | colsep = 3 |
|
906 | colsep = 3 | |
908 | # variable format strings |
|
907 | # variable format strings | |
909 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
908 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
910 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
909 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
911 | # find the size of the columns to format the output nicely |
|
910 | # find the size of the columns to format the output nicely | |
912 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
911 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
913 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
912 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
914 | # table header |
|
913 | # table header | |
915 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
914 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
916 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
915 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
917 | # and the table itself |
|
916 | # and the table itself | |
918 | kb = 1024 |
|
917 | kb = 1024 | |
919 | Mb = 1048576 # kb**2 |
|
918 | Mb = 1048576 # kb**2 | |
920 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
919 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
921 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
920 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
922 | if vtype in seq_types: |
|
921 | if vtype in seq_types: | |
923 | print "n="+str(len(var)) |
|
922 | print "n="+str(len(var)) | |
924 | elif vtype == ndarray_type: |
|
923 | elif vtype == ndarray_type: | |
925 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
924 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
926 | if vtype==ndarray_type: |
|
925 | if vtype==ndarray_type: | |
927 | # numpy |
|
926 | # numpy | |
928 | vsize = var.size |
|
927 | vsize = var.size | |
929 | vbytes = vsize*var.itemsize |
|
928 | vbytes = vsize*var.itemsize | |
930 | vdtype = var.dtype |
|
929 | vdtype = var.dtype | |
931 | else: |
|
930 | else: | |
932 | # Numeric |
|
931 | # Numeric | |
933 | vsize = Numeric.size(var) |
|
932 | vsize = Numeric.size(var) | |
934 | vbytes = vsize*var.itemsize() |
|
933 | vbytes = vsize*var.itemsize() | |
935 | vdtype = var.typecode() |
|
934 | vdtype = var.typecode() | |
936 |
|
935 | |||
937 | if vbytes < 100000: |
|
936 | if vbytes < 100000: | |
938 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
937 | print aformat % (vshape,vsize,vdtype,vbytes) | |
939 | else: |
|
938 | else: | |
940 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
939 | print aformat % (vshape,vsize,vdtype,vbytes), | |
941 | if vbytes < Mb: |
|
940 | if vbytes < Mb: | |
942 | print '(%s kb)' % (vbytes/kb,) |
|
941 | print '(%s kb)' % (vbytes/kb,) | |
943 | else: |
|
942 | else: | |
944 | print '(%s Mb)' % (vbytes/Mb,) |
|
943 | print '(%s Mb)' % (vbytes/Mb,) | |
945 | else: |
|
944 | else: | |
946 | try: |
|
945 | try: | |
947 | vstr = str(var) |
|
946 | vstr = str(var) | |
948 | except UnicodeEncodeError: |
|
947 | except UnicodeEncodeError: | |
949 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
948 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
950 | 'backslashreplace') |
|
949 | 'backslashreplace') | |
951 | vstr = vstr.replace('\n','\\n') |
|
950 | vstr = vstr.replace('\n','\\n') | |
952 | if len(vstr) < 50: |
|
951 | if len(vstr) < 50: | |
953 | print vstr |
|
952 | print vstr | |
954 | else: |
|
953 | else: | |
955 | print vstr[:25] + "<...>" + vstr[-25:] |
|
954 | print vstr[:25] + "<...>" + vstr[-25:] | |
956 |
|
955 | |||
957 | def magic_reset(self, parameter_s=''): |
|
956 | def magic_reset(self, parameter_s=''): | |
958 | """Resets the namespace by removing all names defined by the user. |
|
957 | """Resets the namespace by removing all names defined by the user. | |
959 |
|
958 | |||
960 | Parameters |
|
959 | Parameters | |
961 | ---------- |
|
960 | ---------- | |
962 | -f : force reset without asking for confirmation. |
|
961 | -f : force reset without asking for confirmation. | |
963 |
|
962 | |||
964 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
963 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
965 | References to objects may be kept. By default (without this option), |
|
964 | References to objects may be kept. By default (without this option), | |
966 | we do a 'hard' reset, giving you a new session and removing all |
|
965 | we do a 'hard' reset, giving you a new session and removing all | |
967 | references to objects from the current session. |
|
966 | references to objects from the current session. | |
968 |
|
967 | |||
969 | Examples |
|
968 | Examples | |
970 | -------- |
|
969 | -------- | |
971 | In [6]: a = 1 |
|
970 | In [6]: a = 1 | |
972 |
|
971 | |||
973 | In [7]: a |
|
972 | In [7]: a | |
974 | Out[7]: 1 |
|
973 | Out[7]: 1 | |
975 |
|
974 | |||
976 | In [8]: 'a' in _ip.user_ns |
|
975 | In [8]: 'a' in _ip.user_ns | |
977 | Out[8]: True |
|
976 | Out[8]: True | |
978 |
|
977 | |||
979 | In [9]: %reset -f |
|
978 | In [9]: %reset -f | |
980 |
|
979 | |||
981 | In [1]: 'a' in _ip.user_ns |
|
980 | In [1]: 'a' in _ip.user_ns | |
982 | Out[1]: False |
|
981 | Out[1]: False | |
983 | """ |
|
982 | """ | |
984 | opts, args = self.parse_options(parameter_s,'sf') |
|
983 | opts, args = self.parse_options(parameter_s,'sf') | |
985 | if 'f' in opts: |
|
984 | if 'f' in opts: | |
986 | ans = True |
|
985 | ans = True | |
987 | else: |
|
986 | else: | |
988 | ans = self.shell.ask_yes_no( |
|
987 | ans = self.shell.ask_yes_no( | |
989 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') |
|
988 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') | |
990 | if not ans: |
|
989 | if not ans: | |
991 | print 'Nothing done.' |
|
990 | print 'Nothing done.' | |
992 | return |
|
991 | return | |
993 |
|
992 | |||
994 | if 's' in opts: # Soft reset |
|
993 | if 's' in opts: # Soft reset | |
995 | user_ns = self.shell.user_ns |
|
994 | user_ns = self.shell.user_ns | |
996 | for i in self.magic_who_ls(): |
|
995 | for i in self.magic_who_ls(): | |
997 | del(user_ns[i]) |
|
996 | del(user_ns[i]) | |
998 |
|
997 | |||
999 | else: # Hard reset |
|
998 | else: # Hard reset | |
1000 | self.shell.reset(new_session = False) |
|
999 | self.shell.reset(new_session = False) | |
1001 |
|
1000 | |||
1002 |
|
1001 | |||
1003 |
|
1002 | |||
1004 | def magic_reset_selective(self, parameter_s=''): |
|
1003 | def magic_reset_selective(self, parameter_s=''): | |
1005 | """Resets the namespace by removing names defined by the user. |
|
1004 | """Resets the namespace by removing names defined by the user. | |
1006 |
|
1005 | |||
1007 | Input/Output history are left around in case you need them. |
|
1006 | Input/Output history are left around in case you need them. | |
1008 |
|
1007 | |||
1009 | %reset_selective [-f] regex |
|
1008 | %reset_selective [-f] regex | |
1010 |
|
1009 | |||
1011 | No action is taken if regex is not included |
|
1010 | No action is taken if regex is not included | |
1012 |
|
1011 | |||
1013 | Options |
|
1012 | Options | |
1014 | -f : force reset without asking for confirmation. |
|
1013 | -f : force reset without asking for confirmation. | |
1015 |
|
1014 | |||
1016 | Examples |
|
1015 | Examples | |
1017 | -------- |
|
1016 | -------- | |
1018 |
|
1017 | |||
1019 | We first fully reset the namespace so your output looks identical to |
|
1018 | We first fully reset the namespace so your output looks identical to | |
1020 | this example for pedagogical reasons; in practice you do not need a |
|
1019 | this example for pedagogical reasons; in practice you do not need a | |
1021 | full reset. |
|
1020 | full reset. | |
1022 |
|
1021 | |||
1023 | In [1]: %reset -f |
|
1022 | In [1]: %reset -f | |
1024 |
|
1023 | |||
1025 | Now, with a clean namespace we can make a few variables and use |
|
1024 | Now, with a clean namespace we can make a few variables and use | |
1026 | %reset_selective to only delete names that match our regexp: |
|
1025 | %reset_selective to only delete names that match our regexp: | |
1027 |
|
1026 | |||
1028 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1027 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1029 |
|
1028 | |||
1030 | In [3]: who_ls |
|
1029 | In [3]: who_ls | |
1031 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1030 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1032 |
|
1031 | |||
1033 | In [4]: %reset_selective -f b[2-3]m |
|
1032 | In [4]: %reset_selective -f b[2-3]m | |
1034 |
|
1033 | |||
1035 | In [5]: who_ls |
|
1034 | In [5]: who_ls | |
1036 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1035 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1037 |
|
1036 | |||
1038 | In [6]: %reset_selective -f d |
|
1037 | In [6]: %reset_selective -f d | |
1039 |
|
1038 | |||
1040 | In [7]: who_ls |
|
1039 | In [7]: who_ls | |
1041 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1040 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1042 |
|
1041 | |||
1043 | In [8]: %reset_selective -f c |
|
1042 | In [8]: %reset_selective -f c | |
1044 |
|
1043 | |||
1045 | In [9]: who_ls |
|
1044 | In [9]: who_ls | |
1046 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1045 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1047 |
|
1046 | |||
1048 | In [10]: %reset_selective -f b |
|
1047 | In [10]: %reset_selective -f b | |
1049 |
|
1048 | |||
1050 | In [11]: who_ls |
|
1049 | In [11]: who_ls | |
1051 | Out[11]: ['a'] |
|
1050 | Out[11]: ['a'] | |
1052 | """ |
|
1051 | """ | |
1053 |
|
1052 | |||
1054 | opts, regex = self.parse_options(parameter_s,'f') |
|
1053 | opts, regex = self.parse_options(parameter_s,'f') | |
1055 |
|
1054 | |||
1056 | if opts.has_key('f'): |
|
1055 | if opts.has_key('f'): | |
1057 | ans = True |
|
1056 | ans = True | |
1058 | else: |
|
1057 | else: | |
1059 | ans = self.shell.ask_yes_no( |
|
1058 | ans = self.shell.ask_yes_no( | |
1060 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
1059 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |
1061 | default='n') |
|
1060 | default='n') | |
1062 | if not ans: |
|
1061 | if not ans: | |
1063 | print 'Nothing done.' |
|
1062 | print 'Nothing done.' | |
1064 | return |
|
1063 | return | |
1065 | user_ns = self.shell.user_ns |
|
1064 | user_ns = self.shell.user_ns | |
1066 | if not regex: |
|
1065 | if not regex: | |
1067 | print 'No regex pattern specified. Nothing done.' |
|
1066 | print 'No regex pattern specified. Nothing done.' | |
1068 | return |
|
1067 | return | |
1069 | else: |
|
1068 | else: | |
1070 | try: |
|
1069 | try: | |
1071 | m = re.compile(regex) |
|
1070 | m = re.compile(regex) | |
1072 | except TypeError: |
|
1071 | except TypeError: | |
1073 | raise TypeError('regex must be a string or compiled pattern') |
|
1072 | raise TypeError('regex must be a string or compiled pattern') | |
1074 | for i in self.magic_who_ls(): |
|
1073 | for i in self.magic_who_ls(): | |
1075 | if m.search(i): |
|
1074 | if m.search(i): | |
1076 | del(user_ns[i]) |
|
1075 | del(user_ns[i]) | |
1077 |
|
1076 | |||
1078 | def magic_xdel(self, parameter_s=''): |
|
1077 | def magic_xdel(self, parameter_s=''): | |
1079 | """Delete a variable, trying to clear it from anywhere that |
|
1078 | """Delete a variable, trying to clear it from anywhere that | |
1080 | IPython's machinery has references to it. By default, this uses |
|
1079 | IPython's machinery has references to it. By default, this uses | |
1081 | the identity of the named object in the user namespace to remove |
|
1080 | the identity of the named object in the user namespace to remove | |
1082 | references held under other names. The object is also removed |
|
1081 | references held under other names. The object is also removed | |
1083 | from the output history. |
|
1082 | from the output history. | |
1084 |
|
1083 | |||
1085 | Options |
|
1084 | Options | |
1086 | -n : Delete the specified name from all namespaces, without |
|
1085 | -n : Delete the specified name from all namespaces, without | |
1087 | checking their identity. |
|
1086 | checking their identity. | |
1088 | """ |
|
1087 | """ | |
1089 | opts, varname = self.parse_options(parameter_s,'n') |
|
1088 | opts, varname = self.parse_options(parameter_s,'n') | |
1090 | try: |
|
1089 | try: | |
1091 | self.shell.del_var(varname, ('n' in opts)) |
|
1090 | self.shell.del_var(varname, ('n' in opts)) | |
1092 | except (NameError, ValueError) as e: |
|
1091 | except (NameError, ValueError) as e: | |
1093 | print type(e).__name__ +": "+ str(e) |
|
1092 | print type(e).__name__ +": "+ str(e) | |
1094 |
|
1093 | |||
1095 | def magic_logstart(self,parameter_s=''): |
|
1094 | def magic_logstart(self,parameter_s=''): | |
1096 | """Start logging anywhere in a session. |
|
1095 | """Start logging anywhere in a session. | |
1097 |
|
1096 | |||
1098 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1097 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1099 |
|
1098 | |||
1100 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1099 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1101 | current directory, in 'rotate' mode (see below). |
|
1100 | current directory, in 'rotate' mode (see below). | |
1102 |
|
1101 | |||
1103 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1102 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1104 | history up to that point and then continues logging. |
|
1103 | history up to that point and then continues logging. | |
1105 |
|
1104 | |||
1106 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1105 | %logstart takes a second optional parameter: logging mode. This can be one | |
1107 | of (note that the modes are given unquoted):\\ |
|
1106 | of (note that the modes are given unquoted):\\ | |
1108 | append: well, that says it.\\ |
|
1107 | append: well, that says it.\\ | |
1109 | backup: rename (if exists) to name~ and start name.\\ |
|
1108 | backup: rename (if exists) to name~ and start name.\\ | |
1110 | global: single logfile in your home dir, appended to.\\ |
|
1109 | global: single logfile in your home dir, appended to.\\ | |
1111 | over : overwrite existing log.\\ |
|
1110 | over : overwrite existing log.\\ | |
1112 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1111 | rotate: create rotating logs name.1~, name.2~, etc. | |
1113 |
|
1112 | |||
1114 | Options: |
|
1113 | Options: | |
1115 |
|
1114 | |||
1116 | -o: log also IPython's output. In this mode, all commands which |
|
1115 | -o: log also IPython's output. In this mode, all commands which | |
1117 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1116 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1118 | their corresponding input line. The output lines are always |
|
1117 | their corresponding input line. The output lines are always | |
1119 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1118 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1120 | Python code. |
|
1119 | Python code. | |
1121 |
|
1120 | |||
1122 | Since this marker is always the same, filtering only the output from |
|
1121 | Since this marker is always the same, filtering only the output from | |
1123 | a log is very easy, using for example a simple awk call: |
|
1122 | a log is very easy, using for example a simple awk call: | |
1124 |
|
1123 | |||
1125 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1124 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1126 |
|
1125 | |||
1127 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1126 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1128 | input, so that user lines are logged in their final form, converted |
|
1127 | input, so that user lines are logged in their final form, converted | |
1129 | into valid Python. For example, %Exit is logged as |
|
1128 | into valid Python. For example, %Exit is logged as | |
1130 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1129 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1131 | exactly as typed, with no transformations applied. |
|
1130 | exactly as typed, with no transformations applied. | |
1132 |
|
1131 | |||
1133 | -t: put timestamps before each input line logged (these are put in |
|
1132 | -t: put timestamps before each input line logged (these are put in | |
1134 | comments).""" |
|
1133 | comments).""" | |
1135 |
|
1134 | |||
1136 | opts,par = self.parse_options(parameter_s,'ort') |
|
1135 | opts,par = self.parse_options(parameter_s,'ort') | |
1137 | log_output = 'o' in opts |
|
1136 | log_output = 'o' in opts | |
1138 | log_raw_input = 'r' in opts |
|
1137 | log_raw_input = 'r' in opts | |
1139 | timestamp = 't' in opts |
|
1138 | timestamp = 't' in opts | |
1140 |
|
1139 | |||
1141 | logger = self.shell.logger |
|
1140 | logger = self.shell.logger | |
1142 |
|
1141 | |||
1143 | # if no args are given, the defaults set in the logger constructor by |
|
1142 | # if no args are given, the defaults set in the logger constructor by | |
1144 | # ipytohn remain valid |
|
1143 | # ipytohn remain valid | |
1145 | if par: |
|
1144 | if par: | |
1146 | try: |
|
1145 | try: | |
1147 | logfname,logmode = par.split() |
|
1146 | logfname,logmode = par.split() | |
1148 | except: |
|
1147 | except: | |
1149 | logfname = par |
|
1148 | logfname = par | |
1150 | logmode = 'backup' |
|
1149 | logmode = 'backup' | |
1151 | else: |
|
1150 | else: | |
1152 | logfname = logger.logfname |
|
1151 | logfname = logger.logfname | |
1153 | logmode = logger.logmode |
|
1152 | logmode = logger.logmode | |
1154 | # put logfname into rc struct as if it had been called on the command |
|
1153 | # put logfname into rc struct as if it had been called on the command | |
1155 | # line, so it ends up saved in the log header Save it in case we need |
|
1154 | # line, so it ends up saved in the log header Save it in case we need | |
1156 | # to restore it... |
|
1155 | # to restore it... | |
1157 | old_logfile = self.shell.logfile |
|
1156 | old_logfile = self.shell.logfile | |
1158 | if logfname: |
|
1157 | if logfname: | |
1159 | logfname = os.path.expanduser(logfname) |
|
1158 | logfname = os.path.expanduser(logfname) | |
1160 | self.shell.logfile = logfname |
|
1159 | self.shell.logfile = logfname | |
1161 |
|
1160 | |||
1162 | loghead = '# IPython log file\n\n' |
|
1161 | loghead = '# IPython log file\n\n' | |
1163 | try: |
|
1162 | try: | |
1164 | started = logger.logstart(logfname,loghead,logmode, |
|
1163 | started = logger.logstart(logfname,loghead,logmode, | |
1165 | log_output,timestamp,log_raw_input) |
|
1164 | log_output,timestamp,log_raw_input) | |
1166 | except: |
|
1165 | except: | |
1167 | self.shell.logfile = old_logfile |
|
1166 | self.shell.logfile = old_logfile | |
1168 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1167 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1169 | else: |
|
1168 | else: | |
1170 | # log input history up to this point, optionally interleaving |
|
1169 | # log input history up to this point, optionally interleaving | |
1171 | # output if requested |
|
1170 | # output if requested | |
1172 |
|
1171 | |||
1173 | if timestamp: |
|
1172 | if timestamp: | |
1174 | # disable timestamping for the previous history, since we've |
|
1173 | # disable timestamping for the previous history, since we've | |
1175 | # lost those already (no time machine here). |
|
1174 | # lost those already (no time machine here). | |
1176 | logger.timestamp = False |
|
1175 | logger.timestamp = False | |
1177 |
|
1176 | |||
1178 | if log_raw_input: |
|
1177 | if log_raw_input: | |
1179 | input_hist = self.shell.history_manager.input_hist_raw |
|
1178 | input_hist = self.shell.history_manager.input_hist_raw | |
1180 | else: |
|
1179 | else: | |
1181 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1180 | input_hist = self.shell.history_manager.input_hist_parsed | |
1182 |
|
1181 | |||
1183 | if log_output: |
|
1182 | if log_output: | |
1184 | log_write = logger.log_write |
|
1183 | log_write = logger.log_write | |
1185 | output_hist = self.shell.history_manager.output_hist |
|
1184 | output_hist = self.shell.history_manager.output_hist | |
1186 | for n in range(1,len(input_hist)-1): |
|
1185 | for n in range(1,len(input_hist)-1): | |
1187 | log_write(input_hist[n].rstrip() + '\n') |
|
1186 | log_write(input_hist[n].rstrip() + '\n') | |
1188 | if n in output_hist: |
|
1187 | if n in output_hist: | |
1189 | log_write(repr(output_hist[n]),'output') |
|
1188 | log_write(repr(output_hist[n]),'output') | |
1190 | else: |
|
1189 | else: | |
1191 | logger.log_write('\n'.join(input_hist[1:])) |
|
1190 | logger.log_write('\n'.join(input_hist[1:])) | |
1192 | logger.log_write('\n') |
|
1191 | logger.log_write('\n') | |
1193 | if timestamp: |
|
1192 | if timestamp: | |
1194 | # re-enable timestamping |
|
1193 | # re-enable timestamping | |
1195 | logger.timestamp = True |
|
1194 | logger.timestamp = True | |
1196 |
|
1195 | |||
1197 | print ('Activating auto-logging. ' |
|
1196 | print ('Activating auto-logging. ' | |
1198 | 'Current session state plus future input saved.') |
|
1197 | 'Current session state plus future input saved.') | |
1199 | logger.logstate() |
|
1198 | logger.logstate() | |
1200 |
|
1199 | |||
1201 | def magic_logstop(self,parameter_s=''): |
|
1200 | def magic_logstop(self,parameter_s=''): | |
1202 | """Fully stop logging and close log file. |
|
1201 | """Fully stop logging and close log file. | |
1203 |
|
1202 | |||
1204 | In order to start logging again, a new %logstart call needs to be made, |
|
1203 | In order to start logging again, a new %logstart call needs to be made, | |
1205 | possibly (though not necessarily) with a new filename, mode and other |
|
1204 | possibly (though not necessarily) with a new filename, mode and other | |
1206 | options.""" |
|
1205 | options.""" | |
1207 | self.logger.logstop() |
|
1206 | self.logger.logstop() | |
1208 |
|
1207 | |||
1209 | def magic_logoff(self,parameter_s=''): |
|
1208 | def magic_logoff(self,parameter_s=''): | |
1210 | """Temporarily stop logging. |
|
1209 | """Temporarily stop logging. | |
1211 |
|
1210 | |||
1212 | You must have previously started logging.""" |
|
1211 | You must have previously started logging.""" | |
1213 | self.shell.logger.switch_log(0) |
|
1212 | self.shell.logger.switch_log(0) | |
1214 |
|
1213 | |||
1215 | def magic_logon(self,parameter_s=''): |
|
1214 | def magic_logon(self,parameter_s=''): | |
1216 | """Restart logging. |
|
1215 | """Restart logging. | |
1217 |
|
1216 | |||
1218 | This function is for restarting logging which you've temporarily |
|
1217 | This function is for restarting logging which you've temporarily | |
1219 | stopped with %logoff. For starting logging for the first time, you |
|
1218 | stopped with %logoff. For starting logging for the first time, you | |
1220 | must use the %logstart function, which allows you to specify an |
|
1219 | must use the %logstart function, which allows you to specify an | |
1221 | optional log filename.""" |
|
1220 | optional log filename.""" | |
1222 |
|
1221 | |||
1223 | self.shell.logger.switch_log(1) |
|
1222 | self.shell.logger.switch_log(1) | |
1224 |
|
1223 | |||
1225 | def magic_logstate(self,parameter_s=''): |
|
1224 | def magic_logstate(self,parameter_s=''): | |
1226 | """Print the status of the logging system.""" |
|
1225 | """Print the status of the logging system.""" | |
1227 |
|
1226 | |||
1228 | self.shell.logger.logstate() |
|
1227 | self.shell.logger.logstate() | |
1229 |
|
1228 | |||
1230 | def magic_pdb(self, parameter_s=''): |
|
1229 | def magic_pdb(self, parameter_s=''): | |
1231 | """Control the automatic calling of the pdb interactive debugger. |
|
1230 | """Control the automatic calling of the pdb interactive debugger. | |
1232 |
|
1231 | |||
1233 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1232 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1234 | argument it works as a toggle. |
|
1233 | argument it works as a toggle. | |
1235 |
|
1234 | |||
1236 | When an exception is triggered, IPython can optionally call the |
|
1235 | When an exception is triggered, IPython can optionally call the | |
1237 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1236 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1238 | this feature on and off. |
|
1237 | this feature on and off. | |
1239 |
|
1238 | |||
1240 | The initial state of this feature is set in your configuration |
|
1239 | The initial state of this feature is set in your configuration | |
1241 | file (the option is ``InteractiveShell.pdb``). |
|
1240 | file (the option is ``InteractiveShell.pdb``). | |
1242 |
|
1241 | |||
1243 | If you want to just activate the debugger AFTER an exception has fired, |
|
1242 | If you want to just activate the debugger AFTER an exception has fired, | |
1244 | without having to type '%pdb on' and rerunning your code, you can use |
|
1243 | without having to type '%pdb on' and rerunning your code, you can use | |
1245 | the %debug magic.""" |
|
1244 | the %debug magic.""" | |
1246 |
|
1245 | |||
1247 | par = parameter_s.strip().lower() |
|
1246 | par = parameter_s.strip().lower() | |
1248 |
|
1247 | |||
1249 | if par: |
|
1248 | if par: | |
1250 | try: |
|
1249 | try: | |
1251 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1250 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1252 | except KeyError: |
|
1251 | except KeyError: | |
1253 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1252 | print ('Incorrect argument. Use on/1, off/0, ' | |
1254 | 'or nothing for a toggle.') |
|
1253 | 'or nothing for a toggle.') | |
1255 | return |
|
1254 | return | |
1256 | else: |
|
1255 | else: | |
1257 | # toggle |
|
1256 | # toggle | |
1258 | new_pdb = not self.shell.call_pdb |
|
1257 | new_pdb = not self.shell.call_pdb | |
1259 |
|
1258 | |||
1260 | # set on the shell |
|
1259 | # set on the shell | |
1261 | self.shell.call_pdb = new_pdb |
|
1260 | self.shell.call_pdb = new_pdb | |
1262 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1261 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1263 |
|
1262 | |||
1264 | def magic_debug(self, parameter_s=''): |
|
1263 | def magic_debug(self, parameter_s=''): | |
1265 | """Activate the interactive debugger in post-mortem mode. |
|
1264 | """Activate the interactive debugger in post-mortem mode. | |
1266 |
|
1265 | |||
1267 | If an exception has just occurred, this lets you inspect its stack |
|
1266 | If an exception has just occurred, this lets you inspect its stack | |
1268 | frames interactively. Note that this will always work only on the last |
|
1267 | frames interactively. Note that this will always work only on the last | |
1269 | traceback that occurred, so you must call this quickly after an |
|
1268 | traceback that occurred, so you must call this quickly after an | |
1270 | exception that you wish to inspect has fired, because if another one |
|
1269 | exception that you wish to inspect has fired, because if another one | |
1271 | occurs, it clobbers the previous one. |
|
1270 | occurs, it clobbers the previous one. | |
1272 |
|
1271 | |||
1273 | If you want IPython to automatically do this on every exception, see |
|
1272 | If you want IPython to automatically do this on every exception, see | |
1274 | the %pdb magic for more details. |
|
1273 | the %pdb magic for more details. | |
1275 | """ |
|
1274 | """ | |
1276 | self.shell.debugger(force=True) |
|
1275 | self.shell.debugger(force=True) | |
1277 |
|
1276 | |||
1278 | @skip_doctest |
|
1277 | @skip_doctest | |
1279 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1278 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1280 | opts=None,arg_lst=None,prog_ns=None): |
|
1279 | opts=None,arg_lst=None,prog_ns=None): | |
1281 |
|
1280 | |||
1282 | """Run a statement through the python code profiler. |
|
1281 | """Run a statement through the python code profiler. | |
1283 |
|
1282 | |||
1284 | Usage: |
|
1283 | Usage: | |
1285 | %prun [options] statement |
|
1284 | %prun [options] statement | |
1286 |
|
1285 | |||
1287 | The given statement (which doesn't require quote marks) is run via the |
|
1286 | The given statement (which doesn't require quote marks) is run via the | |
1288 | python profiler in a manner similar to the profile.run() function. |
|
1287 | python profiler in a manner similar to the profile.run() function. | |
1289 | Namespaces are internally managed to work correctly; profile.run |
|
1288 | Namespaces are internally managed to work correctly; profile.run | |
1290 | cannot be used in IPython because it makes certain assumptions about |
|
1289 | cannot be used in IPython because it makes certain assumptions about | |
1291 | namespaces which do not hold under IPython. |
|
1290 | namespaces which do not hold under IPython. | |
1292 |
|
1291 | |||
1293 | Options: |
|
1292 | Options: | |
1294 |
|
1293 | |||
1295 | -l <limit>: you can place restrictions on what or how much of the |
|
1294 | -l <limit>: you can place restrictions on what or how much of the | |
1296 | profile gets printed. The limit value can be: |
|
1295 | profile gets printed. The limit value can be: | |
1297 |
|
1296 | |||
1298 | * A string: only information for function names containing this string |
|
1297 | * A string: only information for function names containing this string | |
1299 | is printed. |
|
1298 | is printed. | |
1300 |
|
1299 | |||
1301 | * An integer: only these many lines are printed. |
|
1300 | * An integer: only these many lines are printed. | |
1302 |
|
1301 | |||
1303 | * A float (between 0 and 1): this fraction of the report is printed |
|
1302 | * A float (between 0 and 1): this fraction of the report is printed | |
1304 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1303 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1305 |
|
1304 | |||
1306 | You can combine several limits with repeated use of the option. For |
|
1305 | You can combine several limits with repeated use of the option. For | |
1307 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1306 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1308 | information about class constructors. |
|
1307 | information about class constructors. | |
1309 |
|
1308 | |||
1310 | -r: return the pstats.Stats object generated by the profiling. This |
|
1309 | -r: return the pstats.Stats object generated by the profiling. This | |
1311 | object has all the information about the profile in it, and you can |
|
1310 | object has all the information about the profile in it, and you can | |
1312 | later use it for further analysis or in other functions. |
|
1311 | later use it for further analysis or in other functions. | |
1313 |
|
1312 | |||
1314 | -s <key>: sort profile by given key. You can provide more than one key |
|
1313 | -s <key>: sort profile by given key. You can provide more than one key | |
1315 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1314 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1316 | default sorting key is 'time'. |
|
1315 | default sorting key is 'time'. | |
1317 |
|
1316 | |||
1318 | The following is copied verbatim from the profile documentation |
|
1317 | The following is copied verbatim from the profile documentation | |
1319 | referenced below: |
|
1318 | referenced below: | |
1320 |
|
1319 | |||
1321 | When more than one key is provided, additional keys are used as |
|
1320 | When more than one key is provided, additional keys are used as | |
1322 | secondary criteria when the there is equality in all keys selected |
|
1321 | secondary criteria when the there is equality in all keys selected | |
1323 | before them. |
|
1322 | before them. | |
1324 |
|
1323 | |||
1325 | Abbreviations can be used for any key names, as long as the |
|
1324 | Abbreviations can be used for any key names, as long as the | |
1326 | abbreviation is unambiguous. The following are the keys currently |
|
1325 | abbreviation is unambiguous. The following are the keys currently | |
1327 | defined: |
|
1326 | defined: | |
1328 |
|
1327 | |||
1329 | Valid Arg Meaning |
|
1328 | Valid Arg Meaning | |
1330 | "calls" call count |
|
1329 | "calls" call count | |
1331 | "cumulative" cumulative time |
|
1330 | "cumulative" cumulative time | |
1332 | "file" file name |
|
1331 | "file" file name | |
1333 | "module" file name |
|
1332 | "module" file name | |
1334 | "pcalls" primitive call count |
|
1333 | "pcalls" primitive call count | |
1335 | "line" line number |
|
1334 | "line" line number | |
1336 | "name" function name |
|
1335 | "name" function name | |
1337 | "nfl" name/file/line |
|
1336 | "nfl" name/file/line | |
1338 | "stdname" standard name |
|
1337 | "stdname" standard name | |
1339 | "time" internal time |
|
1338 | "time" internal time | |
1340 |
|
1339 | |||
1341 | Note that all sorts on statistics are in descending order (placing |
|
1340 | Note that all sorts on statistics are in descending order (placing | |
1342 | most time consuming items first), where as name, file, and line number |
|
1341 | most time consuming items first), where as name, file, and line number | |
1343 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1342 | searches are in ascending order (i.e., alphabetical). The subtle | |
1344 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1343 | distinction between "nfl" and "stdname" is that the standard name is a | |
1345 | sort of the name as printed, which means that the embedded line |
|
1344 | sort of the name as printed, which means that the embedded line | |
1346 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1345 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1347 | would (if the file names were the same) appear in the string order |
|
1346 | would (if the file names were the same) appear in the string order | |
1348 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1347 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1349 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1348 | line numbers. In fact, sort_stats("nfl") is the same as | |
1350 | sort_stats("name", "file", "line"). |
|
1349 | sort_stats("name", "file", "line"). | |
1351 |
|
1350 | |||
1352 | -T <filename>: save profile results as shown on screen to a text |
|
1351 | -T <filename>: save profile results as shown on screen to a text | |
1353 | file. The profile is still shown on screen. |
|
1352 | file. The profile is still shown on screen. | |
1354 |
|
1353 | |||
1355 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1354 | -D <filename>: save (via dump_stats) profile statistics to given | |
1356 | filename. This data is in a format understod by the pstats module, and |
|
1355 | filename. This data is in a format understod by the pstats module, and | |
1357 | is generated by a call to the dump_stats() method of profile |
|
1356 | is generated by a call to the dump_stats() method of profile | |
1358 | objects. The profile is still shown on screen. |
|
1357 | objects. The profile is still shown on screen. | |
1359 |
|
1358 | |||
1360 | If you want to run complete programs under the profiler's control, use |
|
1359 | If you want to run complete programs under the profiler's control, use | |
1361 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1360 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1362 | contains profiler specific options as described here. |
|
1361 | contains profiler specific options as described here. | |
1363 |
|
1362 | |||
1364 | You can read the complete documentation for the profile module with:: |
|
1363 | You can read the complete documentation for the profile module with:: | |
1365 |
|
1364 | |||
1366 | In [1]: import profile; profile.help() |
|
1365 | In [1]: import profile; profile.help() | |
1367 | """ |
|
1366 | """ | |
1368 |
|
1367 | |||
1369 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1368 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1370 | # protect user quote marks |
|
1369 | # protect user quote marks | |
1371 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1370 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1372 |
|
1371 | |||
1373 | if user_mode: # regular user call |
|
1372 | if user_mode: # regular user call | |
1374 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1373 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1375 | list_all=1) |
|
1374 | list_all=1) | |
1376 | namespace = self.shell.user_ns |
|
1375 | namespace = self.shell.user_ns | |
1377 | else: # called to run a program by %run -p |
|
1376 | else: # called to run a program by %run -p | |
1378 | try: |
|
1377 | try: | |
1379 | filename = get_py_filename(arg_lst[0]) |
|
1378 | filename = get_py_filename(arg_lst[0]) | |
1380 | except IOError as e: |
|
1379 | except IOError as e: | |
1381 | try: |
|
1380 | try: | |
1382 | msg = str(e) |
|
1381 | msg = str(e) | |
1383 | except UnicodeError: |
|
1382 | except UnicodeError: | |
1384 | msg = e.message |
|
1383 | msg = e.message | |
1385 | error(msg) |
|
1384 | error(msg) | |
1386 | return |
|
1385 | return | |
1387 |
|
1386 | |||
1388 | arg_str = 'execfile(filename,prog_ns)' |
|
1387 | arg_str = 'execfile(filename,prog_ns)' | |
1389 | namespace = { |
|
1388 | namespace = { | |
1390 | 'execfile': self.shell.safe_execfile, |
|
1389 | 'execfile': self.shell.safe_execfile, | |
1391 | 'prog_ns': prog_ns, |
|
1390 | 'prog_ns': prog_ns, | |
1392 | 'filename': filename |
|
1391 | 'filename': filename | |
1393 | } |
|
1392 | } | |
1394 |
|
1393 | |||
1395 | opts.merge(opts_def) |
|
1394 | opts.merge(opts_def) | |
1396 |
|
1395 | |||
1397 | prof = profile.Profile() |
|
1396 | prof = profile.Profile() | |
1398 | try: |
|
1397 | try: | |
1399 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1398 | prof = prof.runctx(arg_str,namespace,namespace) | |
1400 | sys_exit = '' |
|
1399 | sys_exit = '' | |
1401 | except SystemExit: |
|
1400 | except SystemExit: | |
1402 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1401 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1403 |
|
1402 | |||
1404 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1403 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1405 |
|
1404 | |||
1406 | lims = opts.l |
|
1405 | lims = opts.l | |
1407 | if lims: |
|
1406 | if lims: | |
1408 | lims = [] # rebuild lims with ints/floats/strings |
|
1407 | lims = [] # rebuild lims with ints/floats/strings | |
1409 | for lim in opts.l: |
|
1408 | for lim in opts.l: | |
1410 | try: |
|
1409 | try: | |
1411 | lims.append(int(lim)) |
|
1410 | lims.append(int(lim)) | |
1412 | except ValueError: |
|
1411 | except ValueError: | |
1413 | try: |
|
1412 | try: | |
1414 | lims.append(float(lim)) |
|
1413 | lims.append(float(lim)) | |
1415 | except ValueError: |
|
1414 | except ValueError: | |
1416 | lims.append(lim) |
|
1415 | lims.append(lim) | |
1417 |
|
1416 | |||
1418 | # Trap output. |
|
1417 | # Trap output. | |
1419 | stdout_trap = StringIO() |
|
1418 | stdout_trap = StringIO() | |
1420 |
|
1419 | |||
1421 | if hasattr(stats,'stream'): |
|
1420 | if hasattr(stats,'stream'): | |
1422 | # In newer versions of python, the stats object has a 'stream' |
|
1421 | # In newer versions of python, the stats object has a 'stream' | |
1423 | # attribute to write into. |
|
1422 | # attribute to write into. | |
1424 | stats.stream = stdout_trap |
|
1423 | stats.stream = stdout_trap | |
1425 | stats.print_stats(*lims) |
|
1424 | stats.print_stats(*lims) | |
1426 | else: |
|
1425 | else: | |
1427 | # For older versions, we manually redirect stdout during printing |
|
1426 | # For older versions, we manually redirect stdout during printing | |
1428 | sys_stdout = sys.stdout |
|
1427 | sys_stdout = sys.stdout | |
1429 | try: |
|
1428 | try: | |
1430 | sys.stdout = stdout_trap |
|
1429 | sys.stdout = stdout_trap | |
1431 | stats.print_stats(*lims) |
|
1430 | stats.print_stats(*lims) | |
1432 | finally: |
|
1431 | finally: | |
1433 | sys.stdout = sys_stdout |
|
1432 | sys.stdout = sys_stdout | |
1434 |
|
1433 | |||
1435 | output = stdout_trap.getvalue() |
|
1434 | output = stdout_trap.getvalue() | |
1436 | output = output.rstrip() |
|
1435 | output = output.rstrip() | |
1437 |
|
1436 | |||
1438 | page.page(output) |
|
1437 | page.page(output) | |
1439 | print sys_exit, |
|
1438 | print sys_exit, | |
1440 |
|
1439 | |||
1441 | dump_file = opts.D[0] |
|
1440 | dump_file = opts.D[0] | |
1442 | text_file = opts.T[0] |
|
1441 | text_file = opts.T[0] | |
1443 | if dump_file: |
|
1442 | if dump_file: | |
1444 | dump_file = unquote_filename(dump_file) |
|
1443 | dump_file = unquote_filename(dump_file) | |
1445 | prof.dump_stats(dump_file) |
|
1444 | prof.dump_stats(dump_file) | |
1446 | print '\n*** Profile stats marshalled to file',\ |
|
1445 | print '\n*** Profile stats marshalled to file',\ | |
1447 | `dump_file`+'.',sys_exit |
|
1446 | `dump_file`+'.',sys_exit | |
1448 | if text_file: |
|
1447 | if text_file: | |
1449 | text_file = unquote_filename(text_file) |
|
1448 | text_file = unquote_filename(text_file) | |
1450 | pfile = file(text_file,'w') |
|
1449 | pfile = file(text_file,'w') | |
1451 | pfile.write(output) |
|
1450 | pfile.write(output) | |
1452 | pfile.close() |
|
1451 | pfile.close() | |
1453 | print '\n*** Profile printout saved to text file',\ |
|
1452 | print '\n*** Profile printout saved to text file',\ | |
1454 | `text_file`+'.',sys_exit |
|
1453 | `text_file`+'.',sys_exit | |
1455 |
|
1454 | |||
1456 | if opts.has_key('r'): |
|
1455 | if opts.has_key('r'): | |
1457 | return stats |
|
1456 | return stats | |
1458 | else: |
|
1457 | else: | |
1459 | return None |
|
1458 | return None | |
1460 |
|
1459 | |||
1461 | @skip_doctest |
|
1460 | @skip_doctest | |
1462 | def magic_run(self, parameter_s ='', runner=None, |
|
1461 | def magic_run(self, parameter_s ='', runner=None, | |
1463 | file_finder=get_py_filename): |
|
1462 | file_finder=get_py_filename): | |
1464 | """Run the named file inside IPython as a program. |
|
1463 | """Run the named file inside IPython as a program. | |
1465 |
|
1464 | |||
1466 | Usage:\\ |
|
1465 | Usage:\\ | |
1467 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1466 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1468 |
|
1467 | |||
1469 | Parameters after the filename are passed as command-line arguments to |
|
1468 | Parameters after the filename are passed as command-line arguments to | |
1470 | the program (put in sys.argv). Then, control returns to IPython's |
|
1469 | the program (put in sys.argv). Then, control returns to IPython's | |
1471 | prompt. |
|
1470 | prompt. | |
1472 |
|
1471 | |||
1473 | This is similar to running at a system prompt:\\ |
|
1472 | This is similar to running at a system prompt:\\ | |
1474 | $ python file args\\ |
|
1473 | $ python file args\\ | |
1475 | but with the advantage of giving you IPython's tracebacks, and of |
|
1474 | but with the advantage of giving you IPython's tracebacks, and of | |
1476 | loading all variables into your interactive namespace for further use |
|
1475 | loading all variables into your interactive namespace for further use | |
1477 | (unless -p is used, see below). |
|
1476 | (unless -p is used, see below). | |
1478 |
|
1477 | |||
1479 | The file is executed in a namespace initially consisting only of |
|
1478 | The file is executed in a namespace initially consisting only of | |
1480 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1479 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1481 | sees its environment as if it were being run as a stand-alone program |
|
1480 | sees its environment as if it were being run as a stand-alone program | |
1482 | (except for sharing global objects such as previously imported |
|
1481 | (except for sharing global objects such as previously imported | |
1483 | modules). But after execution, the IPython interactive namespace gets |
|
1482 | modules). But after execution, the IPython interactive namespace gets | |
1484 | updated with all variables defined in the program (except for __name__ |
|
1483 | updated with all variables defined in the program (except for __name__ | |
1485 | and sys.argv). This allows for very convenient loading of code for |
|
1484 | and sys.argv). This allows for very convenient loading of code for | |
1486 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1485 | interactive work, while giving each program a 'clean sheet' to run in. | |
1487 |
|
1486 | |||
1488 | Options: |
|
1487 | Options: | |
1489 |
|
1488 | |||
1490 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1489 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1491 | without extension (as python does under import). This allows running |
|
1490 | without extension (as python does under import). This allows running | |
1492 | scripts and reloading the definitions in them without calling code |
|
1491 | scripts and reloading the definitions in them without calling code | |
1493 | protected by an ' if __name__ == "__main__" ' clause. |
|
1492 | protected by an ' if __name__ == "__main__" ' clause. | |
1494 |
|
1493 | |||
1495 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1494 | -i: run the file in IPython's namespace instead of an empty one. This | |
1496 | is useful if you are experimenting with code written in a text editor |
|
1495 | is useful if you are experimenting with code written in a text editor | |
1497 | which depends on variables defined interactively. |
|
1496 | which depends on variables defined interactively. | |
1498 |
|
1497 | |||
1499 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1498 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1500 | being run. This is particularly useful if IPython is being used to |
|
1499 | being run. This is particularly useful if IPython is being used to | |
1501 | run unittests, which always exit with a sys.exit() call. In such |
|
1500 | run unittests, which always exit with a sys.exit() call. In such | |
1502 | cases you are interested in the output of the test results, not in |
|
1501 | cases you are interested in the output of the test results, not in | |
1503 | seeing a traceback of the unittest module. |
|
1502 | seeing a traceback of the unittest module. | |
1504 |
|
1503 | |||
1505 | -t: print timing information at the end of the run. IPython will give |
|
1504 | -t: print timing information at the end of the run. IPython will give | |
1506 | you an estimated CPU time consumption for your script, which under |
|
1505 | you an estimated CPU time consumption for your script, which under | |
1507 | Unix uses the resource module to avoid the wraparound problems of |
|
1506 | Unix uses the resource module to avoid the wraparound problems of | |
1508 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1507 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1509 | is also given (for Windows platforms this is reported as 0.0). |
|
1508 | is also given (for Windows platforms this is reported as 0.0). | |
1510 |
|
1509 | |||
1511 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1510 | If -t is given, an additional -N<N> option can be given, where <N> | |
1512 | must be an integer indicating how many times you want the script to |
|
1511 | must be an integer indicating how many times you want the script to | |
1513 | run. The final timing report will include total and per run results. |
|
1512 | run. The final timing report will include total and per run results. | |
1514 |
|
1513 | |||
1515 | For example (testing the script uniq_stable.py): |
|
1514 | For example (testing the script uniq_stable.py): | |
1516 |
|
1515 | |||
1517 | In [1]: run -t uniq_stable |
|
1516 | In [1]: run -t uniq_stable | |
1518 |
|
1517 | |||
1519 | IPython CPU timings (estimated):\\ |
|
1518 | IPython CPU timings (estimated):\\ | |
1520 | User : 0.19597 s.\\ |
|
1519 | User : 0.19597 s.\\ | |
1521 | System: 0.0 s.\\ |
|
1520 | System: 0.0 s.\\ | |
1522 |
|
1521 | |||
1523 | In [2]: run -t -N5 uniq_stable |
|
1522 | In [2]: run -t -N5 uniq_stable | |
1524 |
|
1523 | |||
1525 | IPython CPU timings (estimated):\\ |
|
1524 | IPython CPU timings (estimated):\\ | |
1526 | Total runs performed: 5\\ |
|
1525 | Total runs performed: 5\\ | |
1527 | Times : Total Per run\\ |
|
1526 | Times : Total Per run\\ | |
1528 | User : 0.910862 s, 0.1821724 s.\\ |
|
1527 | User : 0.910862 s, 0.1821724 s.\\ | |
1529 | System: 0.0 s, 0.0 s. |
|
1528 | System: 0.0 s, 0.0 s. | |
1530 |
|
1529 | |||
1531 | -d: run your program under the control of pdb, the Python debugger. |
|
1530 | -d: run your program under the control of pdb, the Python debugger. | |
1532 | This allows you to execute your program step by step, watch variables, |
|
1531 | This allows you to execute your program step by step, watch variables, | |
1533 | etc. Internally, what IPython does is similar to calling: |
|
1532 | etc. Internally, what IPython does is similar to calling: | |
1534 |
|
1533 | |||
1535 | pdb.run('execfile("YOURFILENAME")') |
|
1534 | pdb.run('execfile("YOURFILENAME")') | |
1536 |
|
1535 | |||
1537 | with a breakpoint set on line 1 of your file. You can change the line |
|
1536 | with a breakpoint set on line 1 of your file. You can change the line | |
1538 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1537 | number for this automatic breakpoint to be <N> by using the -bN option | |
1539 | (where N must be an integer). For example: |
|
1538 | (where N must be an integer). For example: | |
1540 |
|
1539 | |||
1541 | %run -d -b40 myscript |
|
1540 | %run -d -b40 myscript | |
1542 |
|
1541 | |||
1543 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1542 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1544 | the first breakpoint must be set on a line which actually does |
|
1543 | the first breakpoint must be set on a line which actually does | |
1545 | something (not a comment or docstring) for it to stop execution. |
|
1544 | something (not a comment or docstring) for it to stop execution. | |
1546 |
|
1545 | |||
1547 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1546 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1548 | first enter 'c' (without qoutes) to start execution up to the first |
|
1547 | first enter 'c' (without qoutes) to start execution up to the first | |
1549 | breakpoint. |
|
1548 | breakpoint. | |
1550 |
|
1549 | |||
1551 | Entering 'help' gives information about the use of the debugger. You |
|
1550 | Entering 'help' gives information about the use of the debugger. You | |
1552 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1551 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1553 | at a prompt. |
|
1552 | at a prompt. | |
1554 |
|
1553 | |||
1555 | -p: run program under the control of the Python profiler module (which |
|
1554 | -p: run program under the control of the Python profiler module (which | |
1556 | prints a detailed report of execution times, function calls, etc). |
|
1555 | prints a detailed report of execution times, function calls, etc). | |
1557 |
|
1556 | |||
1558 | You can pass other options after -p which affect the behavior of the |
|
1557 | You can pass other options after -p which affect the behavior of the | |
1559 | profiler itself. See the docs for %prun for details. |
|
1558 | profiler itself. See the docs for %prun for details. | |
1560 |
|
1559 | |||
1561 | In this mode, the program's variables do NOT propagate back to the |
|
1560 | In this mode, the program's variables do NOT propagate back to the | |
1562 | IPython interactive namespace (because they remain in the namespace |
|
1561 | IPython interactive namespace (because they remain in the namespace | |
1563 | where the profiler executes them). |
|
1562 | where the profiler executes them). | |
1564 |
|
1563 | |||
1565 | Internally this triggers a call to %prun, see its documentation for |
|
1564 | Internally this triggers a call to %prun, see its documentation for | |
1566 | details on the options available specifically for profiling. |
|
1565 | details on the options available specifically for profiling. | |
1567 |
|
1566 | |||
1568 | There is one special usage for which the text above doesn't apply: |
|
1567 | There is one special usage for which the text above doesn't apply: | |
1569 | if the filename ends with .ipy, the file is run as ipython script, |
|
1568 | if the filename ends with .ipy, the file is run as ipython script, | |
1570 | just as if the commands were written on IPython prompt. |
|
1569 | just as if the commands were written on IPython prompt. | |
1571 |
|
1570 | |||
1572 | -m: specify module name to load instead of script path. Similar to |
|
1571 | -m: specify module name to load instead of script path. Similar to | |
1573 | the -m option for the python interpreter. Use this option last if you |
|
1572 | the -m option for the python interpreter. Use this option last if you | |
1574 | want to combine with other %run options. Unlike the python interpreter |
|
1573 | want to combine with other %run options. Unlike the python interpreter | |
1575 | only source modules are allowed no .pyc or .pyo files. |
|
1574 | only source modules are allowed no .pyc or .pyo files. | |
1576 | For example: |
|
1575 | For example: | |
1577 |
|
1576 | |||
1578 | %run -m example |
|
1577 | %run -m example | |
1579 |
|
1578 | |||
1580 | will run the example module. |
|
1579 | will run the example module. | |
1581 |
|
1580 | |||
1582 | """ |
|
1581 | """ | |
1583 |
|
1582 | |||
1584 | # get arguments and set sys.argv for program to be run. |
|
1583 | # get arguments and set sys.argv for program to be run. | |
1585 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', |
|
1584 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', | |
1586 | mode='list', list_all=1) |
|
1585 | mode='list', list_all=1) | |
1587 | if "m" in opts: |
|
1586 | if "m" in opts: | |
1588 | modulename = opts["m"][0] |
|
1587 | modulename = opts["m"][0] | |
1589 | modpath = find_mod(modulename) |
|
1588 | modpath = find_mod(modulename) | |
1590 | if modpath is None: |
|
1589 | if modpath is None: | |
1591 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
1590 | warn('%r is not a valid modulename on sys.path'%modulename) | |
1592 | return |
|
1591 | return | |
1593 | arg_lst = [modpath] + arg_lst |
|
1592 | arg_lst = [modpath] + arg_lst | |
1594 | try: |
|
1593 | try: | |
1595 | filename = file_finder(arg_lst[0]) |
|
1594 | filename = file_finder(arg_lst[0]) | |
1596 | except IndexError: |
|
1595 | except IndexError: | |
1597 | warn('you must provide at least a filename.') |
|
1596 | warn('you must provide at least a filename.') | |
1598 | print '\n%run:\n', oinspect.getdoc(self.magic_run) |
|
1597 | print '\n%run:\n', oinspect.getdoc(self.magic_run) | |
1599 | return |
|
1598 | return | |
1600 | except IOError as e: |
|
1599 | except IOError as e: | |
1601 | try: |
|
1600 | try: | |
1602 | msg = str(e) |
|
1601 | msg = str(e) | |
1603 | except UnicodeError: |
|
1602 | except UnicodeError: | |
1604 | msg = e.message |
|
1603 | msg = e.message | |
1605 | error(msg) |
|
1604 | error(msg) | |
1606 | return |
|
1605 | return | |
1607 |
|
1606 | |||
1608 | if filename.lower().endswith('.ipy'): |
|
1607 | if filename.lower().endswith('.ipy'): | |
1609 | self.shell.safe_execfile_ipy(filename) |
|
1608 | self.shell.safe_execfile_ipy(filename) | |
1610 | return |
|
1609 | return | |
1611 |
|
1610 | |||
1612 | # Control the response to exit() calls made by the script being run |
|
1611 | # Control the response to exit() calls made by the script being run | |
1613 | exit_ignore = 'e' in opts |
|
1612 | exit_ignore = 'e' in opts | |
1614 |
|
1613 | |||
1615 | # Make sure that the running script gets a proper sys.argv as if it |
|
1614 | # Make sure that the running script gets a proper sys.argv as if it | |
1616 | # were run from a system shell. |
|
1615 | # were run from a system shell. | |
1617 | save_argv = sys.argv # save it for later restoring |
|
1616 | save_argv = sys.argv # save it for later restoring | |
1618 |
|
1617 | |||
1619 | # simulate shell expansion on arguments, at least tilde expansion |
|
1618 | # simulate shell expansion on arguments, at least tilde expansion | |
1620 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] |
|
1619 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] | |
1621 |
|
1620 | |||
1622 | sys.argv = [filename] + args # put in the proper filename |
|
1621 | sys.argv = [filename] + args # put in the proper filename | |
1623 | # protect sys.argv from potential unicode strings on Python 2: |
|
1622 | # protect sys.argv from potential unicode strings on Python 2: | |
1624 | if not py3compat.PY3: |
|
1623 | if not py3compat.PY3: | |
1625 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
1624 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] | |
1626 |
|
1625 | |||
1627 | if 'i' in opts: |
|
1626 | if 'i' in opts: | |
1628 | # Run in user's interactive namespace |
|
1627 | # Run in user's interactive namespace | |
1629 | prog_ns = self.shell.user_ns |
|
1628 | prog_ns = self.shell.user_ns | |
1630 | __name__save = self.shell.user_ns['__name__'] |
|
1629 | __name__save = self.shell.user_ns['__name__'] | |
1631 | prog_ns['__name__'] = '__main__' |
|
1630 | prog_ns['__name__'] = '__main__' | |
1632 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1631 | main_mod = self.shell.new_main_mod(prog_ns) | |
1633 | else: |
|
1632 | else: | |
1634 | # Run in a fresh, empty namespace |
|
1633 | # Run in a fresh, empty namespace | |
1635 | if 'n' in opts: |
|
1634 | if 'n' in opts: | |
1636 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1635 | name = os.path.splitext(os.path.basename(filename))[0] | |
1637 | else: |
|
1636 | else: | |
1638 | name = '__main__' |
|
1637 | name = '__main__' | |
1639 |
|
1638 | |||
1640 | main_mod = self.shell.new_main_mod() |
|
1639 | main_mod = self.shell.new_main_mod() | |
1641 | prog_ns = main_mod.__dict__ |
|
1640 | prog_ns = main_mod.__dict__ | |
1642 | prog_ns['__name__'] = name |
|
1641 | prog_ns['__name__'] = name | |
1643 |
|
1642 | |||
1644 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1643 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1645 | # set the __file__ global in the script's namespace |
|
1644 | # set the __file__ global in the script's namespace | |
1646 | prog_ns['__file__'] = filename |
|
1645 | prog_ns['__file__'] = filename | |
1647 |
|
1646 | |||
1648 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1647 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1649 | # that, if we overwrite __main__, we replace it at the end |
|
1648 | # that, if we overwrite __main__, we replace it at the end | |
1650 | main_mod_name = prog_ns['__name__'] |
|
1649 | main_mod_name = prog_ns['__name__'] | |
1651 |
|
1650 | |||
1652 | if main_mod_name == '__main__': |
|
1651 | if main_mod_name == '__main__': | |
1653 | restore_main = sys.modules['__main__'] |
|
1652 | restore_main = sys.modules['__main__'] | |
1654 | else: |
|
1653 | else: | |
1655 | restore_main = False |
|
1654 | restore_main = False | |
1656 |
|
1655 | |||
1657 | # This needs to be undone at the end to prevent holding references to |
|
1656 | # This needs to be undone at the end to prevent holding references to | |
1658 | # every single object ever created. |
|
1657 | # every single object ever created. | |
1659 | sys.modules[main_mod_name] = main_mod |
|
1658 | sys.modules[main_mod_name] = main_mod | |
1660 |
|
1659 | |||
1661 | try: |
|
1660 | try: | |
1662 | stats = None |
|
1661 | stats = None | |
1663 | with self.readline_no_record: |
|
1662 | with self.readline_no_record: | |
1664 | if 'p' in opts: |
|
1663 | if 'p' in opts: | |
1665 | stats = self.magic_prun('', 0, opts, arg_lst, prog_ns) |
|
1664 | stats = self.magic_prun('', 0, opts, arg_lst, prog_ns) | |
1666 | else: |
|
1665 | else: | |
1667 | if 'd' in opts: |
|
1666 | if 'd' in opts: | |
1668 | deb = debugger.Pdb(self.shell.colors) |
|
1667 | deb = debugger.Pdb(self.shell.colors) | |
1669 | # reset Breakpoint state, which is moronically kept |
|
1668 | # reset Breakpoint state, which is moronically kept | |
1670 | # in a class |
|
1669 | # in a class | |
1671 | bdb.Breakpoint.next = 1 |
|
1670 | bdb.Breakpoint.next = 1 | |
1672 | bdb.Breakpoint.bplist = {} |
|
1671 | bdb.Breakpoint.bplist = {} | |
1673 | bdb.Breakpoint.bpbynumber = [None] |
|
1672 | bdb.Breakpoint.bpbynumber = [None] | |
1674 | # Set an initial breakpoint to stop execution |
|
1673 | # Set an initial breakpoint to stop execution | |
1675 | maxtries = 10 |
|
1674 | maxtries = 10 | |
1676 | bp = int(opts.get('b', [1])[0]) |
|
1675 | bp = int(opts.get('b', [1])[0]) | |
1677 | checkline = deb.checkline(filename, bp) |
|
1676 | checkline = deb.checkline(filename, bp) | |
1678 | if not checkline: |
|
1677 | if not checkline: | |
1679 | for bp in range(bp + 1, bp + maxtries + 1): |
|
1678 | for bp in range(bp + 1, bp + maxtries + 1): | |
1680 | if deb.checkline(filename, bp): |
|
1679 | if deb.checkline(filename, bp): | |
1681 | break |
|
1680 | break | |
1682 | else: |
|
1681 | else: | |
1683 | msg = ("\nI failed to find a valid line to set " |
|
1682 | msg = ("\nI failed to find a valid line to set " | |
1684 | "a breakpoint\n" |
|
1683 | "a breakpoint\n" | |
1685 | "after trying up to line: %s.\n" |
|
1684 | "after trying up to line: %s.\n" | |
1686 | "Please set a valid breakpoint manually " |
|
1685 | "Please set a valid breakpoint manually " | |
1687 | "with the -b option." % bp) |
|
1686 | "with the -b option." % bp) | |
1688 | error(msg) |
|
1687 | error(msg) | |
1689 | return |
|
1688 | return | |
1690 | # if we find a good linenumber, set the breakpoint |
|
1689 | # if we find a good linenumber, set the breakpoint | |
1691 | deb.do_break('%s:%s' % (filename, bp)) |
|
1690 | deb.do_break('%s:%s' % (filename, bp)) | |
1692 | # Start file run |
|
1691 | # Start file run | |
1693 | print "NOTE: Enter 'c' at the", |
|
1692 | print "NOTE: Enter 'c' at the", | |
1694 | print "%s prompt to start your script." % deb.prompt |
|
1693 | print "%s prompt to start your script." % deb.prompt | |
1695 | try: |
|
1694 | try: | |
1696 | deb.run('execfile("%s")' % filename, prog_ns) |
|
1695 | deb.run('execfile("%s")' % filename, prog_ns) | |
1697 |
|
1696 | |||
1698 | except: |
|
1697 | except: | |
1699 | etype, value, tb = sys.exc_info() |
|
1698 | etype, value, tb = sys.exc_info() | |
1700 | # Skip three frames in the traceback: the %run one, |
|
1699 | # Skip three frames in the traceback: the %run one, | |
1701 | # one inside bdb.py, and the command-line typed by the |
|
1700 | # one inside bdb.py, and the command-line typed by the | |
1702 | # user (run by exec in pdb itself). |
|
1701 | # user (run by exec in pdb itself). | |
1703 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
1702 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) | |
1704 | else: |
|
1703 | else: | |
1705 | if runner is None: |
|
1704 | if runner is None: | |
1706 | runner = self.shell.safe_execfile |
|
1705 | runner = self.shell.safe_execfile | |
1707 | if 't' in opts: |
|
1706 | if 't' in opts: | |
1708 | # timed execution |
|
1707 | # timed execution | |
1709 | try: |
|
1708 | try: | |
1710 | nruns = int(opts['N'][0]) |
|
1709 | nruns = int(opts['N'][0]) | |
1711 | if nruns < 1: |
|
1710 | if nruns < 1: | |
1712 | error('Number of runs must be >=1') |
|
1711 | error('Number of runs must be >=1') | |
1713 | return |
|
1712 | return | |
1714 | except (KeyError): |
|
1713 | except (KeyError): | |
1715 | nruns = 1 |
|
1714 | nruns = 1 | |
1716 | twall0 = time.time() |
|
1715 | twall0 = time.time() | |
1717 | if nruns == 1: |
|
1716 | if nruns == 1: | |
1718 | t0 = clock2() |
|
1717 | t0 = clock2() | |
1719 | runner(filename, prog_ns, prog_ns, |
|
1718 | runner(filename, prog_ns, prog_ns, | |
1720 | exit_ignore=exit_ignore) |
|
1719 | exit_ignore=exit_ignore) | |
1721 | t1 = clock2() |
|
1720 | t1 = clock2() | |
1722 | t_usr = t1[0] - t0[0] |
|
1721 | t_usr = t1[0] - t0[0] | |
1723 | t_sys = t1[1] - t0[1] |
|
1722 | t_sys = t1[1] - t0[1] | |
1724 | print "\nIPython CPU timings (estimated):" |
|
1723 | print "\nIPython CPU timings (estimated):" | |
1725 | print " User : %10.2f s." % t_usr |
|
1724 | print " User : %10.2f s." % t_usr | |
1726 | print " System : %10.2f s." % t_sys |
|
1725 | print " System : %10.2f s." % t_sys | |
1727 | else: |
|
1726 | else: | |
1728 | runs = range(nruns) |
|
1727 | runs = range(nruns) | |
1729 | t0 = clock2() |
|
1728 | t0 = clock2() | |
1730 | for nr in runs: |
|
1729 | for nr in runs: | |
1731 | runner(filename, prog_ns, prog_ns, |
|
1730 | runner(filename, prog_ns, prog_ns, | |
1732 | exit_ignore=exit_ignore) |
|
1731 | exit_ignore=exit_ignore) | |
1733 | t1 = clock2() |
|
1732 | t1 = clock2() | |
1734 | t_usr = t1[0] - t0[0] |
|
1733 | t_usr = t1[0] - t0[0] | |
1735 | t_sys = t1[1] - t0[1] |
|
1734 | t_sys = t1[1] - t0[1] | |
1736 | print "\nIPython CPU timings (estimated):" |
|
1735 | print "\nIPython CPU timings (estimated):" | |
1737 | print "Total runs performed:", nruns |
|
1736 | print "Total runs performed:", nruns | |
1738 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') |
|
1737 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') | |
1739 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) |
|
1738 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) | |
1740 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) |
|
1739 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) | |
1741 | twall1 = time.time() |
|
1740 | twall1 = time.time() | |
1742 | print "Wall time: %10.2f s." % (twall1 - twall0) |
|
1741 | print "Wall time: %10.2f s." % (twall1 - twall0) | |
1743 |
|
1742 | |||
1744 | else: |
|
1743 | else: | |
1745 | # regular execution |
|
1744 | # regular execution | |
1746 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) |
|
1745 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) | |
1747 |
|
1746 | |||
1748 | if 'i' in opts: |
|
1747 | if 'i' in opts: | |
1749 | self.shell.user_ns['__name__'] = __name__save |
|
1748 | self.shell.user_ns['__name__'] = __name__save | |
1750 | else: |
|
1749 | else: | |
1751 | # The shell MUST hold a reference to prog_ns so after %run |
|
1750 | # The shell MUST hold a reference to prog_ns so after %run | |
1752 | # exits, the python deletion mechanism doesn't zero it out |
|
1751 | # exits, the python deletion mechanism doesn't zero it out | |
1753 | # (leaving dangling references). |
|
1752 | # (leaving dangling references). | |
1754 | self.shell.cache_main_mod(prog_ns, filename) |
|
1753 | self.shell.cache_main_mod(prog_ns, filename) | |
1755 | # update IPython interactive namespace |
|
1754 | # update IPython interactive namespace | |
1756 |
|
1755 | |||
1757 | # Some forms of read errors on the file may mean the |
|
1756 | # Some forms of read errors on the file may mean the | |
1758 | # __name__ key was never set; using pop we don't have to |
|
1757 | # __name__ key was never set; using pop we don't have to | |
1759 | # worry about a possible KeyError. |
|
1758 | # worry about a possible KeyError. | |
1760 | prog_ns.pop('__name__', None) |
|
1759 | prog_ns.pop('__name__', None) | |
1761 |
|
1760 | |||
1762 | self.shell.user_ns.update(prog_ns) |
|
1761 | self.shell.user_ns.update(prog_ns) | |
1763 | finally: |
|
1762 | finally: | |
1764 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1763 | # It's a bit of a mystery why, but __builtins__ can change from | |
1765 | # being a module to becoming a dict missing some key data after |
|
1764 | # being a module to becoming a dict missing some key data after | |
1766 | # %run. As best I can see, this is NOT something IPython is doing |
|
1765 | # %run. As best I can see, this is NOT something IPython is doing | |
1767 | # at all, and similar problems have been reported before: |
|
1766 | # at all, and similar problems have been reported before: | |
1768 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1767 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1769 | # Since this seems to be done by the interpreter itself, the best |
|
1768 | # Since this seems to be done by the interpreter itself, the best | |
1770 | # we can do is to at least restore __builtins__ for the user on |
|
1769 | # we can do is to at least restore __builtins__ for the user on | |
1771 | # exit. |
|
1770 | # exit. | |
1772 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
1771 | self.shell.user_ns['__builtins__'] = builtin_mod | |
1773 |
|
1772 | |||
1774 | # Ensure key global structures are restored |
|
1773 | # Ensure key global structures are restored | |
1775 | sys.argv = save_argv |
|
1774 | sys.argv = save_argv | |
1776 | if restore_main: |
|
1775 | if restore_main: | |
1777 | sys.modules['__main__'] = restore_main |
|
1776 | sys.modules['__main__'] = restore_main | |
1778 | else: |
|
1777 | else: | |
1779 | # Remove from sys.modules the reference to main_mod we'd |
|
1778 | # Remove from sys.modules the reference to main_mod we'd | |
1780 | # added. Otherwise it will trap references to objects |
|
1779 | # added. Otherwise it will trap references to objects | |
1781 | # contained therein. |
|
1780 | # contained therein. | |
1782 | del sys.modules[main_mod_name] |
|
1781 | del sys.modules[main_mod_name] | |
1783 |
|
1782 | |||
1784 | return stats |
|
1783 | return stats | |
1785 |
|
1784 | |||
1786 | @skip_doctest |
|
1785 | @skip_doctest | |
1787 | def magic_timeit(self, parameter_s =''): |
|
1786 | def magic_timeit(self, parameter_s =''): | |
1788 | """Time execution of a Python statement or expression |
|
1787 | """Time execution of a Python statement or expression | |
1789 |
|
1788 | |||
1790 | Usage:\\ |
|
1789 | Usage:\\ | |
1791 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1790 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1792 |
|
1791 | |||
1793 | Time execution of a Python statement or expression using the timeit |
|
1792 | Time execution of a Python statement or expression using the timeit | |
1794 | module. |
|
1793 | module. | |
1795 |
|
1794 | |||
1796 | Options: |
|
1795 | Options: | |
1797 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1796 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1798 | is not given, a fitting value is chosen. |
|
1797 | is not given, a fitting value is chosen. | |
1799 |
|
1798 | |||
1800 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1799 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1801 | Default: 3 |
|
1800 | Default: 3 | |
1802 |
|
1801 | |||
1803 | -t: use time.time to measure the time, which is the default on Unix. |
|
1802 | -t: use time.time to measure the time, which is the default on Unix. | |
1804 | This function measures wall time. |
|
1803 | This function measures wall time. | |
1805 |
|
1804 | |||
1806 | -c: use time.clock to measure the time, which is the default on |
|
1805 | -c: use time.clock to measure the time, which is the default on | |
1807 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1806 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1808 | instead and returns the CPU user time. |
|
1807 | instead and returns the CPU user time. | |
1809 |
|
1808 | |||
1810 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1809 | -p<P>: use a precision of <P> digits to display the timing result. | |
1811 | Default: 3 |
|
1810 | Default: 3 | |
1812 |
|
1811 | |||
1813 |
|
1812 | |||
1814 | Examples: |
|
1813 | Examples: | |
1815 |
|
1814 | |||
1816 | In [1]: %timeit pass |
|
1815 | In [1]: %timeit pass | |
1817 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1816 | 10000000 loops, best of 3: 53.3 ns per loop | |
1818 |
|
1817 | |||
1819 | In [2]: u = None |
|
1818 | In [2]: u = None | |
1820 |
|
1819 | |||
1821 | In [3]: %timeit u is None |
|
1820 | In [3]: %timeit u is None | |
1822 | 10000000 loops, best of 3: 184 ns per loop |
|
1821 | 10000000 loops, best of 3: 184 ns per loop | |
1823 |
|
1822 | |||
1824 | In [4]: %timeit -r 4 u == None |
|
1823 | In [4]: %timeit -r 4 u == None | |
1825 | 1000000 loops, best of 4: 242 ns per loop |
|
1824 | 1000000 loops, best of 4: 242 ns per loop | |
1826 |
|
1825 | |||
1827 | In [5]: import time |
|
1826 | In [5]: import time | |
1828 |
|
1827 | |||
1829 | In [6]: %timeit -n1 time.sleep(2) |
|
1828 | In [6]: %timeit -n1 time.sleep(2) | |
1830 | 1 loops, best of 3: 2 s per loop |
|
1829 | 1 loops, best of 3: 2 s per loop | |
1831 |
|
1830 | |||
1832 |
|
1831 | |||
1833 | The times reported by %timeit will be slightly higher than those |
|
1832 | The times reported by %timeit will be slightly higher than those | |
1834 | reported by the timeit.py script when variables are accessed. This is |
|
1833 | reported by the timeit.py script when variables are accessed. This is | |
1835 | due to the fact that %timeit executes the statement in the namespace |
|
1834 | due to the fact that %timeit executes the statement in the namespace | |
1836 | of the shell, compared with timeit.py, which uses a single setup |
|
1835 | of the shell, compared with timeit.py, which uses a single setup | |
1837 | statement to import function or create variables. Generally, the bias |
|
1836 | statement to import function or create variables. Generally, the bias | |
1838 | does not matter as long as results from timeit.py are not mixed with |
|
1837 | does not matter as long as results from timeit.py are not mixed with | |
1839 | those from %timeit.""" |
|
1838 | those from %timeit.""" | |
1840 |
|
1839 | |||
1841 | import timeit |
|
1840 | import timeit | |
1842 | import math |
|
1841 | import math | |
1843 |
|
1842 | |||
1844 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1843 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1845 | # certain terminals. Until we figure out a robust way of |
|
1844 | # certain terminals. Until we figure out a robust way of | |
1846 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1845 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1847 | # microseconds. I am really NOT happy about disabling the proper |
|
1846 | # microseconds. I am really NOT happy about disabling the proper | |
1848 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1847 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1849 | # right solution for this is, I'm all ears... |
|
1848 | # right solution for this is, I'm all ears... | |
1850 | # |
|
1849 | # | |
1851 | # Note: using |
|
1850 | # Note: using | |
1852 | # |
|
1851 | # | |
1853 | # s = u'\xb5' |
|
1852 | # s = u'\xb5' | |
1854 | # s.encode(sys.getdefaultencoding()) |
|
1853 | # s.encode(sys.getdefaultencoding()) | |
1855 | # |
|
1854 | # | |
1856 | # is not sufficient, as I've seen terminals where that fails but |
|
1855 | # is not sufficient, as I've seen terminals where that fails but | |
1857 | # print s |
|
1856 | # print s | |
1858 | # |
|
1857 | # | |
1859 | # succeeds |
|
1858 | # succeeds | |
1860 | # |
|
1859 | # | |
1861 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1860 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1862 |
|
1861 | |||
1863 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1862 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1864 | units = [u"s", u"ms",u'us',"ns"] |
|
1863 | units = [u"s", u"ms",u'us',"ns"] | |
1865 |
|
1864 | |||
1866 | scaling = [1, 1e3, 1e6, 1e9] |
|
1865 | scaling = [1, 1e3, 1e6, 1e9] | |
1867 |
|
1866 | |||
1868 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1867 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1869 | posix=False) |
|
1868 | posix=False) | |
1870 | if stmt == "": |
|
1869 | if stmt == "": | |
1871 | return |
|
1870 | return | |
1872 | timefunc = timeit.default_timer |
|
1871 | timefunc = timeit.default_timer | |
1873 | number = int(getattr(opts, "n", 0)) |
|
1872 | number = int(getattr(opts, "n", 0)) | |
1874 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1873 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1875 | precision = int(getattr(opts, "p", 3)) |
|
1874 | precision = int(getattr(opts, "p", 3)) | |
1876 | if hasattr(opts, "t"): |
|
1875 | if hasattr(opts, "t"): | |
1877 | timefunc = time.time |
|
1876 | timefunc = time.time | |
1878 | if hasattr(opts, "c"): |
|
1877 | if hasattr(opts, "c"): | |
1879 | timefunc = clock |
|
1878 | timefunc = clock | |
1880 |
|
1879 | |||
1881 | timer = timeit.Timer(timer=timefunc) |
|
1880 | timer = timeit.Timer(timer=timefunc) | |
1882 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1881 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1883 | # but is there a better way to achieve that the code stmt has access |
|
1882 | # but is there a better way to achieve that the code stmt has access | |
1884 | # to the shell namespace? |
|
1883 | # to the shell namespace? | |
1885 |
|
1884 | |||
1886 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1885 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1887 | 'setup': "pass"} |
|
1886 | 'setup': "pass"} | |
1888 | # Track compilation time so it can be reported if too long |
|
1887 | # Track compilation time so it can be reported if too long | |
1889 | # Minimum time above which compilation time will be reported |
|
1888 | # Minimum time above which compilation time will be reported | |
1890 | tc_min = 0.1 |
|
1889 | tc_min = 0.1 | |
1891 |
|
1890 | |||
1892 | t0 = clock() |
|
1891 | t0 = clock() | |
1893 | code = compile(src, "<magic-timeit>", "exec") |
|
1892 | code = compile(src, "<magic-timeit>", "exec") | |
1894 | tc = clock()-t0 |
|
1893 | tc = clock()-t0 | |
1895 |
|
1894 | |||
1896 | ns = {} |
|
1895 | ns = {} | |
1897 | exec code in self.shell.user_ns, ns |
|
1896 | exec code in self.shell.user_ns, ns | |
1898 | timer.inner = ns["inner"] |
|
1897 | timer.inner = ns["inner"] | |
1899 |
|
1898 | |||
1900 | if number == 0: |
|
1899 | if number == 0: | |
1901 | # determine number so that 0.2 <= total time < 2.0 |
|
1900 | # determine number so that 0.2 <= total time < 2.0 | |
1902 | number = 1 |
|
1901 | number = 1 | |
1903 | for i in range(1, 10): |
|
1902 | for i in range(1, 10): | |
1904 | if timer.timeit(number) >= 0.2: |
|
1903 | if timer.timeit(number) >= 0.2: | |
1905 | break |
|
1904 | break | |
1906 | number *= 10 |
|
1905 | number *= 10 | |
1907 |
|
1906 | |||
1908 | best = min(timer.repeat(repeat, number)) / number |
|
1907 | best = min(timer.repeat(repeat, number)) / number | |
1909 |
|
1908 | |||
1910 | if best > 0.0 and best < 1000.0: |
|
1909 | if best > 0.0 and best < 1000.0: | |
1911 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1910 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1912 | elif best >= 1000.0: |
|
1911 | elif best >= 1000.0: | |
1913 | order = 0 |
|
1912 | order = 0 | |
1914 | else: |
|
1913 | else: | |
1915 | order = 3 |
|
1914 | order = 3 | |
1916 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1915 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1917 | precision, |
|
1916 | precision, | |
1918 | best * scaling[order], |
|
1917 | best * scaling[order], | |
1919 | units[order]) |
|
1918 | units[order]) | |
1920 | if tc > tc_min: |
|
1919 | if tc > tc_min: | |
1921 | print "Compiler time: %.2f s" % tc |
|
1920 | print "Compiler time: %.2f s" % tc | |
1922 |
|
1921 | |||
1923 | @skip_doctest |
|
1922 | @skip_doctest | |
1924 | @needs_local_scope |
|
1923 | @needs_local_scope | |
1925 | def magic_time(self,parameter_s = ''): |
|
1924 | def magic_time(self,parameter_s = ''): | |
1926 | """Time execution of a Python statement or expression. |
|
1925 | """Time execution of a Python statement or expression. | |
1927 |
|
1926 | |||
1928 | The CPU and wall clock times are printed, and the value of the |
|
1927 | The CPU and wall clock times are printed, and the value of the | |
1929 | expression (if any) is returned. Note that under Win32, system time |
|
1928 | expression (if any) is returned. Note that under Win32, system time | |
1930 | is always reported as 0, since it can not be measured. |
|
1929 | is always reported as 0, since it can not be measured. | |
1931 |
|
1930 | |||
1932 | This function provides very basic timing functionality. In Python |
|
1931 | This function provides very basic timing functionality. In Python | |
1933 | 2.3, the timeit module offers more control and sophistication, so this |
|
1932 | 2.3, the timeit module offers more control and sophistication, so this | |
1934 | could be rewritten to use it (patches welcome). |
|
1933 | could be rewritten to use it (patches welcome). | |
1935 |
|
1934 | |||
1936 | Some examples: |
|
1935 | Some examples: | |
1937 |
|
1936 | |||
1938 | In [1]: time 2**128 |
|
1937 | In [1]: time 2**128 | |
1939 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1938 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1940 | Wall time: 0.00 |
|
1939 | Wall time: 0.00 | |
1941 | Out[1]: 340282366920938463463374607431768211456L |
|
1940 | Out[1]: 340282366920938463463374607431768211456L | |
1942 |
|
1941 | |||
1943 | In [2]: n = 1000000 |
|
1942 | In [2]: n = 1000000 | |
1944 |
|
1943 | |||
1945 | In [3]: time sum(range(n)) |
|
1944 | In [3]: time sum(range(n)) | |
1946 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1945 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1947 | Wall time: 1.37 |
|
1946 | Wall time: 1.37 | |
1948 | Out[3]: 499999500000L |
|
1947 | Out[3]: 499999500000L | |
1949 |
|
1948 | |||
1950 | In [4]: time print 'hello world' |
|
1949 | In [4]: time print 'hello world' | |
1951 | hello world |
|
1950 | hello world | |
1952 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1951 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1953 | Wall time: 0.00 |
|
1952 | Wall time: 0.00 | |
1954 |
|
1953 | |||
1955 | Note that the time needed by Python to compile the given expression |
|
1954 | Note that the time needed by Python to compile the given expression | |
1956 | will be reported if it is more than 0.1s. In this example, the |
|
1955 | will be reported if it is more than 0.1s. In this example, the | |
1957 | actual exponentiation is done by Python at compilation time, so while |
|
1956 | actual exponentiation is done by Python at compilation time, so while | |
1958 | the expression can take a noticeable amount of time to compute, that |
|
1957 | the expression can take a noticeable amount of time to compute, that | |
1959 | time is purely due to the compilation: |
|
1958 | time is purely due to the compilation: | |
1960 |
|
1959 | |||
1961 | In [5]: time 3**9999; |
|
1960 | In [5]: time 3**9999; | |
1962 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1961 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1963 | Wall time: 0.00 s |
|
1962 | Wall time: 0.00 s | |
1964 |
|
1963 | |||
1965 | In [6]: time 3**999999; |
|
1964 | In [6]: time 3**999999; | |
1966 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1965 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1967 | Wall time: 0.00 s |
|
1966 | Wall time: 0.00 s | |
1968 | Compiler : 0.78 s |
|
1967 | Compiler : 0.78 s | |
1969 | """ |
|
1968 | """ | |
1970 |
|
1969 | |||
1971 | # fail immediately if the given expression can't be compiled |
|
1970 | # fail immediately if the given expression can't be compiled | |
1972 |
|
1971 | |||
1973 | expr = self.shell.prefilter(parameter_s,False) |
|
1972 | expr = self.shell.prefilter(parameter_s,False) | |
1974 |
|
1973 | |||
1975 | # Minimum time above which compilation time will be reported |
|
1974 | # Minimum time above which compilation time will be reported | |
1976 | tc_min = 0.1 |
|
1975 | tc_min = 0.1 | |
1977 |
|
1976 | |||
1978 | try: |
|
1977 | try: | |
1979 | mode = 'eval' |
|
1978 | mode = 'eval' | |
1980 | t0 = clock() |
|
1979 | t0 = clock() | |
1981 | code = compile(expr,'<timed eval>',mode) |
|
1980 | code = compile(expr,'<timed eval>',mode) | |
1982 | tc = clock()-t0 |
|
1981 | tc = clock()-t0 | |
1983 | except SyntaxError: |
|
1982 | except SyntaxError: | |
1984 | mode = 'exec' |
|
1983 | mode = 'exec' | |
1985 | t0 = clock() |
|
1984 | t0 = clock() | |
1986 | code = compile(expr,'<timed exec>',mode) |
|
1985 | code = compile(expr,'<timed exec>',mode) | |
1987 | tc = clock()-t0 |
|
1986 | tc = clock()-t0 | |
1988 | # skew measurement as little as possible |
|
1987 | # skew measurement as little as possible | |
1989 | glob = self.shell.user_ns |
|
1988 | glob = self.shell.user_ns | |
1990 | locs = self._magic_locals |
|
1989 | locs = self._magic_locals | |
1991 | clk = clock2 |
|
1990 | clk = clock2 | |
1992 | wtime = time.time |
|
1991 | wtime = time.time | |
1993 | # time execution |
|
1992 | # time execution | |
1994 | wall_st = wtime() |
|
1993 | wall_st = wtime() | |
1995 | if mode=='eval': |
|
1994 | if mode=='eval': | |
1996 | st = clk() |
|
1995 | st = clk() | |
1997 | out = eval(code, glob, locs) |
|
1996 | out = eval(code, glob, locs) | |
1998 | end = clk() |
|
1997 | end = clk() | |
1999 | else: |
|
1998 | else: | |
2000 | st = clk() |
|
1999 | st = clk() | |
2001 | exec code in glob, locs |
|
2000 | exec code in glob, locs | |
2002 | end = clk() |
|
2001 | end = clk() | |
2003 | out = None |
|
2002 | out = None | |
2004 | wall_end = wtime() |
|
2003 | wall_end = wtime() | |
2005 | # Compute actual times and report |
|
2004 | # Compute actual times and report | |
2006 | wall_time = wall_end-wall_st |
|
2005 | wall_time = wall_end-wall_st | |
2007 | cpu_user = end[0]-st[0] |
|
2006 | cpu_user = end[0]-st[0] | |
2008 | cpu_sys = end[1]-st[1] |
|
2007 | cpu_sys = end[1]-st[1] | |
2009 | cpu_tot = cpu_user+cpu_sys |
|
2008 | cpu_tot = cpu_user+cpu_sys | |
2010 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
2009 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
2011 | (cpu_user,cpu_sys,cpu_tot) |
|
2010 | (cpu_user,cpu_sys,cpu_tot) | |
2012 | print "Wall time: %.2f s" % wall_time |
|
2011 | print "Wall time: %.2f s" % wall_time | |
2013 | if tc > tc_min: |
|
2012 | if tc > tc_min: | |
2014 | print "Compiler : %.2f s" % tc |
|
2013 | print "Compiler : %.2f s" % tc | |
2015 | return out |
|
2014 | return out | |
2016 |
|
2015 | |||
2017 | @skip_doctest |
|
2016 | @skip_doctest | |
2018 | def magic_macro(self,parameter_s = ''): |
|
2017 | def magic_macro(self,parameter_s = ''): | |
2019 | """Define a macro for future re-execution. It accepts ranges of history, |
|
2018 | """Define a macro for future re-execution. It accepts ranges of history, | |
2020 | filenames or string objects. |
|
2019 | filenames or string objects. | |
2021 |
|
2020 | |||
2022 | Usage:\\ |
|
2021 | Usage:\\ | |
2023 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
2022 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
2024 |
|
2023 | |||
2025 | Options: |
|
2024 | Options: | |
2026 |
|
2025 | |||
2027 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2026 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2028 | so that magics are loaded in their transformed version to valid |
|
2027 | so that magics are loaded in their transformed version to valid | |
2029 | Python. If this option is given, the raw input as typed as the |
|
2028 | Python. If this option is given, the raw input as typed as the | |
2030 | command line is used instead. |
|
2029 | command line is used instead. | |
2031 |
|
2030 | |||
2032 | This will define a global variable called `name` which is a string |
|
2031 | This will define a global variable called `name` which is a string | |
2033 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2032 | made of joining the slices and lines you specify (n1,n2,... numbers | |
2034 | above) from your input history into a single string. This variable |
|
2033 | above) from your input history into a single string. This variable | |
2035 | acts like an automatic function which re-executes those lines as if |
|
2034 | acts like an automatic function which re-executes those lines as if | |
2036 | you had typed them. You just type 'name' at the prompt and the code |
|
2035 | you had typed them. You just type 'name' at the prompt and the code | |
2037 | executes. |
|
2036 | executes. | |
2038 |
|
2037 | |||
2039 | The syntax for indicating input ranges is described in %history. |
|
2038 | The syntax for indicating input ranges is described in %history. | |
2040 |
|
2039 | |||
2041 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2040 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2042 | notation, where N:M means numbers N through M-1. |
|
2041 | notation, where N:M means numbers N through M-1. | |
2043 |
|
2042 | |||
2044 | For example, if your history contains (%hist prints it): |
|
2043 | For example, if your history contains (%hist prints it): | |
2045 |
|
2044 | |||
2046 | 44: x=1 |
|
2045 | 44: x=1 | |
2047 | 45: y=3 |
|
2046 | 45: y=3 | |
2048 | 46: z=x+y |
|
2047 | 46: z=x+y | |
2049 | 47: print x |
|
2048 | 47: print x | |
2050 | 48: a=5 |
|
2049 | 48: a=5 | |
2051 | 49: print 'x',x,'y',y |
|
2050 | 49: print 'x',x,'y',y | |
2052 |
|
2051 | |||
2053 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2052 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2054 | called my_macro with: |
|
2053 | called my_macro with: | |
2055 |
|
2054 | |||
2056 | In [55]: %macro my_macro 44-47 49 |
|
2055 | In [55]: %macro my_macro 44-47 49 | |
2057 |
|
2056 | |||
2058 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2057 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2059 | in one pass. |
|
2058 | in one pass. | |
2060 |
|
2059 | |||
2061 | You don't need to give the line-numbers in order, and any given line |
|
2060 | You don't need to give the line-numbers in order, and any given line | |
2062 | number can appear multiple times. You can assemble macros with any |
|
2061 | number can appear multiple times. You can assemble macros with any | |
2063 | lines from your input history in any order. |
|
2062 | lines from your input history in any order. | |
2064 |
|
2063 | |||
2065 | The macro is a simple object which holds its value in an attribute, |
|
2064 | The macro is a simple object which holds its value in an attribute, | |
2066 | but IPython's display system checks for macros and executes them as |
|
2065 | but IPython's display system checks for macros and executes them as | |
2067 | code instead of printing them when you type their name. |
|
2066 | code instead of printing them when you type their name. | |
2068 |
|
2067 | |||
2069 | You can view a macro's contents by explicitly printing it with: |
|
2068 | You can view a macro's contents by explicitly printing it with: | |
2070 |
|
2069 | |||
2071 | 'print macro_name'. |
|
2070 | 'print macro_name'. | |
2072 |
|
2071 | |||
2073 | """ |
|
2072 | """ | |
2074 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2073 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2075 | if not args: # List existing macros |
|
2074 | if not args: # List existing macros | |
2076 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2075 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
2077 | isinstance(v, Macro)) |
|
2076 | isinstance(v, Macro)) | |
2078 | if len(args) == 1: |
|
2077 | if len(args) == 1: | |
2079 | raise UsageError( |
|
2078 | raise UsageError( | |
2080 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2079 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2081 | name, codefrom = args[0], " ".join(args[1:]) |
|
2080 | name, codefrom = args[0], " ".join(args[1:]) | |
2082 |
|
2081 | |||
2083 | #print 'rng',ranges # dbg |
|
2082 | #print 'rng',ranges # dbg | |
2084 | try: |
|
2083 | try: | |
2085 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2084 | lines = self.shell.find_user_code(codefrom, 'r' in opts) | |
2086 | except (ValueError, TypeError) as e: |
|
2085 | except (ValueError, TypeError) as e: | |
2087 | print e.args[0] |
|
2086 | print e.args[0] | |
2088 | return |
|
2087 | return | |
2089 | macro = Macro(lines) |
|
2088 | macro = Macro(lines) | |
2090 | self.shell.define_macro(name, macro) |
|
2089 | self.shell.define_macro(name, macro) | |
2091 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2090 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2092 | print '=== Macro contents: ===' |
|
2091 | print '=== Macro contents: ===' | |
2093 | print macro, |
|
2092 | print macro, | |
2094 |
|
2093 | |||
2095 | def magic_save(self,parameter_s = ''): |
|
2094 | def magic_save(self,parameter_s = ''): | |
2096 | """Save a set of lines or a macro to a given filename. |
|
2095 | """Save a set of lines or a macro to a given filename. | |
2097 |
|
2096 | |||
2098 | Usage:\\ |
|
2097 | Usage:\\ | |
2099 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2098 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2100 |
|
2099 | |||
2101 | Options: |
|
2100 | Options: | |
2102 |
|
2101 | |||
2103 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2102 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2104 | so that magics are loaded in their transformed version to valid |
|
2103 | so that magics are loaded in their transformed version to valid | |
2105 | Python. If this option is given, the raw input as typed as the |
|
2104 | Python. If this option is given, the raw input as typed as the | |
2106 | command line is used instead. |
|
2105 | command line is used instead. | |
2107 |
|
2106 | |||
2108 | This function uses the same syntax as %history for input ranges, |
|
2107 | This function uses the same syntax as %history for input ranges, | |
2109 | then saves the lines to the filename you specify. |
|
2108 | then saves the lines to the filename you specify. | |
2110 |
|
2109 | |||
2111 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2110 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2112 | it asks for confirmation before overwriting existing files.""" |
|
2111 | it asks for confirmation before overwriting existing files.""" | |
2113 |
|
2112 | |||
2114 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2113 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2115 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) |
|
2114 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) | |
2116 | if not fname.endswith('.py'): |
|
2115 | if not fname.endswith('.py'): | |
2117 | fname += '.py' |
|
2116 | fname += '.py' | |
2118 | if os.path.isfile(fname): |
|
2117 | if os.path.isfile(fname): | |
2119 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2118 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2120 | if ans.lower() not in ['y','yes']: |
|
2119 | if ans.lower() not in ['y','yes']: | |
2121 | print 'Operation cancelled.' |
|
2120 | print 'Operation cancelled.' | |
2122 | return |
|
2121 | return | |
2123 | try: |
|
2122 | try: | |
2124 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2123 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) | |
2125 | except (TypeError, ValueError) as e: |
|
2124 | except (TypeError, ValueError) as e: | |
2126 | print e.args[0] |
|
2125 | print e.args[0] | |
2127 | return |
|
2126 | return | |
2128 | with py3compat.open(fname,'w', encoding="utf-8") as f: |
|
2127 | with py3compat.open(fname,'w', encoding="utf-8") as f: | |
2129 | f.write(u"# coding: utf-8\n") |
|
2128 | f.write(u"# coding: utf-8\n") | |
2130 | f.write(py3compat.cast_unicode(cmds)) |
|
2129 | f.write(py3compat.cast_unicode(cmds)) | |
2131 | print 'The following commands were written to file `%s`:' % fname |
|
2130 | print 'The following commands were written to file `%s`:' % fname | |
2132 | print cmds |
|
2131 | print cmds | |
2133 |
|
2132 | |||
2134 | def magic_pastebin(self, parameter_s = ''): |
|
2133 | def magic_pastebin(self, parameter_s = ''): | |
2135 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" |
|
2134 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" | |
2136 | try: |
|
2135 | try: | |
2137 | code = self.shell.find_user_code(parameter_s) |
|
2136 | code = self.shell.find_user_code(parameter_s) | |
2138 | except (ValueError, TypeError) as e: |
|
2137 | except (ValueError, TypeError) as e: | |
2139 | print e.args[0] |
|
2138 | print e.args[0] | |
2140 | return |
|
2139 | return | |
2141 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') |
|
2140 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') | |
2142 | id = pbserver.pastes.newPaste("python", code) |
|
2141 | id = pbserver.pastes.newPaste("python", code) | |
2143 | return "http://paste.pocoo.org/show/" + id |
|
2142 | return "http://paste.pocoo.org/show/" + id | |
2144 |
|
2143 | |||
2145 | def magic_loadpy(self, arg_s): |
|
2144 | def magic_loadpy(self, arg_s): | |
2146 | """Load a .py python script into the GUI console. |
|
2145 | """Load a .py python script into the GUI console. | |
2147 |
|
2146 | |||
2148 | This magic command can either take a local filename or a url:: |
|
2147 | This magic command can either take a local filename or a url:: | |
2149 |
|
2148 | |||
2150 | %loadpy myscript.py |
|
2149 | %loadpy myscript.py | |
2151 | %loadpy http://www.example.com/myscript.py |
|
2150 | %loadpy http://www.example.com/myscript.py | |
2152 | """ |
|
2151 | """ | |
2153 | arg_s = unquote_filename(arg_s) |
|
2152 | arg_s = unquote_filename(arg_s) | |
2154 | if not arg_s.endswith('.py'): |
|
2153 | if not arg_s.endswith('.py'): | |
2155 | raise ValueError('%%load only works with .py files: %s' % arg_s) |
|
2154 | raise ValueError('%%load only works with .py files: %s' % arg_s) | |
2156 | if arg_s.startswith('http'): |
|
2155 | if arg_s.startswith('http'): | |
2157 | import urllib2 |
|
2156 | import urllib2 | |
2158 | response = urllib2.urlopen(arg_s) |
|
2157 | response = urllib2.urlopen(arg_s) | |
2159 | content = response.read() |
|
2158 | content = response.read() | |
2160 | else: |
|
2159 | else: | |
2161 | with open(arg_s) as f: |
|
2160 | with open(arg_s) as f: | |
2162 | content = f.read() |
|
2161 | content = f.read() | |
2163 | self.set_next_input(content) |
|
2162 | self.set_next_input(content) | |
2164 |
|
2163 | |||
2165 | def _find_edit_target(self, args, opts, last_call): |
|
2164 | def _find_edit_target(self, args, opts, last_call): | |
2166 | """Utility method used by magic_edit to find what to edit.""" |
|
2165 | """Utility method used by magic_edit to find what to edit.""" | |
2167 |
|
2166 | |||
2168 | def make_filename(arg): |
|
2167 | def make_filename(arg): | |
2169 | "Make a filename from the given args" |
|
2168 | "Make a filename from the given args" | |
2170 | arg = unquote_filename(arg) |
|
2169 | arg = unquote_filename(arg) | |
2171 | try: |
|
2170 | try: | |
2172 | filename = get_py_filename(arg) |
|
2171 | filename = get_py_filename(arg) | |
2173 | except IOError: |
|
2172 | except IOError: | |
2174 | # If it ends with .py but doesn't already exist, assume we want |
|
2173 | # If it ends with .py but doesn't already exist, assume we want | |
2175 | # a new file. |
|
2174 | # a new file. | |
2176 | if arg.endswith('.py'): |
|
2175 | if arg.endswith('.py'): | |
2177 | filename = arg |
|
2176 | filename = arg | |
2178 | else: |
|
2177 | else: | |
2179 | filename = None |
|
2178 | filename = None | |
2180 | return filename |
|
2179 | return filename | |
2181 |
|
2180 | |||
2182 | # Set a few locals from the options for convenience: |
|
2181 | # Set a few locals from the options for convenience: | |
2183 | opts_prev = 'p' in opts |
|
2182 | opts_prev = 'p' in opts | |
2184 | opts_raw = 'r' in opts |
|
2183 | opts_raw = 'r' in opts | |
2185 |
|
2184 | |||
2186 | # custom exceptions |
|
2185 | # custom exceptions | |
2187 | class DataIsObject(Exception): pass |
|
2186 | class DataIsObject(Exception): pass | |
2188 |
|
2187 | |||
2189 | # Default line number value |
|
2188 | # Default line number value | |
2190 | lineno = opts.get('n',None) |
|
2189 | lineno = opts.get('n',None) | |
2191 |
|
2190 | |||
2192 | if opts_prev: |
|
2191 | if opts_prev: | |
2193 | args = '_%s' % last_call[0] |
|
2192 | args = '_%s' % last_call[0] | |
2194 | if not self.shell.user_ns.has_key(args): |
|
2193 | if not self.shell.user_ns.has_key(args): | |
2195 | args = last_call[1] |
|
2194 | args = last_call[1] | |
2196 |
|
2195 | |||
2197 | # use last_call to remember the state of the previous call, but don't |
|
2196 | # use last_call to remember the state of the previous call, but don't | |
2198 | # let it be clobbered by successive '-p' calls. |
|
2197 | # let it be clobbered by successive '-p' calls. | |
2199 | try: |
|
2198 | try: | |
2200 | last_call[0] = self.shell.displayhook.prompt_count |
|
2199 | last_call[0] = self.shell.displayhook.prompt_count | |
2201 | if not opts_prev: |
|
2200 | if not opts_prev: | |
2202 | last_call[1] = parameter_s |
|
2201 | last_call[1] = parameter_s | |
2203 | except: |
|
2202 | except: | |
2204 | pass |
|
2203 | pass | |
2205 |
|
2204 | |||
2206 | # by default this is done with temp files, except when the given |
|
2205 | # by default this is done with temp files, except when the given | |
2207 | # arg is a filename |
|
2206 | # arg is a filename | |
2208 | use_temp = True |
|
2207 | use_temp = True | |
2209 |
|
2208 | |||
2210 | data = '' |
|
2209 | data = '' | |
2211 |
|
2210 | |||
2212 | # First, see if the arguments should be a filename. |
|
2211 | # First, see if the arguments should be a filename. | |
2213 | filename = make_filename(args) |
|
2212 | filename = make_filename(args) | |
2214 | if filename: |
|
2213 | if filename: | |
2215 | use_temp = False |
|
2214 | use_temp = False | |
2216 | elif args: |
|
2215 | elif args: | |
2217 | # Mode where user specifies ranges of lines, like in %macro. |
|
2216 | # Mode where user specifies ranges of lines, like in %macro. | |
2218 | data = self.extract_input_lines(args, opts_raw) |
|
2217 | data = self.extract_input_lines(args, opts_raw) | |
2219 | if not data: |
|
2218 | if not data: | |
2220 | try: |
|
2219 | try: | |
2221 | # Load the parameter given as a variable. If not a string, |
|
2220 | # Load the parameter given as a variable. If not a string, | |
2222 | # process it as an object instead (below) |
|
2221 | # process it as an object instead (below) | |
2223 |
|
2222 | |||
2224 | #print '*** args',args,'type',type(args) # dbg |
|
2223 | #print '*** args',args,'type',type(args) # dbg | |
2225 | data = eval(args, self.shell.user_ns) |
|
2224 | data = eval(args, self.shell.user_ns) | |
2226 | if not isinstance(data, basestring): |
|
2225 | if not isinstance(data, basestring): | |
2227 | raise DataIsObject |
|
2226 | raise DataIsObject | |
2228 |
|
2227 | |||
2229 | except (NameError,SyntaxError): |
|
2228 | except (NameError,SyntaxError): | |
2230 | # given argument is not a variable, try as a filename |
|
2229 | # given argument is not a variable, try as a filename | |
2231 | filename = make_filename(args) |
|
2230 | filename = make_filename(args) | |
2232 | if filename is None: |
|
2231 | if filename is None: | |
2233 | warn("Argument given (%s) can't be found as a variable " |
|
2232 | warn("Argument given (%s) can't be found as a variable " | |
2234 | "or as a filename." % args) |
|
2233 | "or as a filename." % args) | |
2235 | return |
|
2234 | return | |
2236 | use_temp = False |
|
2235 | use_temp = False | |
2237 |
|
2236 | |||
2238 | except DataIsObject: |
|
2237 | except DataIsObject: | |
2239 | # macros have a special edit function |
|
2238 | # macros have a special edit function | |
2240 | if isinstance(data, Macro): |
|
2239 | if isinstance(data, Macro): | |
2241 | raise MacroToEdit(data) |
|
2240 | raise MacroToEdit(data) | |
2242 |
|
2241 | |||
2243 | # For objects, try to edit the file where they are defined |
|
2242 | # For objects, try to edit the file where they are defined | |
2244 | try: |
|
2243 | try: | |
2245 | filename = inspect.getabsfile(data) |
|
2244 | filename = inspect.getabsfile(data) | |
2246 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2245 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2247 | # class created by %edit? Try to find source |
|
2246 | # class created by %edit? Try to find source | |
2248 | # by looking for method definitions instead, the |
|
2247 | # by looking for method definitions instead, the | |
2249 | # __module__ in those classes is FakeModule. |
|
2248 | # __module__ in those classes is FakeModule. | |
2250 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2249 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2251 | for attr in attrs: |
|
2250 | for attr in attrs: | |
2252 | if not inspect.ismethod(attr): |
|
2251 | if not inspect.ismethod(attr): | |
2253 | continue |
|
2252 | continue | |
2254 | filename = inspect.getabsfile(attr) |
|
2253 | filename = inspect.getabsfile(attr) | |
2255 | if filename and 'fakemodule' not in filename.lower(): |
|
2254 | if filename and 'fakemodule' not in filename.lower(): | |
2256 | # change the attribute to be the edit target instead |
|
2255 | # change the attribute to be the edit target instead | |
2257 | data = attr |
|
2256 | data = attr | |
2258 | break |
|
2257 | break | |
2259 |
|
2258 | |||
2260 | datafile = 1 |
|
2259 | datafile = 1 | |
2261 | except TypeError: |
|
2260 | except TypeError: | |
2262 | filename = make_filename(args) |
|
2261 | filename = make_filename(args) | |
2263 | datafile = 1 |
|
2262 | datafile = 1 | |
2264 | warn('Could not find file where `%s` is defined.\n' |
|
2263 | warn('Could not find file where `%s` is defined.\n' | |
2265 | 'Opening a file named `%s`' % (args,filename)) |
|
2264 | 'Opening a file named `%s`' % (args,filename)) | |
2266 | # Now, make sure we can actually read the source (if it was in |
|
2265 | # Now, make sure we can actually read the source (if it was in | |
2267 | # a temp file it's gone by now). |
|
2266 | # a temp file it's gone by now). | |
2268 | if datafile: |
|
2267 | if datafile: | |
2269 | try: |
|
2268 | try: | |
2270 | if lineno is None: |
|
2269 | if lineno is None: | |
2271 | lineno = inspect.getsourcelines(data)[1] |
|
2270 | lineno = inspect.getsourcelines(data)[1] | |
2272 | except IOError: |
|
2271 | except IOError: | |
2273 | filename = make_filename(args) |
|
2272 | filename = make_filename(args) | |
2274 | if filename is None: |
|
2273 | if filename is None: | |
2275 | warn('The file `%s` where `%s` was defined cannot ' |
|
2274 | warn('The file `%s` where `%s` was defined cannot ' | |
2276 | 'be read.' % (filename,data)) |
|
2275 | 'be read.' % (filename,data)) | |
2277 | return |
|
2276 | return | |
2278 | use_temp = False |
|
2277 | use_temp = False | |
2279 |
|
2278 | |||
2280 | if use_temp: |
|
2279 | if use_temp: | |
2281 | filename = self.shell.mktempfile(data) |
|
2280 | filename = self.shell.mktempfile(data) | |
2282 | print 'IPython will make a temporary file named:',filename |
|
2281 | print 'IPython will make a temporary file named:',filename | |
2283 |
|
2282 | |||
2284 | return filename, lineno, use_temp |
|
2283 | return filename, lineno, use_temp | |
2285 |
|
2284 | |||
2286 | def _edit_macro(self,mname,macro): |
|
2285 | def _edit_macro(self,mname,macro): | |
2287 | """open an editor with the macro data in a file""" |
|
2286 | """open an editor with the macro data in a file""" | |
2288 | filename = self.shell.mktempfile(macro.value) |
|
2287 | filename = self.shell.mktempfile(macro.value) | |
2289 | self.shell.hooks.editor(filename) |
|
2288 | self.shell.hooks.editor(filename) | |
2290 |
|
2289 | |||
2291 | # and make a new macro object, to replace the old one |
|
2290 | # and make a new macro object, to replace the old one | |
2292 | mfile = open(filename) |
|
2291 | mfile = open(filename) | |
2293 | mvalue = mfile.read() |
|
2292 | mvalue = mfile.read() | |
2294 | mfile.close() |
|
2293 | mfile.close() | |
2295 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2294 | self.shell.user_ns[mname] = Macro(mvalue) | |
2296 |
|
2295 | |||
2297 | def magic_ed(self,parameter_s=''): |
|
2296 | def magic_ed(self,parameter_s=''): | |
2298 | """Alias to %edit.""" |
|
2297 | """Alias to %edit.""" | |
2299 | return self.magic_edit(parameter_s) |
|
2298 | return self.magic_edit(parameter_s) | |
2300 |
|
2299 | |||
2301 | @skip_doctest |
|
2300 | @skip_doctest | |
2302 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2301 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2303 | """Bring up an editor and execute the resulting code. |
|
2302 | """Bring up an editor and execute the resulting code. | |
2304 |
|
2303 | |||
2305 | Usage: |
|
2304 | Usage: | |
2306 | %edit [options] [args] |
|
2305 | %edit [options] [args] | |
2307 |
|
2306 | |||
2308 | %edit runs IPython's editor hook. The default version of this hook is |
|
2307 | %edit runs IPython's editor hook. The default version of this hook is | |
2309 | set to call the editor specified by your $EDITOR environment variable. |
|
2308 | set to call the editor specified by your $EDITOR environment variable. | |
2310 | If this isn't found, it will default to vi under Linux/Unix and to |
|
2309 | If this isn't found, it will default to vi under Linux/Unix and to | |
2311 | notepad under Windows. See the end of this docstring for how to change |
|
2310 | notepad under Windows. See the end of this docstring for how to change | |
2312 | the editor hook. |
|
2311 | the editor hook. | |
2313 |
|
2312 | |||
2314 | You can also set the value of this editor via the |
|
2313 | You can also set the value of this editor via the | |
2315 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
2314 | ``TerminalInteractiveShell.editor`` option in your configuration file. | |
2316 | This is useful if you wish to use a different editor from your typical |
|
2315 | This is useful if you wish to use a different editor from your typical | |
2317 | default with IPython (and for Windows users who typically don't set |
|
2316 | default with IPython (and for Windows users who typically don't set | |
2318 | environment variables). |
|
2317 | environment variables). | |
2319 |
|
2318 | |||
2320 | This command allows you to conveniently edit multi-line code right in |
|
2319 | This command allows you to conveniently edit multi-line code right in | |
2321 | your IPython session. |
|
2320 | your IPython session. | |
2322 |
|
2321 | |||
2323 | If called without arguments, %edit opens up an empty editor with a |
|
2322 | If called without arguments, %edit opens up an empty editor with a | |
2324 | temporary file and will execute the contents of this file when you |
|
2323 | temporary file and will execute the contents of this file when you | |
2325 | close it (don't forget to save it!). |
|
2324 | close it (don't forget to save it!). | |
2326 |
|
2325 | |||
2327 |
|
2326 | |||
2328 | Options: |
|
2327 | Options: | |
2329 |
|
2328 | |||
2330 | -n <number>: open the editor at a specified line number. By default, |
|
2329 | -n <number>: open the editor at a specified line number. By default, | |
2331 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2330 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2332 | you can configure this by providing your own modified hook if your |
|
2331 | you can configure this by providing your own modified hook if your | |
2333 | favorite editor supports line-number specifications with a different |
|
2332 | favorite editor supports line-number specifications with a different | |
2334 | syntax. |
|
2333 | syntax. | |
2335 |
|
2334 | |||
2336 | -p: this will call the editor with the same data as the previous time |
|
2335 | -p: this will call the editor with the same data as the previous time | |
2337 | it was used, regardless of how long ago (in your current session) it |
|
2336 | it was used, regardless of how long ago (in your current session) it | |
2338 | was. |
|
2337 | was. | |
2339 |
|
2338 | |||
2340 | -r: use 'raw' input. This option only applies to input taken from the |
|
2339 | -r: use 'raw' input. This option only applies to input taken from the | |
2341 | user's history. By default, the 'processed' history is used, so that |
|
2340 | user's history. By default, the 'processed' history is used, so that | |
2342 | magics are loaded in their transformed version to valid Python. If |
|
2341 | magics are loaded in their transformed version to valid Python. If | |
2343 | this option is given, the raw input as typed as the command line is |
|
2342 | this option is given, the raw input as typed as the command line is | |
2344 | used instead. When you exit the editor, it will be executed by |
|
2343 | used instead. When you exit the editor, it will be executed by | |
2345 | IPython's own processor. |
|
2344 | IPython's own processor. | |
2346 |
|
2345 | |||
2347 | -x: do not execute the edited code immediately upon exit. This is |
|
2346 | -x: do not execute the edited code immediately upon exit. This is | |
2348 | mainly useful if you are editing programs which need to be called with |
|
2347 | mainly useful if you are editing programs which need to be called with | |
2349 | command line arguments, which you can then do using %run. |
|
2348 | command line arguments, which you can then do using %run. | |
2350 |
|
2349 | |||
2351 |
|
2350 | |||
2352 | Arguments: |
|
2351 | Arguments: | |
2353 |
|
2352 | |||
2354 | If arguments are given, the following possibilites exist: |
|
2353 | If arguments are given, the following possibilites exist: | |
2355 |
|
2354 | |||
2356 | - If the argument is a filename, IPython will load that into the |
|
2355 | - If the argument is a filename, IPython will load that into the | |
2357 | editor. It will execute its contents with execfile() when you exit, |
|
2356 | editor. It will execute its contents with execfile() when you exit, | |
2358 | loading any code in the file into your interactive namespace. |
|
2357 | loading any code in the file into your interactive namespace. | |
2359 |
|
2358 | |||
2360 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
2359 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
2361 | The syntax is the same as in the %history magic. |
|
2360 | The syntax is the same as in the %history magic. | |
2362 |
|
2361 | |||
2363 | - If the argument is a string variable, its contents are loaded |
|
2362 | - If the argument is a string variable, its contents are loaded | |
2364 | into the editor. You can thus edit any string which contains |
|
2363 | into the editor. You can thus edit any string which contains | |
2365 | python code (including the result of previous edits). |
|
2364 | python code (including the result of previous edits). | |
2366 |
|
2365 | |||
2367 | - If the argument is the name of an object (other than a string), |
|
2366 | - If the argument is the name of an object (other than a string), | |
2368 | IPython will try to locate the file where it was defined and open the |
|
2367 | IPython will try to locate the file where it was defined and open the | |
2369 | editor at the point where it is defined. You can use `%edit function` |
|
2368 | editor at the point where it is defined. You can use `%edit function` | |
2370 | to load an editor exactly at the point where 'function' is defined, |
|
2369 | to load an editor exactly at the point where 'function' is defined, | |
2371 | edit it and have the file be executed automatically. |
|
2370 | edit it and have the file be executed automatically. | |
2372 |
|
2371 | |||
2373 | - If the object is a macro (see %macro for details), this opens up your |
|
2372 | - If the object is a macro (see %macro for details), this opens up your | |
2374 | specified editor with a temporary file containing the macro's data. |
|
2373 | specified editor with a temporary file containing the macro's data. | |
2375 | Upon exit, the macro is reloaded with the contents of the file. |
|
2374 | Upon exit, the macro is reloaded with the contents of the file. | |
2376 |
|
2375 | |||
2377 | Note: opening at an exact line is only supported under Unix, and some |
|
2376 | Note: opening at an exact line is only supported under Unix, and some | |
2378 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2377 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2379 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2378 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2380 | (X)Emacs, vi, jed, pico and joe all do. |
|
2379 | (X)Emacs, vi, jed, pico and joe all do. | |
2381 |
|
2380 | |||
2382 | After executing your code, %edit will return as output the code you |
|
2381 | After executing your code, %edit will return as output the code you | |
2383 | typed in the editor (except when it was an existing file). This way |
|
2382 | typed in the editor (except when it was an existing file). This way | |
2384 | you can reload the code in further invocations of %edit as a variable, |
|
2383 | you can reload the code in further invocations of %edit as a variable, | |
2385 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2384 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2386 | the output. |
|
2385 | the output. | |
2387 |
|
2386 | |||
2388 | Note that %edit is also available through the alias %ed. |
|
2387 | Note that %edit is also available through the alias %ed. | |
2389 |
|
2388 | |||
2390 | This is an example of creating a simple function inside the editor and |
|
2389 | This is an example of creating a simple function inside the editor and | |
2391 | then modifying it. First, start up the editor: |
|
2390 | then modifying it. First, start up the editor: | |
2392 |
|
2391 | |||
2393 | In [1]: ed |
|
2392 | In [1]: ed | |
2394 | Editing... done. Executing edited code... |
|
2393 | Editing... done. Executing edited code... | |
2395 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2394 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2396 |
|
2395 | |||
2397 | We can then call the function foo(): |
|
2396 | We can then call the function foo(): | |
2398 |
|
2397 | |||
2399 | In [2]: foo() |
|
2398 | In [2]: foo() | |
2400 | foo() was defined in an editing session |
|
2399 | foo() was defined in an editing session | |
2401 |
|
2400 | |||
2402 | Now we edit foo. IPython automatically loads the editor with the |
|
2401 | Now we edit foo. IPython automatically loads the editor with the | |
2403 | (temporary) file where foo() was previously defined: |
|
2402 | (temporary) file where foo() was previously defined: | |
2404 |
|
2403 | |||
2405 | In [3]: ed foo |
|
2404 | In [3]: ed foo | |
2406 | Editing... done. Executing edited code... |
|
2405 | Editing... done. Executing edited code... | |
2407 |
|
2406 | |||
2408 | And if we call foo() again we get the modified version: |
|
2407 | And if we call foo() again we get the modified version: | |
2409 |
|
2408 | |||
2410 | In [4]: foo() |
|
2409 | In [4]: foo() | |
2411 | foo() has now been changed! |
|
2410 | foo() has now been changed! | |
2412 |
|
2411 | |||
2413 | Here is an example of how to edit a code snippet successive |
|
2412 | Here is an example of how to edit a code snippet successive | |
2414 | times. First we call the editor: |
|
2413 | times. First we call the editor: | |
2415 |
|
2414 | |||
2416 | In [5]: ed |
|
2415 | In [5]: ed | |
2417 | Editing... done. Executing edited code... |
|
2416 | Editing... done. Executing edited code... | |
2418 | hello |
|
2417 | hello | |
2419 | Out[5]: "print 'hello'n" |
|
2418 | Out[5]: "print 'hello'n" | |
2420 |
|
2419 | |||
2421 | Now we call it again with the previous output (stored in _): |
|
2420 | Now we call it again with the previous output (stored in _): | |
2422 |
|
2421 | |||
2423 | In [6]: ed _ |
|
2422 | In [6]: ed _ | |
2424 | Editing... done. Executing edited code... |
|
2423 | Editing... done. Executing edited code... | |
2425 | hello world |
|
2424 | hello world | |
2426 | Out[6]: "print 'hello world'n" |
|
2425 | Out[6]: "print 'hello world'n" | |
2427 |
|
2426 | |||
2428 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2427 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2429 |
|
2428 | |||
2430 | In [7]: ed _8 |
|
2429 | In [7]: ed _8 | |
2431 | Editing... done. Executing edited code... |
|
2430 | Editing... done. Executing edited code... | |
2432 | hello again |
|
2431 | hello again | |
2433 | Out[7]: "print 'hello again'n" |
|
2432 | Out[7]: "print 'hello again'n" | |
2434 |
|
2433 | |||
2435 |
|
2434 | |||
2436 | Changing the default editor hook: |
|
2435 | Changing the default editor hook: | |
2437 |
|
2436 | |||
2438 | If you wish to write your own editor hook, you can put it in a |
|
2437 | If you wish to write your own editor hook, you can put it in a | |
2439 | configuration file which you load at startup time. The default hook |
|
2438 | configuration file which you load at startup time. The default hook | |
2440 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2439 | is defined in the IPython.core.hooks module, and you can use that as a | |
2441 | starting example for further modifications. That file also has |
|
2440 | starting example for further modifications. That file also has | |
2442 | general instructions on how to set a new hook for use once you've |
|
2441 | general instructions on how to set a new hook for use once you've | |
2443 | defined it.""" |
|
2442 | defined it.""" | |
2444 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2443 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2445 |
|
2444 | |||
2446 | try: |
|
2445 | try: | |
2447 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) |
|
2446 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) | |
2448 | except MacroToEdit as e: |
|
2447 | except MacroToEdit as e: | |
2449 | self._edit_macro(args, e.args[0]) |
|
2448 | self._edit_macro(args, e.args[0]) | |
2450 | return |
|
2449 | return | |
2451 |
|
2450 | |||
2452 | # do actual editing here |
|
2451 | # do actual editing here | |
2453 | print 'Editing...', |
|
2452 | print 'Editing...', | |
2454 | sys.stdout.flush() |
|
2453 | sys.stdout.flush() | |
2455 | try: |
|
2454 | try: | |
2456 | # Quote filenames that may have spaces in them |
|
2455 | # Quote filenames that may have spaces in them | |
2457 | if ' ' in filename: |
|
2456 | if ' ' in filename: | |
2458 | filename = "'%s'" % filename |
|
2457 | filename = "'%s'" % filename | |
2459 | self.shell.hooks.editor(filename,lineno) |
|
2458 | self.shell.hooks.editor(filename,lineno) | |
2460 | except TryNext: |
|
2459 | except TryNext: | |
2461 | warn('Could not open editor') |
|
2460 | warn('Could not open editor') | |
2462 | return |
|
2461 | return | |
2463 |
|
2462 | |||
2464 | # XXX TODO: should this be generalized for all string vars? |
|
2463 | # XXX TODO: should this be generalized for all string vars? | |
2465 | # For now, this is special-cased to blocks created by cpaste |
|
2464 | # For now, this is special-cased to blocks created by cpaste | |
2466 | if args.strip() == 'pasted_block': |
|
2465 | if args.strip() == 'pasted_block': | |
2467 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2466 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2468 |
|
2467 | |||
2469 | if 'x' in opts: # -x prevents actual execution |
|
2468 | if 'x' in opts: # -x prevents actual execution | |
2470 |
|
2469 | |||
2471 | else: |
|
2470 | else: | |
2472 | print 'done. Executing edited code...' |
|
2471 | print 'done. Executing edited code...' | |
2473 | if 'r' in opts: # Untranslated IPython code |
|
2472 | if 'r' in opts: # Untranslated IPython code | |
2474 | self.shell.run_cell(file_read(filename), |
|
2473 | self.shell.run_cell(file_read(filename), | |
2475 | store_history=False) |
|
2474 | store_history=False) | |
2476 | else: |
|
2475 | else: | |
2477 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2476 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2478 | self.shell.user_ns) |
|
2477 | self.shell.user_ns) | |
2479 |
|
2478 | |||
2480 | if is_temp: |
|
2479 | if is_temp: | |
2481 | try: |
|
2480 | try: | |
2482 | return open(filename).read() |
|
2481 | return open(filename).read() | |
2483 | except IOError,msg: |
|
2482 | except IOError,msg: | |
2484 | if msg.filename == filename: |
|
2483 | if msg.filename == filename: | |
2485 | warn('File not found. Did you forget to save?') |
|
2484 | warn('File not found. Did you forget to save?') | |
2486 | return |
|
2485 | return | |
2487 | else: |
|
2486 | else: | |
2488 | self.shell.showtraceback() |
|
2487 | self.shell.showtraceback() | |
2489 |
|
2488 | |||
2490 | def magic_xmode(self,parameter_s = ''): |
|
2489 | def magic_xmode(self,parameter_s = ''): | |
2491 | """Switch modes for the exception handlers. |
|
2490 | """Switch modes for the exception handlers. | |
2492 |
|
2491 | |||
2493 | Valid modes: Plain, Context and Verbose. |
|
2492 | Valid modes: Plain, Context and Verbose. | |
2494 |
|
2493 | |||
2495 | If called without arguments, acts as a toggle.""" |
|
2494 | If called without arguments, acts as a toggle.""" | |
2496 |
|
2495 | |||
2497 | def xmode_switch_err(name): |
|
2496 | def xmode_switch_err(name): | |
2498 | warn('Error changing %s exception modes.\n%s' % |
|
2497 | warn('Error changing %s exception modes.\n%s' % | |
2499 | (name,sys.exc_info()[1])) |
|
2498 | (name,sys.exc_info()[1])) | |
2500 |
|
2499 | |||
2501 | shell = self.shell |
|
2500 | shell = self.shell | |
2502 | new_mode = parameter_s.strip().capitalize() |
|
2501 | new_mode = parameter_s.strip().capitalize() | |
2503 | try: |
|
2502 | try: | |
2504 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2503 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2505 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2504 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2506 | except: |
|
2505 | except: | |
2507 | xmode_switch_err('user') |
|
2506 | xmode_switch_err('user') | |
2508 |
|
2507 | |||
2509 | def magic_colors(self,parameter_s = ''): |
|
2508 | def magic_colors(self,parameter_s = ''): | |
2510 | """Switch color scheme for prompts, info system and exception handlers. |
|
2509 | """Switch color scheme for prompts, info system and exception handlers. | |
2511 |
|
2510 | |||
2512 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2511 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2513 |
|
2512 | |||
2514 | Color scheme names are not case-sensitive. |
|
2513 | Color scheme names are not case-sensitive. | |
2515 |
|
2514 | |||
2516 | Examples |
|
2515 | Examples | |
2517 | -------- |
|
2516 | -------- | |
2518 | To get a plain black and white terminal:: |
|
2517 | To get a plain black and white terminal:: | |
2519 |
|
2518 | |||
2520 | %colors nocolor |
|
2519 | %colors nocolor | |
2521 | """ |
|
2520 | """ | |
2522 |
|
2521 | |||
2523 | def color_switch_err(name): |
|
2522 | def color_switch_err(name): | |
2524 | warn('Error changing %s color schemes.\n%s' % |
|
2523 | warn('Error changing %s color schemes.\n%s' % | |
2525 | (name,sys.exc_info()[1])) |
|
2524 | (name,sys.exc_info()[1])) | |
2526 |
|
2525 | |||
2527 |
|
2526 | |||
2528 | new_scheme = parameter_s.strip() |
|
2527 | new_scheme = parameter_s.strip() | |
2529 | if not new_scheme: |
|
2528 | if not new_scheme: | |
2530 | raise UsageError( |
|
2529 | raise UsageError( | |
2531 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2530 | "%colors: you must specify a color scheme. See '%colors?'") | |
2532 | return |
|
2531 | return | |
2533 | # local shortcut |
|
2532 | # local shortcut | |
2534 | shell = self.shell |
|
2533 | shell = self.shell | |
2535 |
|
2534 | |||
2536 | import IPython.utils.rlineimpl as readline |
|
2535 | import IPython.utils.rlineimpl as readline | |
2537 |
|
2536 | |||
2538 | if not shell.colors_force and \ |
|
2537 | if not shell.colors_force and \ | |
2539 | not readline.have_readline and sys.platform == "win32": |
|
2538 | not readline.have_readline and sys.platform == "win32": | |
2540 | msg = """\ |
|
2539 | msg = """\ | |
2541 | Proper color support under MS Windows requires the pyreadline library. |
|
2540 | Proper color support under MS Windows requires the pyreadline library. | |
2542 | You can find it at: |
|
2541 | You can find it at: | |
2543 | http://ipython.org/pyreadline.html |
|
2542 | http://ipython.org/pyreadline.html | |
2544 | Gary's readline needs the ctypes module, from: |
|
2543 | Gary's readline needs the ctypes module, from: | |
2545 | http://starship.python.net/crew/theller/ctypes |
|
2544 | http://starship.python.net/crew/theller/ctypes | |
2546 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2545 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2547 |
|
2546 | |||
2548 | Defaulting color scheme to 'NoColor'""" |
|
2547 | Defaulting color scheme to 'NoColor'""" | |
2549 | new_scheme = 'NoColor' |
|
2548 | new_scheme = 'NoColor' | |
2550 | warn(msg) |
|
2549 | warn(msg) | |
2551 |
|
2550 | |||
2552 | # readline option is 0 |
|
2551 | # readline option is 0 | |
2553 | if not shell.colors_force and not shell.has_readline: |
|
2552 | if not shell.colors_force and not shell.has_readline: | |
2554 | new_scheme = 'NoColor' |
|
2553 | new_scheme = 'NoColor' | |
2555 |
|
2554 | |||
2556 | # Set prompt colors |
|
2555 | # Set prompt colors | |
2557 | try: |
|
2556 | try: | |
2558 | shell.displayhook.set_colors(new_scheme) |
|
2557 | shell.displayhook.set_colors(new_scheme) | |
2559 | except: |
|
2558 | except: | |
2560 | color_switch_err('prompt') |
|
2559 | color_switch_err('prompt') | |
2561 | else: |
|
2560 | else: | |
2562 | shell.colors = \ |
|
2561 | shell.colors = \ | |
2563 | shell.displayhook.color_table.active_scheme_name |
|
2562 | shell.displayhook.color_table.active_scheme_name | |
2564 | # Set exception colors |
|
2563 | # Set exception colors | |
2565 | try: |
|
2564 | try: | |
2566 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2565 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2567 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2566 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2568 | except: |
|
2567 | except: | |
2569 | color_switch_err('exception') |
|
2568 | color_switch_err('exception') | |
2570 |
|
2569 | |||
2571 | # Set info (for 'object?') colors |
|
2570 | # Set info (for 'object?') colors | |
2572 | if shell.color_info: |
|
2571 | if shell.color_info: | |
2573 | try: |
|
2572 | try: | |
2574 | shell.inspector.set_active_scheme(new_scheme) |
|
2573 | shell.inspector.set_active_scheme(new_scheme) | |
2575 | except: |
|
2574 | except: | |
2576 | color_switch_err('object inspector') |
|
2575 | color_switch_err('object inspector') | |
2577 | else: |
|
2576 | else: | |
2578 | shell.inspector.set_active_scheme('NoColor') |
|
2577 | shell.inspector.set_active_scheme('NoColor') | |
2579 |
|
2578 | |||
2580 | def magic_pprint(self, parameter_s=''): |
|
2579 | def magic_pprint(self, parameter_s=''): | |
2581 | """Toggle pretty printing on/off.""" |
|
2580 | """Toggle pretty printing on/off.""" | |
2582 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2581 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
2583 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2582 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2584 | print 'Pretty printing has been turned', \ |
|
2583 | print 'Pretty printing has been turned', \ | |
2585 | ['OFF','ON'][ptformatter.pprint] |
|
2584 | ['OFF','ON'][ptformatter.pprint] | |
2586 |
|
2585 | |||
2587 | #...................................................................... |
|
2586 | #...................................................................... | |
2588 | # Functions to implement unix shell-type things |
|
2587 | # Functions to implement unix shell-type things | |
2589 |
|
2588 | |||
2590 | @skip_doctest |
|
2589 | @skip_doctest | |
2591 | def magic_alias(self, parameter_s = ''): |
|
2590 | def magic_alias(self, parameter_s = ''): | |
2592 | """Define an alias for a system command. |
|
2591 | """Define an alias for a system command. | |
2593 |
|
2592 | |||
2594 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2593 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2595 |
|
2594 | |||
2596 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2595 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2597 | params' (from your underlying operating system). |
|
2596 | params' (from your underlying operating system). | |
2598 |
|
2597 | |||
2599 | Aliases have lower precedence than magic functions and Python normal |
|
2598 | Aliases have lower precedence than magic functions and Python normal | |
2600 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2599 | variables, so if 'foo' is both a Python variable and an alias, the | |
2601 | alias can not be executed until 'del foo' removes the Python variable. |
|
2600 | alias can not be executed until 'del foo' removes the Python variable. | |
2602 |
|
2601 | |||
2603 | You can use the %l specifier in an alias definition to represent the |
|
2602 | You can use the %l specifier in an alias definition to represent the | |
2604 | whole line when the alias is called. For example: |
|
2603 | whole line when the alias is called. For example: | |
2605 |
|
2604 | |||
2606 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2605 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2607 | In [3]: bracket hello world |
|
2606 | In [3]: bracket hello world | |
2608 | Input in brackets: <hello world> |
|
2607 | Input in brackets: <hello world> | |
2609 |
|
2608 | |||
2610 | You can also define aliases with parameters using %s specifiers (one |
|
2609 | You can also define aliases with parameters using %s specifiers (one | |
2611 | per parameter): |
|
2610 | per parameter): | |
2612 |
|
2611 | |||
2613 | In [1]: alias parts echo first %s second %s |
|
2612 | In [1]: alias parts echo first %s second %s | |
2614 | In [2]: %parts A B |
|
2613 | In [2]: %parts A B | |
2615 | first A second B |
|
2614 | first A second B | |
2616 | In [3]: %parts A |
|
2615 | In [3]: %parts A | |
2617 | Incorrect number of arguments: 2 expected. |
|
2616 | Incorrect number of arguments: 2 expected. | |
2618 | parts is an alias to: 'echo first %s second %s' |
|
2617 | parts is an alias to: 'echo first %s second %s' | |
2619 |
|
2618 | |||
2620 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2619 | Note that %l and %s are mutually exclusive. You can only use one or | |
2621 | the other in your aliases. |
|
2620 | the other in your aliases. | |
2622 |
|
2621 | |||
2623 | Aliases expand Python variables just like system calls using ! or !! |
|
2622 | Aliases expand Python variables just like system calls using ! or !! | |
2624 | do: all expressions prefixed with '$' get expanded. For details of |
|
2623 | do: all expressions prefixed with '$' get expanded. For details of | |
2625 | the semantic rules, see PEP-215: |
|
2624 | the semantic rules, see PEP-215: | |
2626 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2625 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2627 | IPython for variable expansion. If you want to access a true shell |
|
2626 | IPython for variable expansion. If you want to access a true shell | |
2628 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2627 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2629 |
|
2628 | |||
2630 | In [6]: alias show echo |
|
2629 | In [6]: alias show echo | |
2631 | In [7]: PATH='A Python string' |
|
2630 | In [7]: PATH='A Python string' | |
2632 | In [8]: show $PATH |
|
2631 | In [8]: show $PATH | |
2633 | A Python string |
|
2632 | A Python string | |
2634 | In [9]: show $$PATH |
|
2633 | In [9]: show $$PATH | |
2635 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2634 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2636 |
|
2635 | |||
2637 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2636 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2638 | and %rehashx functions, which automatically create aliases for the |
|
2637 | and %rehashx functions, which automatically create aliases for the | |
2639 | contents of your $PATH. |
|
2638 | contents of your $PATH. | |
2640 |
|
2639 | |||
2641 | If called with no parameters, %alias prints the current alias table.""" |
|
2640 | If called with no parameters, %alias prints the current alias table.""" | |
2642 |
|
2641 | |||
2643 | par = parameter_s.strip() |
|
2642 | par = parameter_s.strip() | |
2644 | if not par: |
|
2643 | if not par: | |
2645 | stored = self.db.get('stored_aliases', {} ) |
|
2644 | stored = self.db.get('stored_aliases', {} ) | |
2646 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2645 | aliases = sorted(self.shell.alias_manager.aliases) | |
2647 | # for k, v in stored: |
|
2646 | # for k, v in stored: | |
2648 | # atab.append(k, v[0]) |
|
2647 | # atab.append(k, v[0]) | |
2649 |
|
2648 | |||
2650 | print "Total number of aliases:", len(aliases) |
|
2649 | print "Total number of aliases:", len(aliases) | |
2651 | sys.stdout.flush() |
|
2650 | sys.stdout.flush() | |
2652 | return aliases |
|
2651 | return aliases | |
2653 |
|
2652 | |||
2654 | # Now try to define a new one |
|
2653 | # Now try to define a new one | |
2655 | try: |
|
2654 | try: | |
2656 | alias,cmd = par.split(None, 1) |
|
2655 | alias,cmd = par.split(None, 1) | |
2657 | except: |
|
2656 | except: | |
2658 | print oinspect.getdoc(self.magic_alias) |
|
2657 | print oinspect.getdoc(self.magic_alias) | |
2659 | else: |
|
2658 | else: | |
2660 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2659 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2661 | # end magic_alias |
|
2660 | # end magic_alias | |
2662 |
|
2661 | |||
2663 | def magic_unalias(self, parameter_s = ''): |
|
2662 | def magic_unalias(self, parameter_s = ''): | |
2664 | """Remove an alias""" |
|
2663 | """Remove an alias""" | |
2665 |
|
2664 | |||
2666 | aname = parameter_s.strip() |
|
2665 | aname = parameter_s.strip() | |
2667 | self.shell.alias_manager.undefine_alias(aname) |
|
2666 | self.shell.alias_manager.undefine_alias(aname) | |
2668 | stored = self.db.get('stored_aliases', {} ) |
|
2667 | stored = self.db.get('stored_aliases', {} ) | |
2669 | if aname in stored: |
|
2668 | if aname in stored: | |
2670 | print "Removing %stored alias",aname |
|
2669 | print "Removing %stored alias",aname | |
2671 | del stored[aname] |
|
2670 | del stored[aname] | |
2672 | self.db['stored_aliases'] = stored |
|
2671 | self.db['stored_aliases'] = stored | |
2673 |
|
2672 | |||
2674 | def magic_rehashx(self, parameter_s = ''): |
|
2673 | def magic_rehashx(self, parameter_s = ''): | |
2675 | """Update the alias table with all executable files in $PATH. |
|
2674 | """Update the alias table with all executable files in $PATH. | |
2676 |
|
2675 | |||
2677 | This version explicitly checks that every entry in $PATH is a file |
|
2676 | This version explicitly checks that every entry in $PATH is a file | |
2678 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2677 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2679 |
|
2678 | |||
2680 | Under Windows, it checks executability as a match agains a |
|
2679 | Under Windows, it checks executability as a match agains a | |
2681 | '|'-separated string of extensions, stored in the IPython config |
|
2680 | '|'-separated string of extensions, stored in the IPython config | |
2682 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2681 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2683 |
|
2682 | |||
2684 | This function also resets the root module cache of module completer, |
|
2683 | This function also resets the root module cache of module completer, | |
2685 | used on slow filesystems. |
|
2684 | used on slow filesystems. | |
2686 | """ |
|
2685 | """ | |
2687 | from IPython.core.alias import InvalidAliasError |
|
2686 | from IPython.core.alias import InvalidAliasError | |
2688 |
|
2687 | |||
2689 | # for the benefit of module completer in ipy_completers.py |
|
2688 | # for the benefit of module completer in ipy_completers.py | |
2690 | del self.shell.db['rootmodules'] |
|
2689 | del self.shell.db['rootmodules'] | |
2691 |
|
2690 | |||
2692 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2691 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2693 | os.environ.get('PATH','').split(os.pathsep)] |
|
2692 | os.environ.get('PATH','').split(os.pathsep)] | |
2694 | path = filter(os.path.isdir,path) |
|
2693 | path = filter(os.path.isdir,path) | |
2695 |
|
2694 | |||
2696 | syscmdlist = [] |
|
2695 | syscmdlist = [] | |
2697 | # Now define isexec in a cross platform manner. |
|
2696 | # Now define isexec in a cross platform manner. | |
2698 | if os.name == 'posix': |
|
2697 | if os.name == 'posix': | |
2699 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2698 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2700 | os.access(fname,os.X_OK) |
|
2699 | os.access(fname,os.X_OK) | |
2701 | else: |
|
2700 | else: | |
2702 | try: |
|
2701 | try: | |
2703 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2702 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2704 | except KeyError: |
|
2703 | except KeyError: | |
2705 | winext = 'exe|com|bat|py' |
|
2704 | winext = 'exe|com|bat|py' | |
2706 | if 'py' not in winext: |
|
2705 | if 'py' not in winext: | |
2707 | winext += '|py' |
|
2706 | winext += '|py' | |
2708 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2707 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2709 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2708 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2710 | savedir = os.getcwdu() |
|
2709 | savedir = os.getcwdu() | |
2711 |
|
2710 | |||
2712 | # Now walk the paths looking for executables to alias. |
|
2711 | # Now walk the paths looking for executables to alias. | |
2713 | try: |
|
2712 | try: | |
2714 | # write the whole loop for posix/Windows so we don't have an if in |
|
2713 | # write the whole loop for posix/Windows so we don't have an if in | |
2715 | # the innermost part |
|
2714 | # the innermost part | |
2716 | if os.name == 'posix': |
|
2715 | if os.name == 'posix': | |
2717 | for pdir in path: |
|
2716 | for pdir in path: | |
2718 | os.chdir(pdir) |
|
2717 | os.chdir(pdir) | |
2719 | for ff in os.listdir(pdir): |
|
2718 | for ff in os.listdir(pdir): | |
2720 | if isexec(ff): |
|
2719 | if isexec(ff): | |
2721 | try: |
|
2720 | try: | |
2722 | # Removes dots from the name since ipython |
|
2721 | # Removes dots from the name since ipython | |
2723 | # will assume names with dots to be python. |
|
2722 | # will assume names with dots to be python. | |
2724 | self.shell.alias_manager.define_alias( |
|
2723 | self.shell.alias_manager.define_alias( | |
2725 | ff.replace('.',''), ff) |
|
2724 | ff.replace('.',''), ff) | |
2726 | except InvalidAliasError: |
|
2725 | except InvalidAliasError: | |
2727 | pass |
|
2726 | pass | |
2728 | else: |
|
2727 | else: | |
2729 | syscmdlist.append(ff) |
|
2728 | syscmdlist.append(ff) | |
2730 | else: |
|
2729 | else: | |
2731 | no_alias = self.shell.alias_manager.no_alias |
|
2730 | no_alias = self.shell.alias_manager.no_alias | |
2732 | for pdir in path: |
|
2731 | for pdir in path: | |
2733 | os.chdir(pdir) |
|
2732 | os.chdir(pdir) | |
2734 | for ff in os.listdir(pdir): |
|
2733 | for ff in os.listdir(pdir): | |
2735 | base, ext = os.path.splitext(ff) |
|
2734 | base, ext = os.path.splitext(ff) | |
2736 | if isexec(ff) and base.lower() not in no_alias: |
|
2735 | if isexec(ff) and base.lower() not in no_alias: | |
2737 | if ext.lower() == '.exe': |
|
2736 | if ext.lower() == '.exe': | |
2738 | ff = base |
|
2737 | ff = base | |
2739 | try: |
|
2738 | try: | |
2740 | # Removes dots from the name since ipython |
|
2739 | # Removes dots from the name since ipython | |
2741 | # will assume names with dots to be python. |
|
2740 | # will assume names with dots to be python. | |
2742 | self.shell.alias_manager.define_alias( |
|
2741 | self.shell.alias_manager.define_alias( | |
2743 | base.lower().replace('.',''), ff) |
|
2742 | base.lower().replace('.',''), ff) | |
2744 | except InvalidAliasError: |
|
2743 | except InvalidAliasError: | |
2745 | pass |
|
2744 | pass | |
2746 | syscmdlist.append(ff) |
|
2745 | syscmdlist.append(ff) | |
2747 | self.shell.db['syscmdlist'] = syscmdlist |
|
2746 | self.shell.db['syscmdlist'] = syscmdlist | |
2748 | finally: |
|
2747 | finally: | |
2749 | os.chdir(savedir) |
|
2748 | os.chdir(savedir) | |
2750 |
|
2749 | |||
2751 | @skip_doctest |
|
2750 | @skip_doctest | |
2752 | def magic_pwd(self, parameter_s = ''): |
|
2751 | def magic_pwd(self, parameter_s = ''): | |
2753 | """Return the current working directory path. |
|
2752 | """Return the current working directory path. | |
2754 |
|
2753 | |||
2755 | Examples |
|
2754 | Examples | |
2756 | -------- |
|
2755 | -------- | |
2757 | :: |
|
2756 | :: | |
2758 |
|
2757 | |||
2759 | In [9]: pwd |
|
2758 | In [9]: pwd | |
2760 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2759 | Out[9]: '/home/tsuser/sprint/ipython' | |
2761 | """ |
|
2760 | """ | |
2762 | return os.getcwdu() |
|
2761 | return os.getcwdu() | |
2763 |
|
2762 | |||
2764 | @skip_doctest |
|
2763 | @skip_doctest | |
2765 | def magic_cd(self, parameter_s=''): |
|
2764 | def magic_cd(self, parameter_s=''): | |
2766 | """Change the current working directory. |
|
2765 | """Change the current working directory. | |
2767 |
|
2766 | |||
2768 | This command automatically maintains an internal list of directories |
|
2767 | This command automatically maintains an internal list of directories | |
2769 | you visit during your IPython session, in the variable _dh. The |
|
2768 | you visit during your IPython session, in the variable _dh. The | |
2770 | command %dhist shows this history nicely formatted. You can also |
|
2769 | command %dhist shows this history nicely formatted. You can also | |
2771 | do 'cd -<tab>' to see directory history conveniently. |
|
2770 | do 'cd -<tab>' to see directory history conveniently. | |
2772 |
|
2771 | |||
2773 | Usage: |
|
2772 | Usage: | |
2774 |
|
2773 | |||
2775 | cd 'dir': changes to directory 'dir'. |
|
2774 | cd 'dir': changes to directory 'dir'. | |
2776 |
|
2775 | |||
2777 | cd -: changes to the last visited directory. |
|
2776 | cd -: changes to the last visited directory. | |
2778 |
|
2777 | |||
2779 | cd -<n>: changes to the n-th directory in the directory history. |
|
2778 | cd -<n>: changes to the n-th directory in the directory history. | |
2780 |
|
2779 | |||
2781 | cd --foo: change to directory that matches 'foo' in history |
|
2780 | cd --foo: change to directory that matches 'foo' in history | |
2782 |
|
2781 | |||
2783 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2782 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2784 | (note: cd <bookmark_name> is enough if there is no |
|
2783 | (note: cd <bookmark_name> is enough if there is no | |
2785 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2784 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2786 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2785 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2787 |
|
2786 | |||
2788 | Options: |
|
2787 | Options: | |
2789 |
|
2788 | |||
2790 | -q: quiet. Do not print the working directory after the cd command is |
|
2789 | -q: quiet. Do not print the working directory after the cd command is | |
2791 | executed. By default IPython's cd command does print this directory, |
|
2790 | executed. By default IPython's cd command does print this directory, | |
2792 | since the default prompts do not display path information. |
|
2791 | since the default prompts do not display path information. | |
2793 |
|
2792 | |||
2794 | Note that !cd doesn't work for this purpose because the shell where |
|
2793 | Note that !cd doesn't work for this purpose because the shell where | |
2795 | !command runs is immediately discarded after executing 'command'. |
|
2794 | !command runs is immediately discarded after executing 'command'. | |
2796 |
|
2795 | |||
2797 | Examples |
|
2796 | Examples | |
2798 | -------- |
|
2797 | -------- | |
2799 | :: |
|
2798 | :: | |
2800 |
|
2799 | |||
2801 | In [10]: cd parent/child |
|
2800 | In [10]: cd parent/child | |
2802 | /home/tsuser/parent/child |
|
2801 | /home/tsuser/parent/child | |
2803 | """ |
|
2802 | """ | |
2804 |
|
2803 | |||
2805 | parameter_s = parameter_s.strip() |
|
2804 | parameter_s = parameter_s.strip() | |
2806 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2805 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2807 |
|
2806 | |||
2808 | oldcwd = os.getcwdu() |
|
2807 | oldcwd = os.getcwdu() | |
2809 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2808 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2810 | # jump in directory history by number |
|
2809 | # jump in directory history by number | |
2811 | if numcd: |
|
2810 | if numcd: | |
2812 | nn = int(numcd.group(2)) |
|
2811 | nn = int(numcd.group(2)) | |
2813 | try: |
|
2812 | try: | |
2814 | ps = self.shell.user_ns['_dh'][nn] |
|
2813 | ps = self.shell.user_ns['_dh'][nn] | |
2815 | except IndexError: |
|
2814 | except IndexError: | |
2816 | print 'The requested directory does not exist in history.' |
|
2815 | print 'The requested directory does not exist in history.' | |
2817 | return |
|
2816 | return | |
2818 | else: |
|
2817 | else: | |
2819 | opts = {} |
|
2818 | opts = {} | |
2820 | elif parameter_s.startswith('--'): |
|
2819 | elif parameter_s.startswith('--'): | |
2821 | ps = None |
|
2820 | ps = None | |
2822 | fallback = None |
|
2821 | fallback = None | |
2823 | pat = parameter_s[2:] |
|
2822 | pat = parameter_s[2:] | |
2824 | dh = self.shell.user_ns['_dh'] |
|
2823 | dh = self.shell.user_ns['_dh'] | |
2825 | # first search only by basename (last component) |
|
2824 | # first search only by basename (last component) | |
2826 | for ent in reversed(dh): |
|
2825 | for ent in reversed(dh): | |
2827 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2826 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2828 | ps = ent |
|
2827 | ps = ent | |
2829 | break |
|
2828 | break | |
2830 |
|
2829 | |||
2831 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2830 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2832 | fallback = ent |
|
2831 | fallback = ent | |
2833 |
|
2832 | |||
2834 | # if we have no last part match, pick the first full path match |
|
2833 | # if we have no last part match, pick the first full path match | |
2835 | if ps is None: |
|
2834 | if ps is None: | |
2836 | ps = fallback |
|
2835 | ps = fallback | |
2837 |
|
2836 | |||
2838 | if ps is None: |
|
2837 | if ps is None: | |
2839 | print "No matching entry in directory history" |
|
2838 | print "No matching entry in directory history" | |
2840 | return |
|
2839 | return | |
2841 | else: |
|
2840 | else: | |
2842 | opts = {} |
|
2841 | opts = {} | |
2843 |
|
2842 | |||
2844 |
|
2843 | |||
2845 | else: |
|
2844 | else: | |
2846 | #turn all non-space-escaping backslashes to slashes, |
|
2845 | #turn all non-space-escaping backslashes to slashes, | |
2847 | # for c:\windows\directory\names\ |
|
2846 | # for c:\windows\directory\names\ | |
2848 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2847 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2849 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2848 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2850 | # jump to previous |
|
2849 | # jump to previous | |
2851 | if ps == '-': |
|
2850 | if ps == '-': | |
2852 | try: |
|
2851 | try: | |
2853 | ps = self.shell.user_ns['_dh'][-2] |
|
2852 | ps = self.shell.user_ns['_dh'][-2] | |
2854 | except IndexError: |
|
2853 | except IndexError: | |
2855 | raise UsageError('%cd -: No previous directory to change to.') |
|
2854 | raise UsageError('%cd -: No previous directory to change to.') | |
2856 | # jump to bookmark if needed |
|
2855 | # jump to bookmark if needed | |
2857 | else: |
|
2856 | else: | |
2858 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2857 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2859 | bkms = self.db.get('bookmarks', {}) |
|
2858 | bkms = self.db.get('bookmarks', {}) | |
2860 |
|
2859 | |||
2861 | if bkms.has_key(ps): |
|
2860 | if bkms.has_key(ps): | |
2862 | target = bkms[ps] |
|
2861 | target = bkms[ps] | |
2863 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2862 | print '(bookmark:%s) -> %s' % (ps,target) | |
2864 | ps = target |
|
2863 | ps = target | |
2865 | else: |
|
2864 | else: | |
2866 | if opts.has_key('b'): |
|
2865 | if opts.has_key('b'): | |
2867 | raise UsageError("Bookmark '%s' not found. " |
|
2866 | raise UsageError("Bookmark '%s' not found. " | |
2868 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2867 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2869 |
|
2868 | |||
2870 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
2869 | # strip extra quotes on Windows, because os.chdir doesn't like them | |
2871 | ps = unquote_filename(ps) |
|
2870 | ps = unquote_filename(ps) | |
2872 | # at this point ps should point to the target dir |
|
2871 | # at this point ps should point to the target dir | |
2873 | if ps: |
|
2872 | if ps: | |
2874 | try: |
|
2873 | try: | |
2875 | os.chdir(os.path.expanduser(ps)) |
|
2874 | os.chdir(os.path.expanduser(ps)) | |
2876 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2875 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2877 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2876 | set_term_title('IPython: ' + abbrev_cwd()) | |
2878 | except OSError: |
|
2877 | except OSError: | |
2879 | print sys.exc_info()[1] |
|
2878 | print sys.exc_info()[1] | |
2880 | else: |
|
2879 | else: | |
2881 | cwd = os.getcwdu() |
|
2880 | cwd = os.getcwdu() | |
2882 | dhist = self.shell.user_ns['_dh'] |
|
2881 | dhist = self.shell.user_ns['_dh'] | |
2883 | if oldcwd != cwd: |
|
2882 | if oldcwd != cwd: | |
2884 | dhist.append(cwd) |
|
2883 | dhist.append(cwd) | |
2885 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2884 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2886 |
|
2885 | |||
2887 | else: |
|
2886 | else: | |
2888 | os.chdir(self.shell.home_dir) |
|
2887 | os.chdir(self.shell.home_dir) | |
2889 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2888 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2890 | set_term_title('IPython: ' + '~') |
|
2889 | set_term_title('IPython: ' + '~') | |
2891 | cwd = os.getcwdu() |
|
2890 | cwd = os.getcwdu() | |
2892 | dhist = self.shell.user_ns['_dh'] |
|
2891 | dhist = self.shell.user_ns['_dh'] | |
2893 |
|
2892 | |||
2894 | if oldcwd != cwd: |
|
2893 | if oldcwd != cwd: | |
2895 | dhist.append(cwd) |
|
2894 | dhist.append(cwd) | |
2896 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2895 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2897 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2896 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2898 | print self.shell.user_ns['_dh'][-1] |
|
2897 | print self.shell.user_ns['_dh'][-1] | |
2899 |
|
2898 | |||
2900 |
|
2899 | |||
2901 | def magic_env(self, parameter_s=''): |
|
2900 | def magic_env(self, parameter_s=''): | |
2902 | """List environment variables.""" |
|
2901 | """List environment variables.""" | |
2903 |
|
2902 | |||
2904 | return os.environ.data |
|
2903 | return os.environ.data | |
2905 |
|
2904 | |||
2906 | def magic_pushd(self, parameter_s=''): |
|
2905 | def magic_pushd(self, parameter_s=''): | |
2907 | """Place the current dir on stack and change directory. |
|
2906 | """Place the current dir on stack and change directory. | |
2908 |
|
2907 | |||
2909 | Usage:\\ |
|
2908 | Usage:\\ | |
2910 | %pushd ['dirname'] |
|
2909 | %pushd ['dirname'] | |
2911 | """ |
|
2910 | """ | |
2912 |
|
2911 | |||
2913 | dir_s = self.shell.dir_stack |
|
2912 | dir_s = self.shell.dir_stack | |
2914 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
2913 | tgt = os.path.expanduser(unquote_filename(parameter_s)) | |
2915 | cwd = os.getcwdu().replace(self.home_dir,'~') |
|
2914 | cwd = os.getcwdu().replace(self.home_dir,'~') | |
2916 | if tgt: |
|
2915 | if tgt: | |
2917 | self.magic_cd(parameter_s) |
|
2916 | self.magic_cd(parameter_s) | |
2918 | dir_s.insert(0,cwd) |
|
2917 | dir_s.insert(0,cwd) | |
2919 | return self.magic_dirs() |
|
2918 | return self.magic_dirs() | |
2920 |
|
2919 | |||
2921 | def magic_popd(self, parameter_s=''): |
|
2920 | def magic_popd(self, parameter_s=''): | |
2922 | """Change to directory popped off the top of the stack. |
|
2921 | """Change to directory popped off the top of the stack. | |
2923 | """ |
|
2922 | """ | |
2924 | if not self.shell.dir_stack: |
|
2923 | if not self.shell.dir_stack: | |
2925 | raise UsageError("%popd on empty stack") |
|
2924 | raise UsageError("%popd on empty stack") | |
2926 | top = self.shell.dir_stack.pop(0) |
|
2925 | top = self.shell.dir_stack.pop(0) | |
2927 | self.magic_cd(top) |
|
2926 | self.magic_cd(top) | |
2928 | print "popd ->",top |
|
2927 | print "popd ->",top | |
2929 |
|
2928 | |||
2930 | def magic_dirs(self, parameter_s=''): |
|
2929 | def magic_dirs(self, parameter_s=''): | |
2931 | """Return the current directory stack.""" |
|
2930 | """Return the current directory stack.""" | |
2932 |
|
2931 | |||
2933 | return self.shell.dir_stack |
|
2932 | return self.shell.dir_stack | |
2934 |
|
2933 | |||
2935 | def magic_dhist(self, parameter_s=''): |
|
2934 | def magic_dhist(self, parameter_s=''): | |
2936 | """Print your history of visited directories. |
|
2935 | """Print your history of visited directories. | |
2937 |
|
2936 | |||
2938 | %dhist -> print full history\\ |
|
2937 | %dhist -> print full history\\ | |
2939 | %dhist n -> print last n entries only\\ |
|
2938 | %dhist n -> print last n entries only\\ | |
2940 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2939 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2941 |
|
2940 | |||
2942 | This history is automatically maintained by the %cd command, and |
|
2941 | This history is automatically maintained by the %cd command, and | |
2943 | always available as the global list variable _dh. You can use %cd -<n> |
|
2942 | always available as the global list variable _dh. You can use %cd -<n> | |
2944 | to go to directory number <n>. |
|
2943 | to go to directory number <n>. | |
2945 |
|
2944 | |||
2946 | Note that most of time, you should view directory history by entering |
|
2945 | Note that most of time, you should view directory history by entering | |
2947 | cd -<TAB>. |
|
2946 | cd -<TAB>. | |
2948 |
|
2947 | |||
2949 | """ |
|
2948 | """ | |
2950 |
|
2949 | |||
2951 | dh = self.shell.user_ns['_dh'] |
|
2950 | dh = self.shell.user_ns['_dh'] | |
2952 | if parameter_s: |
|
2951 | if parameter_s: | |
2953 | try: |
|
2952 | try: | |
2954 | args = map(int,parameter_s.split()) |
|
2953 | args = map(int,parameter_s.split()) | |
2955 | except: |
|
2954 | except: | |
2956 | self.arg_err(Magic.magic_dhist) |
|
2955 | self.arg_err(Magic.magic_dhist) | |
2957 | return |
|
2956 | return | |
2958 | if len(args) == 1: |
|
2957 | if len(args) == 1: | |
2959 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2958 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2960 | elif len(args) == 2: |
|
2959 | elif len(args) == 2: | |
2961 | ini,fin = args |
|
2960 | ini,fin = args | |
2962 | else: |
|
2961 | else: | |
2963 | self.arg_err(Magic.magic_dhist) |
|
2962 | self.arg_err(Magic.magic_dhist) | |
2964 | return |
|
2963 | return | |
2965 | else: |
|
2964 | else: | |
2966 | ini,fin = 0,len(dh) |
|
2965 | ini,fin = 0,len(dh) | |
2967 | nlprint(dh, |
|
2966 | nlprint(dh, | |
2968 | header = 'Directory history (kept in _dh)', |
|
2967 | header = 'Directory history (kept in _dh)', | |
2969 | start=ini,stop=fin) |
|
2968 | start=ini,stop=fin) | |
2970 |
|
2969 | |||
2971 | @skip_doctest |
|
2970 | @skip_doctest | |
2972 | def magic_sc(self, parameter_s=''): |
|
2971 | def magic_sc(self, parameter_s=''): | |
2973 | """Shell capture - execute a shell command and capture its output. |
|
2972 | """Shell capture - execute a shell command and capture its output. | |
2974 |
|
2973 | |||
2975 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2974 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2976 |
|
2975 | |||
2977 | You should use the form 'var = !command' instead. Example: |
|
2976 | You should use the form 'var = !command' instead. Example: | |
2978 |
|
2977 | |||
2979 | "%sc -l myfiles = ls ~" should now be written as |
|
2978 | "%sc -l myfiles = ls ~" should now be written as | |
2980 |
|
2979 | |||
2981 | "myfiles = !ls ~" |
|
2980 | "myfiles = !ls ~" | |
2982 |
|
2981 | |||
2983 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2982 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2984 | below. |
|
2983 | below. | |
2985 |
|
2984 | |||
2986 | -- |
|
2985 | -- | |
2987 | %sc [options] varname=command |
|
2986 | %sc [options] varname=command | |
2988 |
|
2987 | |||
2989 | IPython will run the given command using commands.getoutput(), and |
|
2988 | IPython will run the given command using commands.getoutput(), and | |
2990 | will then update the user's interactive namespace with a variable |
|
2989 | will then update the user's interactive namespace with a variable | |
2991 | called varname, containing the value of the call. Your command can |
|
2990 | called varname, containing the value of the call. Your command can | |
2992 | contain shell wildcards, pipes, etc. |
|
2991 | contain shell wildcards, pipes, etc. | |
2993 |
|
2992 | |||
2994 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2993 | The '=' sign in the syntax is mandatory, and the variable name you | |
2995 | supply must follow Python's standard conventions for valid names. |
|
2994 | supply must follow Python's standard conventions for valid names. | |
2996 |
|
2995 | |||
2997 | (A special format without variable name exists for internal use) |
|
2996 | (A special format without variable name exists for internal use) | |
2998 |
|
2997 | |||
2999 | Options: |
|
2998 | Options: | |
3000 |
|
2999 | |||
3001 | -l: list output. Split the output on newlines into a list before |
|
3000 | -l: list output. Split the output on newlines into a list before | |
3002 | assigning it to the given variable. By default the output is stored |
|
3001 | assigning it to the given variable. By default the output is stored | |
3003 | as a single string. |
|
3002 | as a single string. | |
3004 |
|
3003 | |||
3005 | -v: verbose. Print the contents of the variable. |
|
3004 | -v: verbose. Print the contents of the variable. | |
3006 |
|
3005 | |||
3007 | In most cases you should not need to split as a list, because the |
|
3006 | In most cases you should not need to split as a list, because the | |
3008 | returned value is a special type of string which can automatically |
|
3007 | returned value is a special type of string which can automatically | |
3009 | provide its contents either as a list (split on newlines) or as a |
|
3008 | provide its contents either as a list (split on newlines) or as a | |
3010 | space-separated string. These are convenient, respectively, either |
|
3009 | space-separated string. These are convenient, respectively, either | |
3011 | for sequential processing or to be passed to a shell command. |
|
3010 | for sequential processing or to be passed to a shell command. | |
3012 |
|
3011 | |||
3013 | For example: |
|
3012 | For example: | |
3014 |
|
3013 | |||
3015 | # all-random |
|
3014 | # all-random | |
3016 |
|
3015 | |||
3017 | # Capture into variable a |
|
3016 | # Capture into variable a | |
3018 | In [1]: sc a=ls *py |
|
3017 | In [1]: sc a=ls *py | |
3019 |
|
3018 | |||
3020 | # a is a string with embedded newlines |
|
3019 | # a is a string with embedded newlines | |
3021 | In [2]: a |
|
3020 | In [2]: a | |
3022 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3021 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
3023 |
|
3022 | |||
3024 | # which can be seen as a list: |
|
3023 | # which can be seen as a list: | |
3025 | In [3]: a.l |
|
3024 | In [3]: a.l | |
3026 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3025 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
3027 |
|
3026 | |||
3028 | # or as a whitespace-separated string: |
|
3027 | # or as a whitespace-separated string: | |
3029 | In [4]: a.s |
|
3028 | In [4]: a.s | |
3030 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3029 | Out[4]: 'setup.py win32_manual_post_install.py' | |
3031 |
|
3030 | |||
3032 | # a.s is useful to pass as a single command line: |
|
3031 | # a.s is useful to pass as a single command line: | |
3033 | In [5]: !wc -l $a.s |
|
3032 | In [5]: !wc -l $a.s | |
3034 | 146 setup.py |
|
3033 | 146 setup.py | |
3035 | 130 win32_manual_post_install.py |
|
3034 | 130 win32_manual_post_install.py | |
3036 | 276 total |
|
3035 | 276 total | |
3037 |
|
3036 | |||
3038 | # while the list form is useful to loop over: |
|
3037 | # while the list form is useful to loop over: | |
3039 | In [6]: for f in a.l: |
|
3038 | In [6]: for f in a.l: | |
3040 | ...: !wc -l $f |
|
3039 | ...: !wc -l $f | |
3041 | ...: |
|
3040 | ...: | |
3042 | 146 setup.py |
|
3041 | 146 setup.py | |
3043 | 130 win32_manual_post_install.py |
|
3042 | 130 win32_manual_post_install.py | |
3044 |
|
3043 | |||
3045 | Similiarly, the lists returned by the -l option are also special, in |
|
3044 | Similiarly, the lists returned by the -l option are also special, in | |
3046 | the sense that you can equally invoke the .s attribute on them to |
|
3045 | the sense that you can equally invoke the .s attribute on them to | |
3047 | automatically get a whitespace-separated string from their contents: |
|
3046 | automatically get a whitespace-separated string from their contents: | |
3048 |
|
3047 | |||
3049 | In [7]: sc -l b=ls *py |
|
3048 | In [7]: sc -l b=ls *py | |
3050 |
|
3049 | |||
3051 | In [8]: b |
|
3050 | In [8]: b | |
3052 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3051 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
3053 |
|
3052 | |||
3054 | In [9]: b.s |
|
3053 | In [9]: b.s | |
3055 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3054 | Out[9]: 'setup.py win32_manual_post_install.py' | |
3056 |
|
3055 | |||
3057 | In summary, both the lists and strings used for ouptut capture have |
|
3056 | In summary, both the lists and strings used for ouptut capture have | |
3058 | the following special attributes: |
|
3057 | the following special attributes: | |
3059 |
|
3058 | |||
3060 | .l (or .list) : value as list. |
|
3059 | .l (or .list) : value as list. | |
3061 | .n (or .nlstr): value as newline-separated string. |
|
3060 | .n (or .nlstr): value as newline-separated string. | |
3062 | .s (or .spstr): value as space-separated string. |
|
3061 | .s (or .spstr): value as space-separated string. | |
3063 | """ |
|
3062 | """ | |
3064 |
|
3063 | |||
3065 | opts,args = self.parse_options(parameter_s,'lv') |
|
3064 | opts,args = self.parse_options(parameter_s,'lv') | |
3066 | # Try to get a variable name and command to run |
|
3065 | # Try to get a variable name and command to run | |
3067 | try: |
|
3066 | try: | |
3068 | # the variable name must be obtained from the parse_options |
|
3067 | # the variable name must be obtained from the parse_options | |
3069 | # output, which uses shlex.split to strip options out. |
|
3068 | # output, which uses shlex.split to strip options out. | |
3070 | var,_ = args.split('=',1) |
|
3069 | var,_ = args.split('=',1) | |
3071 | var = var.strip() |
|
3070 | var = var.strip() | |
3072 | # But the the command has to be extracted from the original input |
|
3071 | # But the the command has to be extracted from the original input | |
3073 | # parameter_s, not on what parse_options returns, to avoid the |
|
3072 | # parameter_s, not on what parse_options returns, to avoid the | |
3074 | # quote stripping which shlex.split performs on it. |
|
3073 | # quote stripping which shlex.split performs on it. | |
3075 | _,cmd = parameter_s.split('=',1) |
|
3074 | _,cmd = parameter_s.split('=',1) | |
3076 | except ValueError: |
|
3075 | except ValueError: | |
3077 | var,cmd = '','' |
|
3076 | var,cmd = '','' | |
3078 | # If all looks ok, proceed |
|
3077 | # If all looks ok, proceed | |
3079 | split = 'l' in opts |
|
3078 | split = 'l' in opts | |
3080 | out = self.shell.getoutput(cmd, split=split) |
|
3079 | out = self.shell.getoutput(cmd, split=split) | |
3081 | if opts.has_key('v'): |
|
3080 | if opts.has_key('v'): | |
3082 | print '%s ==\n%s' % (var,pformat(out)) |
|
3081 | print '%s ==\n%s' % (var,pformat(out)) | |
3083 | if var: |
|
3082 | if var: | |
3084 | self.shell.user_ns.update({var:out}) |
|
3083 | self.shell.user_ns.update({var:out}) | |
3085 | else: |
|
3084 | else: | |
3086 | return out |
|
3085 | return out | |
3087 |
|
3086 | |||
3088 | def magic_sx(self, parameter_s=''): |
|
3087 | def magic_sx(self, parameter_s=''): | |
3089 | """Shell execute - run a shell command and capture its output. |
|
3088 | """Shell execute - run a shell command and capture its output. | |
3090 |
|
3089 | |||
3091 | %sx command |
|
3090 | %sx command | |
3092 |
|
3091 | |||
3093 | IPython will run the given command using commands.getoutput(), and |
|
3092 | IPython will run the given command using commands.getoutput(), and | |
3094 | return the result formatted as a list (split on '\\n'). Since the |
|
3093 | return the result formatted as a list (split on '\\n'). Since the | |
3095 | output is _returned_, it will be stored in ipython's regular output |
|
3094 | output is _returned_, it will be stored in ipython's regular output | |
3096 | cache Out[N] and in the '_N' automatic variables. |
|
3095 | cache Out[N] and in the '_N' automatic variables. | |
3097 |
|
3096 | |||
3098 | Notes: |
|
3097 | Notes: | |
3099 |
|
3098 | |||
3100 | 1) If an input line begins with '!!', then %sx is automatically |
|
3099 | 1) If an input line begins with '!!', then %sx is automatically | |
3101 | invoked. That is, while: |
|
3100 | invoked. That is, while: | |
3102 | !ls |
|
3101 | !ls | |
3103 | causes ipython to simply issue system('ls'), typing |
|
3102 | causes ipython to simply issue system('ls'), typing | |
3104 | !!ls |
|
3103 | !!ls | |
3105 | is a shorthand equivalent to: |
|
3104 | is a shorthand equivalent to: | |
3106 | %sx ls |
|
3105 | %sx ls | |
3107 |
|
3106 | |||
3108 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3107 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3109 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3108 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3110 | to process line-oriented shell output via further python commands. |
|
3109 | to process line-oriented shell output via further python commands. | |
3111 | %sc is meant to provide much finer control, but requires more |
|
3110 | %sc is meant to provide much finer control, but requires more | |
3112 | typing. |
|
3111 | typing. | |
3113 |
|
3112 | |||
3114 | 3) Just like %sc -l, this is a list with special attributes: |
|
3113 | 3) Just like %sc -l, this is a list with special attributes: | |
3115 |
|
3114 | |||
3116 | .l (or .list) : value as list. |
|
3115 | .l (or .list) : value as list. | |
3117 | .n (or .nlstr): value as newline-separated string. |
|
3116 | .n (or .nlstr): value as newline-separated string. | |
3118 | .s (or .spstr): value as whitespace-separated string. |
|
3117 | .s (or .spstr): value as whitespace-separated string. | |
3119 |
|
3118 | |||
3120 | This is very useful when trying to use such lists as arguments to |
|
3119 | This is very useful when trying to use such lists as arguments to | |
3121 | system commands.""" |
|
3120 | system commands.""" | |
3122 |
|
3121 | |||
3123 | if parameter_s: |
|
3122 | if parameter_s: | |
3124 | return self.shell.getoutput(parameter_s) |
|
3123 | return self.shell.getoutput(parameter_s) | |
3125 |
|
3124 | |||
3126 |
|
3125 | |||
3127 | def magic_bookmark(self, parameter_s=''): |
|
3126 | def magic_bookmark(self, parameter_s=''): | |
3128 | """Manage IPython's bookmark system. |
|
3127 | """Manage IPython's bookmark system. | |
3129 |
|
3128 | |||
3130 | %bookmark <name> - set bookmark to current dir |
|
3129 | %bookmark <name> - set bookmark to current dir | |
3131 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3130 | %bookmark <name> <dir> - set bookmark to <dir> | |
3132 | %bookmark -l - list all bookmarks |
|
3131 | %bookmark -l - list all bookmarks | |
3133 | %bookmark -d <name> - remove bookmark |
|
3132 | %bookmark -d <name> - remove bookmark | |
3134 | %bookmark -r - remove all bookmarks |
|
3133 | %bookmark -r - remove all bookmarks | |
3135 |
|
3134 | |||
3136 | You can later on access a bookmarked folder with: |
|
3135 | You can later on access a bookmarked folder with: | |
3137 | %cd -b <name> |
|
3136 | %cd -b <name> | |
3138 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3137 | or simply '%cd <name>' if there is no directory called <name> AND | |
3139 | there is such a bookmark defined. |
|
3138 | there is such a bookmark defined. | |
3140 |
|
3139 | |||
3141 | Your bookmarks persist through IPython sessions, but they are |
|
3140 | Your bookmarks persist through IPython sessions, but they are | |
3142 | associated with each profile.""" |
|
3141 | associated with each profile.""" | |
3143 |
|
3142 | |||
3144 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3143 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3145 | if len(args) > 2: |
|
3144 | if len(args) > 2: | |
3146 | raise UsageError("%bookmark: too many arguments") |
|
3145 | raise UsageError("%bookmark: too many arguments") | |
3147 |
|
3146 | |||
3148 | bkms = self.db.get('bookmarks',{}) |
|
3147 | bkms = self.db.get('bookmarks',{}) | |
3149 |
|
3148 | |||
3150 | if opts.has_key('d'): |
|
3149 | if opts.has_key('d'): | |
3151 | try: |
|
3150 | try: | |
3152 | todel = args[0] |
|
3151 | todel = args[0] | |
3153 | except IndexError: |
|
3152 | except IndexError: | |
3154 | raise UsageError( |
|
3153 | raise UsageError( | |
3155 | "%bookmark -d: must provide a bookmark to delete") |
|
3154 | "%bookmark -d: must provide a bookmark to delete") | |
3156 | else: |
|
3155 | else: | |
3157 | try: |
|
3156 | try: | |
3158 | del bkms[todel] |
|
3157 | del bkms[todel] | |
3159 | except KeyError: |
|
3158 | except KeyError: | |
3160 | raise UsageError( |
|
3159 | raise UsageError( | |
3161 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3160 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3162 |
|
3161 | |||
3163 | elif opts.has_key('r'): |
|
3162 | elif opts.has_key('r'): | |
3164 | bkms = {} |
|
3163 | bkms = {} | |
3165 | elif opts.has_key('l'): |
|
3164 | elif opts.has_key('l'): | |
3166 | bks = bkms.keys() |
|
3165 | bks = bkms.keys() | |
3167 | bks.sort() |
|
3166 | bks.sort() | |
3168 | if bks: |
|
3167 | if bks: | |
3169 | size = max(map(len,bks)) |
|
3168 | size = max(map(len,bks)) | |
3170 | else: |
|
3169 | else: | |
3171 | size = 0 |
|
3170 | size = 0 | |
3172 | fmt = '%-'+str(size)+'s -> %s' |
|
3171 | fmt = '%-'+str(size)+'s -> %s' | |
3173 | print 'Current bookmarks:' |
|
3172 | print 'Current bookmarks:' | |
3174 | for bk in bks: |
|
3173 | for bk in bks: | |
3175 | print fmt % (bk,bkms[bk]) |
|
3174 | print fmt % (bk,bkms[bk]) | |
3176 | else: |
|
3175 | else: | |
3177 | if not args: |
|
3176 | if not args: | |
3178 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3177 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3179 | elif len(args)==1: |
|
3178 | elif len(args)==1: | |
3180 | bkms[args[0]] = os.getcwdu() |
|
3179 | bkms[args[0]] = os.getcwdu() | |
3181 | elif len(args)==2: |
|
3180 | elif len(args)==2: | |
3182 | bkms[args[0]] = args[1] |
|
3181 | bkms[args[0]] = args[1] | |
3183 | self.db['bookmarks'] = bkms |
|
3182 | self.db['bookmarks'] = bkms | |
3184 |
|
3183 | |||
3185 | def magic_pycat(self, parameter_s=''): |
|
3184 | def magic_pycat(self, parameter_s=''): | |
3186 | """Show a syntax-highlighted file through a pager. |
|
3185 | """Show a syntax-highlighted file through a pager. | |
3187 |
|
3186 | |||
3188 | This magic is similar to the cat utility, but it will assume the file |
|
3187 | This magic is similar to the cat utility, but it will assume the file | |
3189 | to be Python source and will show it with syntax highlighting. """ |
|
3188 | to be Python source and will show it with syntax highlighting. """ | |
3190 |
|
3189 | |||
3191 | try: |
|
3190 | try: | |
3192 | filename = get_py_filename(parameter_s) |
|
3191 | filename = get_py_filename(parameter_s) | |
3193 | cont = file_read(filename) |
|
3192 | cont = file_read(filename) | |
3194 | except IOError: |
|
3193 | except IOError: | |
3195 | try: |
|
3194 | try: | |
3196 | cont = eval(parameter_s,self.user_ns) |
|
3195 | cont = eval(parameter_s,self.user_ns) | |
3197 | except NameError: |
|
3196 | except NameError: | |
3198 | cont = None |
|
3197 | cont = None | |
3199 | if cont is None: |
|
3198 | if cont is None: | |
3200 | print "Error: no such file or variable" |
|
3199 | print "Error: no such file or variable" | |
3201 | return |
|
3200 | return | |
3202 |
|
3201 | |||
3203 | page.page(self.shell.pycolorize(cont)) |
|
3202 | page.page(self.shell.pycolorize(cont)) | |
3204 |
|
3203 | |||
3205 | def magic_quickref(self,arg): |
|
3204 | def magic_quickref(self,arg): | |
3206 | """ Show a quick reference sheet """ |
|
3205 | """ Show a quick reference sheet """ | |
3207 | import IPython.core.usage |
|
3206 | import IPython.core.usage | |
3208 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3207 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3209 |
|
3208 | |||
3210 | page.page(qr) |
|
3209 | page.page(qr) | |
3211 |
|
3210 | |||
3212 | def magic_doctest_mode(self,parameter_s=''): |
|
3211 | def magic_doctest_mode(self,parameter_s=''): | |
3213 | """Toggle doctest mode on and off. |
|
3212 | """Toggle doctest mode on and off. | |
3214 |
|
3213 | |||
3215 | This mode is intended to make IPython behave as much as possible like a |
|
3214 | This mode is intended to make IPython behave as much as possible like a | |
3216 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3215 | plain Python shell, from the perspective of how its prompts, exceptions | |
3217 | and output look. This makes it easy to copy and paste parts of a |
|
3216 | and output look. This makes it easy to copy and paste parts of a | |
3218 | session into doctests. It does so by: |
|
3217 | session into doctests. It does so by: | |
3219 |
|
3218 | |||
3220 | - Changing the prompts to the classic ``>>>`` ones. |
|
3219 | - Changing the prompts to the classic ``>>>`` ones. | |
3221 | - Changing the exception reporting mode to 'Plain'. |
|
3220 | - Changing the exception reporting mode to 'Plain'. | |
3222 | - Disabling pretty-printing of output. |
|
3221 | - Disabling pretty-printing of output. | |
3223 |
|
3222 | |||
3224 | Note that IPython also supports the pasting of code snippets that have |
|
3223 | Note that IPython also supports the pasting of code snippets that have | |
3225 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3224 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3226 | doctests from files or docstrings (even if they have leading |
|
3225 | doctests from files or docstrings (even if they have leading | |
3227 | whitespace), and the code will execute correctly. You can then use |
|
3226 | whitespace), and the code will execute correctly. You can then use | |
3228 | '%history -t' to see the translated history; this will give you the |
|
3227 | '%history -t' to see the translated history; this will give you the | |
3229 | input after removal of all the leading prompts and whitespace, which |
|
3228 | input after removal of all the leading prompts and whitespace, which | |
3230 | can be pasted back into an editor. |
|
3229 | can be pasted back into an editor. | |
3231 |
|
3230 | |||
3232 | With these features, you can switch into this mode easily whenever you |
|
3231 | With these features, you can switch into this mode easily whenever you | |
3233 | need to do testing and changes to doctests, without having to leave |
|
3232 | need to do testing and changes to doctests, without having to leave | |
3234 | your existing IPython session. |
|
3233 | your existing IPython session. | |
3235 | """ |
|
3234 | """ | |
3236 |
|
3235 | |||
3237 | from IPython.utils.ipstruct import Struct |
|
3236 | from IPython.utils.ipstruct import Struct | |
3238 |
|
3237 | |||
3239 | # Shorthands |
|
3238 | # Shorthands | |
3240 | shell = self.shell |
|
3239 | shell = self.shell | |
3241 | oc = shell.displayhook |
|
3240 | oc = shell.displayhook | |
3242 | meta = shell.meta |
|
3241 | meta = shell.meta | |
3243 | disp_formatter = self.shell.display_formatter |
|
3242 | disp_formatter = self.shell.display_formatter | |
3244 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3243 | ptformatter = disp_formatter.formatters['text/plain'] | |
3245 | # dstore is a data store kept in the instance metadata bag to track any |
|
3244 | # dstore is a data store kept in the instance metadata bag to track any | |
3246 | # changes we make, so we can undo them later. |
|
3245 | # changes we make, so we can undo them later. | |
3247 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3246 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3248 | save_dstore = dstore.setdefault |
|
3247 | save_dstore = dstore.setdefault | |
3249 |
|
3248 | |||
3250 | # save a few values we'll need to recover later |
|
3249 | # save a few values we'll need to recover later | |
3251 | mode = save_dstore('mode',False) |
|
3250 | mode = save_dstore('mode',False) | |
3252 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3251 | save_dstore('rc_pprint',ptformatter.pprint) | |
3253 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3252 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3254 | save_dstore('rc_separate_out',shell.separate_out) |
|
3253 | save_dstore('rc_separate_out',shell.separate_out) | |
3255 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3254 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3256 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3255 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3257 | save_dstore('rc_separate_in',shell.separate_in) |
|
3256 | save_dstore('rc_separate_in',shell.separate_in) | |
3258 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3257 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
3259 |
|
3258 | |||
3260 | if mode == False: |
|
3259 | if mode == False: | |
3261 | # turn on |
|
3260 | # turn on | |
3262 | oc.prompt1.p_template = '>>> ' |
|
3261 | oc.prompt1.p_template = '>>> ' | |
3263 | oc.prompt2.p_template = '... ' |
|
3262 | oc.prompt2.p_template = '... ' | |
3264 | oc.prompt_out.p_template = '' |
|
3263 | oc.prompt_out.p_template = '' | |
3265 |
|
3264 | |||
3266 | # Prompt separators like plain python |
|
3265 | # Prompt separators like plain python | |
3267 | oc.input_sep = oc.prompt1.sep = '' |
|
3266 | oc.input_sep = oc.prompt1.sep = '' | |
3268 | oc.output_sep = '' |
|
3267 | oc.output_sep = '' | |
3269 | oc.output_sep2 = '' |
|
3268 | oc.output_sep2 = '' | |
3270 |
|
3269 | |||
3271 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3270 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3272 | oc.prompt_out.pad_left = False |
|
3271 | oc.prompt_out.pad_left = False | |
3273 |
|
3272 | |||
3274 | ptformatter.pprint = False |
|
3273 | ptformatter.pprint = False | |
3275 | disp_formatter.plain_text_only = True |
|
3274 | disp_formatter.plain_text_only = True | |
3276 |
|
3275 | |||
3277 | shell.magic_xmode('Plain') |
|
3276 | shell.magic_xmode('Plain') | |
3278 | else: |
|
3277 | else: | |
3279 | # turn off |
|
3278 | # turn off | |
3280 | oc.prompt1.p_template = shell.prompt_in1 |
|
3279 | oc.prompt1.p_template = shell.prompt_in1 | |
3281 | oc.prompt2.p_template = shell.prompt_in2 |
|
3280 | oc.prompt2.p_template = shell.prompt_in2 | |
3282 | oc.prompt_out.p_template = shell.prompt_out |
|
3281 | oc.prompt_out.p_template = shell.prompt_out | |
3283 |
|
3282 | |||
3284 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3283 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3285 |
|
3284 | |||
3286 | oc.output_sep = dstore.rc_separate_out |
|
3285 | oc.output_sep = dstore.rc_separate_out | |
3287 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3286 | oc.output_sep2 = dstore.rc_separate_out2 | |
3288 |
|
3287 | |||
3289 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3288 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3290 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3289 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3291 |
|
3290 | |||
3292 | ptformatter.pprint = dstore.rc_pprint |
|
3291 | ptformatter.pprint = dstore.rc_pprint | |
3293 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3292 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
3294 |
|
3293 | |||
3295 | shell.magic_xmode(dstore.xmode) |
|
3294 | shell.magic_xmode(dstore.xmode) | |
3296 |
|
3295 | |||
3297 | # Store new mode and inform |
|
3296 | # Store new mode and inform | |
3298 | dstore.mode = bool(1-int(mode)) |
|
3297 | dstore.mode = bool(1-int(mode)) | |
3299 | mode_label = ['OFF','ON'][dstore.mode] |
|
3298 | mode_label = ['OFF','ON'][dstore.mode] | |
3300 | print 'Doctest mode is:', mode_label |
|
3299 | print 'Doctest mode is:', mode_label | |
3301 |
|
3300 | |||
3302 | def magic_gui(self, parameter_s=''): |
|
3301 | def magic_gui(self, parameter_s=''): | |
3303 | """Enable or disable IPython GUI event loop integration. |
|
3302 | """Enable or disable IPython GUI event loop integration. | |
3304 |
|
3303 | |||
3305 | %gui [GUINAME] |
|
3304 | %gui [GUINAME] | |
3306 |
|
3305 | |||
3307 | This magic replaces IPython's threaded shells that were activated |
|
3306 | This magic replaces IPython's threaded shells that were activated | |
3308 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3307 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3309 | can now be enabled, disabled and changed at runtime and keyboard |
|
3308 | can now be enabled, disabled and changed at runtime and keyboard | |
3310 | interrupts should work without any problems. The following toolkits |
|
3309 | interrupts should work without any problems. The following toolkits | |
3311 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3310 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3312 |
|
3311 | |||
3313 | %gui wx # enable wxPython event loop integration |
|
3312 | %gui wx # enable wxPython event loop integration | |
3314 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3313 | %gui qt4|qt # enable PyQt4 event loop integration | |
3315 | %gui gtk # enable PyGTK event loop integration |
|
3314 | %gui gtk # enable PyGTK event loop integration | |
3316 | %gui tk # enable Tk event loop integration |
|
3315 | %gui tk # enable Tk event loop integration | |
3317 | %gui # disable all event loop integration |
|
3316 | %gui # disable all event loop integration | |
3318 |
|
3317 | |||
3319 | WARNING: after any of these has been called you can simply create |
|
3318 | WARNING: after any of these has been called you can simply create | |
3320 | an application object, but DO NOT start the event loop yourself, as |
|
3319 | an application object, but DO NOT start the event loop yourself, as | |
3321 | we have already handled that. |
|
3320 | we have already handled that. | |
3322 | """ |
|
3321 | """ | |
3323 | from IPython.lib.inputhook import enable_gui |
|
3322 | from IPython.lib.inputhook import enable_gui | |
3324 | opts, arg = self.parse_options(parameter_s, '') |
|
3323 | opts, arg = self.parse_options(parameter_s, '') | |
3325 | if arg=='': arg = None |
|
3324 | if arg=='': arg = None | |
3326 | return enable_gui(arg) |
|
3325 | return enable_gui(arg) | |
3327 |
|
3326 | |||
3328 | def magic_load_ext(self, module_str): |
|
3327 | def magic_load_ext(self, module_str): | |
3329 | """Load an IPython extension by its module name.""" |
|
3328 | """Load an IPython extension by its module name.""" | |
3330 | return self.extension_manager.load_extension(module_str) |
|
3329 | return self.extension_manager.load_extension(module_str) | |
3331 |
|
3330 | |||
3332 | def magic_unload_ext(self, module_str): |
|
3331 | def magic_unload_ext(self, module_str): | |
3333 | """Unload an IPython extension by its module name.""" |
|
3332 | """Unload an IPython extension by its module name.""" | |
3334 | self.extension_manager.unload_extension(module_str) |
|
3333 | self.extension_manager.unload_extension(module_str) | |
3335 |
|
3334 | |||
3336 | def magic_reload_ext(self, module_str): |
|
3335 | def magic_reload_ext(self, module_str): | |
3337 | """Reload an IPython extension by its module name.""" |
|
3336 | """Reload an IPython extension by its module name.""" | |
3338 | self.extension_manager.reload_extension(module_str) |
|
3337 | self.extension_manager.reload_extension(module_str) | |
3339 |
|
3338 | |||
3340 | @skip_doctest |
|
3339 | @skip_doctest | |
3341 | def magic_install_profiles(self, s): |
|
3340 | def magic_install_profiles(self, s): | |
3342 | """Install the default IPython profiles into the .ipython dir. |
|
3341 | """Install the default IPython profiles into the .ipython dir. | |
3343 |
|
3342 | |||
3344 | If the default profiles have already been installed, they will not |
|
3343 | If the default profiles have already been installed, they will not | |
3345 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3344 | be overwritten. You can force overwriting them by using the ``-o`` | |
3346 | option:: |
|
3345 | option:: | |
3347 |
|
3346 | |||
3348 | In [1]: %install_profiles -o |
|
3347 | In [1]: %install_profiles -o | |
3349 | """ |
|
3348 | """ | |
3350 | if '-o' in s: |
|
3349 | if '-o' in s: | |
3351 | overwrite = True |
|
3350 | overwrite = True | |
3352 | else: |
|
3351 | else: | |
3353 | overwrite = False |
|
3352 | overwrite = False | |
3354 | from IPython.config import profile |
|
3353 | from IPython.config import profile | |
3355 | profile_dir = os.path.dirname(profile.__file__) |
|
3354 | profile_dir = os.path.dirname(profile.__file__) | |
3356 | ipython_dir = self.ipython_dir |
|
3355 | ipython_dir = self.ipython_dir | |
3357 | print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite) |
|
3356 | print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite) | |
3358 | for src in os.listdir(profile_dir): |
|
3357 | for src in os.listdir(profile_dir): | |
3359 | if src.startswith('profile_'): |
|
3358 | if src.startswith('profile_'): | |
3360 | name = src.replace('profile_', '') |
|
3359 | name = src.replace('profile_', '') | |
3361 | print " %s"%name |
|
3360 | print " %s"%name | |
3362 | pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name) |
|
3361 | pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name) | |
3363 | pd.copy_config_file('ipython_config.py', path=src, |
|
3362 | pd.copy_config_file('ipython_config.py', path=src, | |
3364 | overwrite=overwrite) |
|
3363 | overwrite=overwrite) | |
3365 |
|
3364 | |||
3366 | @skip_doctest |
|
3365 | @skip_doctest | |
3367 | def magic_install_default_config(self, s): |
|
3366 | def magic_install_default_config(self, s): | |
3368 | """Install IPython's default config file into the .ipython dir. |
|
3367 | """Install IPython's default config file into the .ipython dir. | |
3369 |
|
3368 | |||
3370 | If the default config file (:file:`ipython_config.py`) is already |
|
3369 | If the default config file (:file:`ipython_config.py`) is already | |
3371 | installed, it will not be overwritten. You can force overwriting |
|
3370 | installed, it will not be overwritten. You can force overwriting | |
3372 | by using the ``-o`` option:: |
|
3371 | by using the ``-o`` option:: | |
3373 |
|
3372 | |||
3374 | In [1]: %install_default_config |
|
3373 | In [1]: %install_default_config | |
3375 | """ |
|
3374 | """ | |
3376 | if '-o' in s: |
|
3375 | if '-o' in s: | |
3377 | overwrite = True |
|
3376 | overwrite = True | |
3378 | else: |
|
3377 | else: | |
3379 | overwrite = False |
|
3378 | overwrite = False | |
3380 | pd = self.shell.profile_dir |
|
3379 | pd = self.shell.profile_dir | |
3381 | print "Installing default config file in: %s" % pd.location |
|
3380 | print "Installing default config file in: %s" % pd.location | |
3382 | pd.copy_config_file('ipython_config.py', overwrite=overwrite) |
|
3381 | pd.copy_config_file('ipython_config.py', overwrite=overwrite) | |
3383 |
|
3382 | |||
3384 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3383 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3385 | # handling and modify slightly %run |
|
3384 | # handling and modify slightly %run | |
3386 |
|
3385 | |||
3387 | @skip_doctest |
|
3386 | @skip_doctest | |
3388 | def _pylab_magic_run(self, parameter_s=''): |
|
3387 | def _pylab_magic_run(self, parameter_s=''): | |
3389 | Magic.magic_run(self, parameter_s, |
|
3388 | Magic.magic_run(self, parameter_s, | |
3390 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3389 | runner=mpl_runner(self.shell.safe_execfile)) | |
3391 |
|
3390 | |||
3392 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3391 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3393 |
|
3392 | |||
3394 | @skip_doctest |
|
3393 | @skip_doctest | |
3395 | def magic_pylab(self, s): |
|
3394 | def magic_pylab(self, s): | |
3396 | """Load numpy and matplotlib to work interactively. |
|
3395 | """Load numpy and matplotlib to work interactively. | |
3397 |
|
3396 | |||
3398 | %pylab [GUINAME] |
|
3397 | %pylab [GUINAME] | |
3399 |
|
3398 | |||
3400 | This function lets you activate pylab (matplotlib, numpy and |
|
3399 | This function lets you activate pylab (matplotlib, numpy and | |
3401 | interactive support) at any point during an IPython session. |
|
3400 | interactive support) at any point during an IPython session. | |
3402 |
|
3401 | |||
3403 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3402 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3404 | pylab and mlab, as well as all names from numpy and pylab. |
|
3403 | pylab and mlab, as well as all names from numpy and pylab. | |
3405 |
|
3404 | |||
3406 | If you are using the inline matplotlib backend for embedded figures, |
|
3405 | If you are using the inline matplotlib backend for embedded figures, | |
3407 | you can adjust its behavior via the %config magic:: |
|
3406 | you can adjust its behavior via the %config magic:: | |
3408 |
|
3407 | |||
3409 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole |
|
3408 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole | |
3410 | In [1]: %config InlineBackend.figure_format = 'svg' |
|
3409 | In [1]: %config InlineBackend.figure_format = 'svg' | |
3411 |
|
3410 | |||
3412 | # change the behavior of closing all figures at the end of each |
|
3411 | # change the behavior of closing all figures at the end of each | |
3413 | # execution (cell), or allowing reuse of active figures across |
|
3412 | # execution (cell), or allowing reuse of active figures across | |
3414 | # cells: |
|
3413 | # cells: | |
3415 | In [2]: %config InlineBackend.close_figures = False |
|
3414 | In [2]: %config InlineBackend.close_figures = False | |
3416 |
|
3415 | |||
3417 | Parameters |
|
3416 | Parameters | |
3418 | ---------- |
|
3417 | ---------- | |
3419 | guiname : optional |
|
3418 | guiname : optional | |
3420 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or |
|
3419 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or | |
3421 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3420 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3422 | otherwise matplotlib's default (which you can override in your |
|
3421 | otherwise matplotlib's default (which you can override in your | |
3423 | matplotlib config file) is used. |
|
3422 | matplotlib config file) is used. | |
3424 |
|
3423 | |||
3425 | Examples |
|
3424 | Examples | |
3426 | -------- |
|
3425 | -------- | |
3427 | In this case, where the MPL default is TkAgg:: |
|
3426 | In this case, where the MPL default is TkAgg:: | |
3428 |
|
3427 | |||
3429 | In [2]: %pylab |
|
3428 | In [2]: %pylab | |
3430 |
|
3429 | |||
3431 | Welcome to pylab, a matplotlib-based Python environment. |
|
3430 | Welcome to pylab, a matplotlib-based Python environment. | |
3432 | Backend in use: TkAgg |
|
3431 | Backend in use: TkAgg | |
3433 | For more information, type 'help(pylab)'. |
|
3432 | For more information, type 'help(pylab)'. | |
3434 |
|
3433 | |||
3435 | But you can explicitly request a different backend:: |
|
3434 | But you can explicitly request a different backend:: | |
3436 |
|
3435 | |||
3437 | In [3]: %pylab qt |
|
3436 | In [3]: %pylab qt | |
3438 |
|
3437 | |||
3439 | Welcome to pylab, a matplotlib-based Python environment. |
|
3438 | Welcome to pylab, a matplotlib-based Python environment. | |
3440 | Backend in use: Qt4Agg |
|
3439 | Backend in use: Qt4Agg | |
3441 | For more information, type 'help(pylab)'. |
|
3440 | For more information, type 'help(pylab)'. | |
3442 | """ |
|
3441 | """ | |
3443 |
|
3442 | |||
3444 | if Application.initialized(): |
|
3443 | if Application.initialized(): | |
3445 | app = Application.instance() |
|
3444 | app = Application.instance() | |
3446 | try: |
|
3445 | try: | |
3447 | import_all_status = app.pylab_import_all |
|
3446 | import_all_status = app.pylab_import_all | |
3448 | except AttributeError: |
|
3447 | except AttributeError: | |
3449 | import_all_status = True |
|
3448 | import_all_status = True | |
3450 | else: |
|
3449 | else: | |
3451 | import_all_status = True |
|
3450 | import_all_status = True | |
3452 |
|
3451 | |||
3453 | self.shell.enable_pylab(s,import_all=import_all_status) |
|
3452 | self.shell.enable_pylab(s,import_all=import_all_status) | |
3454 |
|
3453 | |||
3455 | def magic_tb(self, s): |
|
3454 | def magic_tb(self, s): | |
3456 | """Print the last traceback with the currently active exception mode. |
|
3455 | """Print the last traceback with the currently active exception mode. | |
3457 |
|
3456 | |||
3458 | See %xmode for changing exception reporting modes.""" |
|
3457 | See %xmode for changing exception reporting modes.""" | |
3459 | self.shell.showtraceback() |
|
3458 | self.shell.showtraceback() | |
3460 |
|
3459 | |||
3461 | @skip_doctest |
|
3460 | @skip_doctest | |
3462 | def magic_precision(self, s=''): |
|
3461 | def magic_precision(self, s=''): | |
3463 | """Set floating point precision for pretty printing. |
|
3462 | """Set floating point precision for pretty printing. | |
3464 |
|
3463 | |||
3465 | Can set either integer precision or a format string. |
|
3464 | Can set either integer precision or a format string. | |
3466 |
|
3465 | |||
3467 | If numpy has been imported and precision is an int, |
|
3466 | If numpy has been imported and precision is an int, | |
3468 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3467 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
3469 |
|
3468 | |||
3470 | If no argument is given, defaults will be restored. |
|
3469 | If no argument is given, defaults will be restored. | |
3471 |
|
3470 | |||
3472 | Examples |
|
3471 | Examples | |
3473 | -------- |
|
3472 | -------- | |
3474 | :: |
|
3473 | :: | |
3475 |
|
3474 | |||
3476 | In [1]: from math import pi |
|
3475 | In [1]: from math import pi | |
3477 |
|
3476 | |||
3478 | In [2]: %precision 3 |
|
3477 | In [2]: %precision 3 | |
3479 | Out[2]: u'%.3f' |
|
3478 | Out[2]: u'%.3f' | |
3480 |
|
3479 | |||
3481 | In [3]: pi |
|
3480 | In [3]: pi | |
3482 | Out[3]: 3.142 |
|
3481 | Out[3]: 3.142 | |
3483 |
|
3482 | |||
3484 | In [4]: %precision %i |
|
3483 | In [4]: %precision %i | |
3485 | Out[4]: u'%i' |
|
3484 | Out[4]: u'%i' | |
3486 |
|
3485 | |||
3487 | In [5]: pi |
|
3486 | In [5]: pi | |
3488 | Out[5]: 3 |
|
3487 | Out[5]: 3 | |
3489 |
|
3488 | |||
3490 | In [6]: %precision %e |
|
3489 | In [6]: %precision %e | |
3491 | Out[6]: u'%e' |
|
3490 | Out[6]: u'%e' | |
3492 |
|
3491 | |||
3493 | In [7]: pi**10 |
|
3492 | In [7]: pi**10 | |
3494 | Out[7]: 9.364805e+04 |
|
3493 | Out[7]: 9.364805e+04 | |
3495 |
|
3494 | |||
3496 | In [8]: %precision |
|
3495 | In [8]: %precision | |
3497 | Out[8]: u'%r' |
|
3496 | Out[8]: u'%r' | |
3498 |
|
3497 | |||
3499 | In [9]: pi**10 |
|
3498 | In [9]: pi**10 | |
3500 | Out[9]: 93648.047476082982 |
|
3499 | Out[9]: 93648.047476082982 | |
3501 |
|
3500 | |||
3502 | """ |
|
3501 | """ | |
3503 |
|
3502 | |||
3504 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3503 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
3505 | ptformatter.float_precision = s |
|
3504 | ptformatter.float_precision = s | |
3506 | return ptformatter.float_format |
|
3505 | return ptformatter.float_format | |
3507 |
|
3506 | |||
3508 |
|
3507 | |||
3509 | @magic_arguments.magic_arguments() |
|
3508 | @magic_arguments.magic_arguments() | |
3510 | @magic_arguments.argument( |
|
3509 | @magic_arguments.argument( | |
3511 | '-e', '--export', action='store_true', default=False, |
|
3510 | '-e', '--export', action='store_true', default=False, | |
3512 | help='Export IPython history as a notebook. The filename argument ' |
|
3511 | help='Export IPython history as a notebook. The filename argument ' | |
3513 | 'is used to specify the notebook name and format. For example ' |
|
3512 | 'is used to specify the notebook name and format. For example ' | |
3514 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
3513 | 'a filename of notebook.ipynb will result in a notebook name ' | |
3515 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
3514 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' | |
3516 | 'or ".py" file extension will write the notebook in the json ' |
|
3515 | 'or ".py" file extension will write the notebook in the json ' | |
3517 | 'or py formats.' |
|
3516 | 'or py formats.' | |
3518 | ) |
|
3517 | ) | |
3519 | @magic_arguments.argument( |
|
3518 | @magic_arguments.argument( | |
3520 | '-f', '--format', |
|
3519 | '-f', '--format', | |
3521 | help='Convert an existing IPython notebook to a new format. This option ' |
|
3520 | help='Convert an existing IPython notebook to a new format. This option ' | |
3522 | 'specifies the new format and can have the values: xml, json, py. ' |
|
3521 | 'specifies the new format and can have the values: xml, json, py. ' | |
3523 | 'The target filename is choosen automatically based on the new ' |
|
3522 | 'The target filename is choosen automatically based on the new ' | |
3524 | 'format. The filename argument gives the name of the source file.' |
|
3523 | 'format. The filename argument gives the name of the source file.' | |
3525 | ) |
|
3524 | ) | |
3526 | @magic_arguments.argument( |
|
3525 | @magic_arguments.argument( | |
3527 | 'filename', type=unicode, |
|
3526 | 'filename', type=unicode, | |
3528 | help='Notebook name or filename' |
|
3527 | help='Notebook name or filename' | |
3529 | ) |
|
3528 | ) | |
3530 | def magic_notebook(self, s): |
|
3529 | def magic_notebook(self, s): | |
3531 | """Export and convert IPython notebooks. |
|
3530 | """Export and convert IPython notebooks. | |
3532 |
|
3531 | |||
3533 | This function can export the current IPython history to a notebook file |
|
3532 | This function can export the current IPython history to a notebook file | |
3534 | or can convert an existing notebook file into a different format. For |
|
3533 | or can convert an existing notebook file into a different format. For | |
3535 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
3534 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". | |
3536 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
3535 | To export the history to "foo.py" do "%notebook -e foo.py". To convert | |
3537 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
3536 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible | |
3538 | formats include (json/ipynb, py). |
|
3537 | formats include (json/ipynb, py). | |
3539 | """ |
|
3538 | """ | |
3540 | args = magic_arguments.parse_argstring(self.magic_notebook, s) |
|
3539 | args = magic_arguments.parse_argstring(self.magic_notebook, s) | |
3541 |
|
3540 | |||
3542 | from IPython.nbformat import current |
|
3541 | from IPython.nbformat import current | |
3543 | args.filename = unquote_filename(args.filename) |
|
3542 | args.filename = unquote_filename(args.filename) | |
3544 | if args.export: |
|
3543 | if args.export: | |
3545 | fname, name, format = current.parse_filename(args.filename) |
|
3544 | fname, name, format = current.parse_filename(args.filename) | |
3546 | cells = [] |
|
3545 | cells = [] | |
3547 | hist = list(self.history_manager.get_range()) |
|
3546 | hist = list(self.history_manager.get_range()) | |
3548 | for session, prompt_number, input in hist[:-1]: |
|
3547 | for session, prompt_number, input in hist[:-1]: | |
3549 | cells.append(current.new_code_cell(prompt_number=prompt_number, input=input)) |
|
3548 | cells.append(current.new_code_cell(prompt_number=prompt_number, input=input)) | |
3550 | worksheet = current.new_worksheet(cells=cells) |
|
3549 | worksheet = current.new_worksheet(cells=cells) | |
3551 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
3550 | nb = current.new_notebook(name=name,worksheets=[worksheet]) | |
3552 | with open(fname, 'w') as f: |
|
3551 | with open(fname, 'w') as f: | |
3553 | current.write(nb, f, format); |
|
3552 | current.write(nb, f, format); | |
3554 | elif args.format is not None: |
|
3553 | elif args.format is not None: | |
3555 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
3554 | old_fname, old_name, old_format = current.parse_filename(args.filename) | |
3556 | new_format = args.format |
|
3555 | new_format = args.format | |
3557 | if new_format == u'xml': |
|
3556 | if new_format == u'xml': | |
3558 | raise ValueError('Notebooks cannot be written as xml.') |
|
3557 | raise ValueError('Notebooks cannot be written as xml.') | |
3559 | elif new_format == u'ipynb' or new_format == u'json': |
|
3558 | elif new_format == u'ipynb' or new_format == u'json': | |
3560 | new_fname = old_name + u'.ipynb' |
|
3559 | new_fname = old_name + u'.ipynb' | |
3561 | new_format = u'json' |
|
3560 | new_format = u'json' | |
3562 | elif new_format == u'py': |
|
3561 | elif new_format == u'py': | |
3563 | new_fname = old_name + u'.py' |
|
3562 | new_fname = old_name + u'.py' | |
3564 | else: |
|
3563 | else: | |
3565 | raise ValueError('Invalid notebook format: %s' % new_format) |
|
3564 | raise ValueError('Invalid notebook format: %s' % new_format) | |
3566 | with open(old_fname, 'r') as f: |
|
3565 | with open(old_fname, 'r') as f: | |
3567 | s = f.read() |
|
3566 | s = f.read() | |
3568 | try: |
|
3567 | try: | |
3569 | nb = current.reads(s, old_format) |
|
3568 | nb = current.reads(s, old_format) | |
3570 | except: |
|
3569 | except: | |
3571 | nb = current.reads(s, u'xml') |
|
3570 | nb = current.reads(s, u'xml') | |
3572 | with open(new_fname, 'w') as f: |
|
3571 | with open(new_fname, 'w') as f: | |
3573 | current.write(nb, f, new_format) |
|
3572 | current.write(nb, f, new_format) | |
3574 |
|
3573 | |||
3575 | def magic_config(self, s): |
|
3574 | def magic_config(self, s): | |
3576 | """configure IPython |
|
3575 | """configure IPython | |
3577 |
|
3576 | |||
3578 | %config Class[.trait=value] |
|
3577 | %config Class[.trait=value] | |
3579 |
|
3578 | |||
3580 | This magic exposes most of the IPython config system. Any |
|
3579 | This magic exposes most of the IPython config system. Any | |
3581 | Configurable class should be able to be configured with the simple |
|
3580 | Configurable class should be able to be configured with the simple | |
3582 | line:: |
|
3581 | line:: | |
3583 |
|
3582 | |||
3584 | %config Class.trait=value |
|
3583 | %config Class.trait=value | |
3585 |
|
3584 | |||
3586 | Where `value` will be resolved in the user's namespace, if it is an |
|
3585 | Where `value` will be resolved in the user's namespace, if it is an | |
3587 | expression or variable name. |
|
3586 | expression or variable name. | |
3588 |
|
3587 | |||
3589 | Examples |
|
3588 | Examples | |
3590 | -------- |
|
3589 | -------- | |
3591 |
|
3590 | |||
3592 | To see what classes are availabe for config, pass no arguments:: |
|
3591 | To see what classes are availabe for config, pass no arguments:: | |
3593 |
|
3592 | |||
3594 | In [1]: %config |
|
3593 | In [1]: %config | |
3595 | Available objects for config: |
|
3594 | Available objects for config: | |
3596 | TerminalInteractiveShell |
|
3595 | TerminalInteractiveShell | |
3597 | HistoryManager |
|
3596 | HistoryManager | |
3598 | PrefilterManager |
|
3597 | PrefilterManager | |
3599 | AliasManager |
|
3598 | AliasManager | |
3600 | IPCompleter |
|
3599 | IPCompleter | |
3601 | DisplayFormatter |
|
3600 | DisplayFormatter | |
3602 |
|
3601 | |||
3603 | To view what is configurable on a given class, just pass the class name:: |
|
3602 | To view what is configurable on a given class, just pass the class name:: | |
3604 |
|
3603 | |||
3605 | In [2]: %config IPCompleter |
|
3604 | In [2]: %config IPCompleter | |
3606 | IPCompleter options |
|
3605 | IPCompleter options | |
3607 | ----------------- |
|
3606 | ----------------- | |
3608 | IPCompleter.omit__names=<Enum> |
|
3607 | IPCompleter.omit__names=<Enum> | |
3609 | Current: 2 |
|
3608 | Current: 2 | |
3610 | Choices: (0, 1, 2) |
|
3609 | Choices: (0, 1, 2) | |
3611 | Instruct the completer to omit private method names |
|
3610 | Instruct the completer to omit private method names | |
3612 | Specifically, when completing on ``object.<tab>``. |
|
3611 | Specifically, when completing on ``object.<tab>``. | |
3613 | When 2 [default]: all names that start with '_' will be excluded. |
|
3612 | When 2 [default]: all names that start with '_' will be excluded. | |
3614 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
3613 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
3615 | When 0: nothing will be excluded. |
|
3614 | When 0: nothing will be excluded. | |
3616 | IPCompleter.merge_completions=<CBool> |
|
3615 | IPCompleter.merge_completions=<CBool> | |
3617 | Current: True |
|
3616 | Current: True | |
3618 | Whether to merge completion results into a single list |
|
3617 | Whether to merge completion results into a single list | |
3619 | If False, only the completion results from the first non-empty completer |
|
3618 | If False, only the completion results from the first non-empty completer | |
3620 | will be returned. |
|
3619 | will be returned. | |
3621 | IPCompleter.greedy=<CBool> |
|
3620 | IPCompleter.greedy=<CBool> | |
3622 | Current: False |
|
3621 | Current: False | |
3623 | Activate greedy completion |
|
3622 | Activate greedy completion | |
3624 | This will enable completion on elements of lists, results of function calls, |
|
3623 | This will enable completion on elements of lists, results of function calls, | |
3625 | etc., but can be unsafe because the code is actually evaluated on TAB. |
|
3624 | etc., but can be unsafe because the code is actually evaluated on TAB. | |
3626 |
|
3625 | |||
3627 | but the real use is in setting values:: |
|
3626 | but the real use is in setting values:: | |
3628 |
|
3627 | |||
3629 | In [3]: %config IPCompleter.greedy = True |
|
3628 | In [3]: %config IPCompleter.greedy = True | |
3630 |
|
3629 | |||
3631 | and these values are read from the user_ns if they are variables:: |
|
3630 | and these values are read from the user_ns if they are variables:: | |
3632 |
|
3631 | |||
3633 | In [4]: feeling_greedy=False |
|
3632 | In [4]: feeling_greedy=False | |
3634 |
|
3633 | |||
3635 | In [5]: %config IPCompleter.greedy = feeling_greedy |
|
3634 | In [5]: %config IPCompleter.greedy = feeling_greedy | |
3636 |
|
3635 | |||
3637 | """ |
|
3636 | """ | |
3638 | from IPython.config.loader import Config |
|
3637 | from IPython.config.loader import Config | |
3639 | # some IPython objects are Configurable, but do not yet have |
|
3638 | # some IPython objects are Configurable, but do not yet have | |
3640 | # any configurable traits. Exclude them from the effects of |
|
3639 | # any configurable traits. Exclude them from the effects of | |
3641 | # this magic, as their presence is just noise: |
|
3640 | # this magic, as their presence is just noise: | |
3642 | configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ] |
|
3641 | configurables = [ c for c in self.configurables if c.__class__.class_traits(config=True) ] | |
3643 | classnames = [ c.__class__.__name__ for c in configurables ] |
|
3642 | classnames = [ c.__class__.__name__ for c in configurables ] | |
3644 |
|
3643 | |||
3645 | line = s.strip() |
|
3644 | line = s.strip() | |
3646 | if not line: |
|
3645 | if not line: | |
3647 | # print available configurable names |
|
3646 | # print available configurable names | |
3648 | print "Available objects for config:" |
|
3647 | print "Available objects for config:" | |
3649 | for name in classnames: |
|
3648 | for name in classnames: | |
3650 | print " ", name |
|
3649 | print " ", name | |
3651 | return |
|
3650 | return | |
3652 | elif line in classnames: |
|
3651 | elif line in classnames: | |
3653 | # `%config TerminalInteractiveShell` will print trait info for |
|
3652 | # `%config TerminalInteractiveShell` will print trait info for | |
3654 | # TerminalInteractiveShell |
|
3653 | # TerminalInteractiveShell | |
3655 | c = configurables[classnames.index(line)] |
|
3654 | c = configurables[classnames.index(line)] | |
3656 | cls = c.__class__ |
|
3655 | cls = c.__class__ | |
3657 | help = cls.class_get_help(c) |
|
3656 | help = cls.class_get_help(c) | |
3658 | # strip leading '--' from cl-args: |
|
3657 | # strip leading '--' from cl-args: | |
3659 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
3658 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) | |
3660 | print help |
|
3659 | print help | |
3661 | return |
|
3660 | return | |
3662 | elif '=' not in line: |
|
3661 | elif '=' not in line: | |
3663 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) |
|
3662 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) | |
3664 |
|
3663 | |||
3665 |
|
3664 | |||
3666 | # otherwise, assume we are setting configurables. |
|
3665 | # otherwise, assume we are setting configurables. | |
3667 | # leave quotes on args when splitting, because we want |
|
3666 | # leave quotes on args when splitting, because we want | |
3668 | # unquoted args to eval in user_ns |
|
3667 | # unquoted args to eval in user_ns | |
3669 | cfg = Config() |
|
3668 | cfg = Config() | |
3670 | exec "cfg."+line in locals(), self.user_ns |
|
3669 | exec "cfg."+line in locals(), self.user_ns | |
3671 |
|
3670 | |||
3672 | for configurable in configurables: |
|
3671 | for configurable in configurables: | |
3673 | try: |
|
3672 | try: | |
3674 | configurable.update_config(cfg) |
|
3673 | configurable.update_config(cfg) | |
3675 | except Exception as e: |
|
3674 | except Exception as e: | |
3676 | error(e) |
|
3675 | error(e) | |
3677 |
|
3676 | |||
3678 | # end Magic |
|
3677 | # end Magic |
@@ -1,946 +1,946 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Prefiltering components. |
|
3 | Prefiltering components. | |
4 |
|
4 | |||
5 | Prefilters transform user input before it is exec'd by Python. These |
|
5 | Prefilters transform user input before it is exec'd by Python. These | |
6 | transforms are used to implement additional syntax such as !ls and %magic. |
|
6 | transforms are used to implement additional syntax such as !ls and %magic. | |
7 |
|
7 | |||
8 | Authors: |
|
8 | Authors: | |
9 |
|
9 | |||
10 | * Brian Granger |
|
10 | * Brian Granger | |
11 | * Fernando Perez |
|
11 | * Fernando Perez | |
12 | * Dan Milstein |
|
12 | * Dan Milstein | |
13 | * Ville Vainio |
|
13 | * Ville Vainio | |
14 | """ |
|
14 | """ | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Copyright (C) 2008-2011 The IPython Development Team |
|
17 | # Copyright (C) 2008-2011 The IPython Development Team | |
18 | # |
|
18 | # | |
19 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | # Distributed under the terms of the BSD License. The full license is in | |
20 | # the file COPYING, distributed as part of this software. |
|
20 | # the file COPYING, distributed as part of this software. | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 | # Imports |
|
24 | # Imports | |
25 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
26 |
|
26 | |||
27 | import __builtin__ |
|
27 | import __builtin__ | |
28 | import codeop |
|
28 | import codeop | |
29 | import re |
|
29 | import re | |
30 |
|
30 | |||
31 | from IPython.core.alias import AliasManager |
|
31 | from IPython.core.alias import AliasManager | |
32 | from IPython.core.autocall import IPyAutocall |
|
32 | from IPython.core.autocall import IPyAutocall | |
33 | from IPython.config.configurable import Configurable |
|
33 | from IPython.config.configurable import Configurable | |
34 | from IPython.core.macro import Macro |
|
34 | from IPython.core.macro import Macro | |
35 | from IPython.core.splitinput import split_user_input, LineInfo |
|
35 | from IPython.core.splitinput import split_user_input, LineInfo | |
36 | from IPython.core import page |
|
36 | from IPython.core import page | |
37 |
|
37 | |||
38 | from IPython.utils.traitlets import List, Integer, Any, Unicode, CBool, Bool, Instance |
|
38 | from IPython.utils.traitlets import List, Integer, Any, Unicode, CBool, Bool, Instance | |
39 | from IPython.utils.autoattr import auto_attr |
|
39 | from IPython.utils.autoattr import auto_attr | |
40 |
|
40 | |||
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 | # Global utilities, errors and constants |
|
42 | # Global utilities, errors and constants | |
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 |
|
44 | |||
45 | # Warning, these cannot be changed unless various regular expressions |
|
45 | # Warning, these cannot be changed unless various regular expressions | |
46 | # are updated in a number of places. Not great, but at least we told you. |
|
46 | # are updated in a number of places. Not great, but at least we told you. | |
47 | ESC_SHELL = '!' |
|
47 | ESC_SHELL = '!' | |
48 | ESC_SH_CAP = '!!' |
|
48 | ESC_SH_CAP = '!!' | |
49 | ESC_HELP = '?' |
|
49 | ESC_HELP = '?' | |
50 | ESC_MAGIC = '%' |
|
50 | ESC_MAGIC = '%' | |
51 | ESC_QUOTE = ',' |
|
51 | ESC_QUOTE = ',' | |
52 | ESC_QUOTE2 = ';' |
|
52 | ESC_QUOTE2 = ';' | |
53 | ESC_PAREN = '/' |
|
53 | ESC_PAREN = '/' | |
54 |
|
54 | |||
55 |
|
55 | |||
56 | class PrefilterError(Exception): |
|
56 | class PrefilterError(Exception): | |
57 | pass |
|
57 | pass | |
58 |
|
58 | |||
59 |
|
59 | |||
60 | # RegExp to identify potential function names |
|
60 | # RegExp to identify potential function names | |
61 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
61 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
62 |
|
62 | |||
63 | # RegExp to exclude strings with this start from autocalling. In |
|
63 | # RegExp to exclude strings with this start from autocalling. In | |
64 | # particular, all binary operators should be excluded, so that if foo is |
|
64 | # particular, all binary operators should be excluded, so that if foo is | |
65 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
65 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The | |
66 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
66 | # characters '!=()' don't need to be checked for, as the checkPythonChars | |
67 | # routine explicitely does so, to catch direct calls and rebindings of |
|
67 | # routine explicitely does so, to catch direct calls and rebindings of | |
68 | # existing names. |
|
68 | # existing names. | |
69 |
|
69 | |||
70 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
70 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
71 | # it affects the rest of the group in square brackets. |
|
71 | # it affects the rest of the group in square brackets. | |
72 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
72 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' | |
73 | r'|^is |^not |^in |^and |^or ') |
|
73 | r'|^is |^not |^in |^and |^or ') | |
74 |
|
74 | |||
75 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
75 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
76 | # (experimental). For this to work, the line_split regexp would need |
|
76 | # (experimental). For this to work, the line_split regexp would need | |
77 | # to be modified so it wouldn't break things at '['. That line is |
|
77 | # to be modified so it wouldn't break things at '['. That line is | |
78 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
78 | # nasty enough that I shouldn't change it until I can test it _well_. | |
79 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
79 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
80 |
|
80 | |||
81 |
|
81 | |||
82 | # Handler Check Utilities |
|
82 | # Handler Check Utilities | |
83 | def is_shadowed(identifier, ip): |
|
83 | def is_shadowed(identifier, ip): | |
84 | """Is the given identifier defined in one of the namespaces which shadow |
|
84 | """Is the given identifier defined in one of the namespaces which shadow | |
85 | the alias and magic namespaces? Note that an identifier is different |
|
85 | the alias and magic namespaces? Note that an identifier is different | |
86 | than ifun, because it can not contain a '.' character.""" |
|
86 | than ifun, because it can not contain a '.' character.""" | |
87 | # This is much safer than calling ofind, which can change state |
|
87 | # This is much safer than calling ofind, which can change state | |
88 | return (identifier in ip.user_ns \ |
|
88 | return (identifier in ip.user_ns \ | |
89 |
or identifier in ip. |
|
89 | or identifier in ip.user_global_ns \ | |
90 | or identifier in ip.ns_table['builtin']) |
|
90 | or identifier in ip.ns_table['builtin']) | |
91 |
|
91 | |||
92 |
|
92 | |||
93 | #----------------------------------------------------------------------------- |
|
93 | #----------------------------------------------------------------------------- | |
94 | # Main Prefilter manager |
|
94 | # Main Prefilter manager | |
95 | #----------------------------------------------------------------------------- |
|
95 | #----------------------------------------------------------------------------- | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | class PrefilterManager(Configurable): |
|
98 | class PrefilterManager(Configurable): | |
99 | """Main prefilter component. |
|
99 | """Main prefilter component. | |
100 |
|
100 | |||
101 | The IPython prefilter is run on all user input before it is run. The |
|
101 | The IPython prefilter is run on all user input before it is run. The | |
102 | prefilter consumes lines of input and produces transformed lines of |
|
102 | prefilter consumes lines of input and produces transformed lines of | |
103 | input. |
|
103 | input. | |
104 |
|
104 | |||
105 | The iplementation consists of two phases: |
|
105 | The iplementation consists of two phases: | |
106 |
|
106 | |||
107 | 1. Transformers |
|
107 | 1. Transformers | |
108 | 2. Checkers and handlers |
|
108 | 2. Checkers and handlers | |
109 |
|
109 | |||
110 | Over time, we plan on deprecating the checkers and handlers and doing |
|
110 | Over time, we plan on deprecating the checkers and handlers and doing | |
111 | everything in the transformers. |
|
111 | everything in the transformers. | |
112 |
|
112 | |||
113 | The transformers are instances of :class:`PrefilterTransformer` and have |
|
113 | The transformers are instances of :class:`PrefilterTransformer` and have | |
114 | a single method :meth:`transform` that takes a line and returns a |
|
114 | a single method :meth:`transform` that takes a line and returns a | |
115 | transformed line. The transformation can be accomplished using any |
|
115 | transformed line. The transformation can be accomplished using any | |
116 | tool, but our current ones use regular expressions for speed. We also |
|
116 | tool, but our current ones use regular expressions for speed. We also | |
117 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. |
|
117 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. | |
118 |
|
118 | |||
119 | After all the transformers have been run, the line is fed to the checkers, |
|
119 | After all the transformers have been run, the line is fed to the checkers, | |
120 | which are instances of :class:`PrefilterChecker`. The line is passed to |
|
120 | which are instances of :class:`PrefilterChecker`. The line is passed to | |
121 | the :meth:`check` method, which either returns `None` or a |
|
121 | the :meth:`check` method, which either returns `None` or a | |
122 | :class:`PrefilterHandler` instance. If `None` is returned, the other |
|
122 | :class:`PrefilterHandler` instance. If `None` is returned, the other | |
123 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, |
|
123 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, | |
124 | the line is passed to the :meth:`handle` method of the returned |
|
124 | the line is passed to the :meth:`handle` method of the returned | |
125 | handler and no further checkers are tried. |
|
125 | handler and no further checkers are tried. | |
126 |
|
126 | |||
127 | Both transformers and checkers have a `priority` attribute, that determines |
|
127 | Both transformers and checkers have a `priority` attribute, that determines | |
128 | the order in which they are called. Smaller priorities are tried first. |
|
128 | the order in which they are called. Smaller priorities are tried first. | |
129 |
|
129 | |||
130 | Both transformers and checkers also have `enabled` attribute, which is |
|
130 | Both transformers and checkers also have `enabled` attribute, which is | |
131 | a boolean that determines if the instance is used. |
|
131 | a boolean that determines if the instance is used. | |
132 |
|
132 | |||
133 | Users or developers can change the priority or enabled attribute of |
|
133 | Users or developers can change the priority or enabled attribute of | |
134 | transformers or checkers, but they must call the :meth:`sort_checkers` |
|
134 | transformers or checkers, but they must call the :meth:`sort_checkers` | |
135 | or :meth:`sort_transformers` method after changing the priority. |
|
135 | or :meth:`sort_transformers` method after changing the priority. | |
136 | """ |
|
136 | """ | |
137 |
|
137 | |||
138 | multi_line_specials = CBool(True, config=True) |
|
138 | multi_line_specials = CBool(True, config=True) | |
139 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
139 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
140 |
|
140 | |||
141 | def __init__(self, shell=None, config=None): |
|
141 | def __init__(self, shell=None, config=None): | |
142 | super(PrefilterManager, self).__init__(shell=shell, config=config) |
|
142 | super(PrefilterManager, self).__init__(shell=shell, config=config) | |
143 | self.shell = shell |
|
143 | self.shell = shell | |
144 | self.init_transformers() |
|
144 | self.init_transformers() | |
145 | self.init_handlers() |
|
145 | self.init_handlers() | |
146 | self.init_checkers() |
|
146 | self.init_checkers() | |
147 |
|
147 | |||
148 | #------------------------------------------------------------------------- |
|
148 | #------------------------------------------------------------------------- | |
149 | # API for managing transformers |
|
149 | # API for managing transformers | |
150 | #------------------------------------------------------------------------- |
|
150 | #------------------------------------------------------------------------- | |
151 |
|
151 | |||
152 | def init_transformers(self): |
|
152 | def init_transformers(self): | |
153 | """Create the default transformers.""" |
|
153 | """Create the default transformers.""" | |
154 | self._transformers = [] |
|
154 | self._transformers = [] | |
155 | for transformer_cls in _default_transformers: |
|
155 | for transformer_cls in _default_transformers: | |
156 | transformer_cls( |
|
156 | transformer_cls( | |
157 | shell=self.shell, prefilter_manager=self, config=self.config |
|
157 | shell=self.shell, prefilter_manager=self, config=self.config | |
158 | ) |
|
158 | ) | |
159 |
|
159 | |||
160 | def sort_transformers(self): |
|
160 | def sort_transformers(self): | |
161 | """Sort the transformers by priority. |
|
161 | """Sort the transformers by priority. | |
162 |
|
162 | |||
163 | This must be called after the priority of a transformer is changed. |
|
163 | This must be called after the priority of a transformer is changed. | |
164 | The :meth:`register_transformer` method calls this automatically. |
|
164 | The :meth:`register_transformer` method calls this automatically. | |
165 | """ |
|
165 | """ | |
166 | self._transformers.sort(key=lambda x: x.priority) |
|
166 | self._transformers.sort(key=lambda x: x.priority) | |
167 |
|
167 | |||
168 | @property |
|
168 | @property | |
169 | def transformers(self): |
|
169 | def transformers(self): | |
170 | """Return a list of checkers, sorted by priority.""" |
|
170 | """Return a list of checkers, sorted by priority.""" | |
171 | return self._transformers |
|
171 | return self._transformers | |
172 |
|
172 | |||
173 | def register_transformer(self, transformer): |
|
173 | def register_transformer(self, transformer): | |
174 | """Register a transformer instance.""" |
|
174 | """Register a transformer instance.""" | |
175 | if transformer not in self._transformers: |
|
175 | if transformer not in self._transformers: | |
176 | self._transformers.append(transformer) |
|
176 | self._transformers.append(transformer) | |
177 | self.sort_transformers() |
|
177 | self.sort_transformers() | |
178 |
|
178 | |||
179 | def unregister_transformer(self, transformer): |
|
179 | def unregister_transformer(self, transformer): | |
180 | """Unregister a transformer instance.""" |
|
180 | """Unregister a transformer instance.""" | |
181 | if transformer in self._transformers: |
|
181 | if transformer in self._transformers: | |
182 | self._transformers.remove(transformer) |
|
182 | self._transformers.remove(transformer) | |
183 |
|
183 | |||
184 | #------------------------------------------------------------------------- |
|
184 | #------------------------------------------------------------------------- | |
185 | # API for managing checkers |
|
185 | # API for managing checkers | |
186 | #------------------------------------------------------------------------- |
|
186 | #------------------------------------------------------------------------- | |
187 |
|
187 | |||
188 | def init_checkers(self): |
|
188 | def init_checkers(self): | |
189 | """Create the default checkers.""" |
|
189 | """Create the default checkers.""" | |
190 | self._checkers = [] |
|
190 | self._checkers = [] | |
191 | for checker in _default_checkers: |
|
191 | for checker in _default_checkers: | |
192 | checker( |
|
192 | checker( | |
193 | shell=self.shell, prefilter_manager=self, config=self.config |
|
193 | shell=self.shell, prefilter_manager=self, config=self.config | |
194 | ) |
|
194 | ) | |
195 |
|
195 | |||
196 | def sort_checkers(self): |
|
196 | def sort_checkers(self): | |
197 | """Sort the checkers by priority. |
|
197 | """Sort the checkers by priority. | |
198 |
|
198 | |||
199 | This must be called after the priority of a checker is changed. |
|
199 | This must be called after the priority of a checker is changed. | |
200 | The :meth:`register_checker` method calls this automatically. |
|
200 | The :meth:`register_checker` method calls this automatically. | |
201 | """ |
|
201 | """ | |
202 | self._checkers.sort(key=lambda x: x.priority) |
|
202 | self._checkers.sort(key=lambda x: x.priority) | |
203 |
|
203 | |||
204 | @property |
|
204 | @property | |
205 | def checkers(self): |
|
205 | def checkers(self): | |
206 | """Return a list of checkers, sorted by priority.""" |
|
206 | """Return a list of checkers, sorted by priority.""" | |
207 | return self._checkers |
|
207 | return self._checkers | |
208 |
|
208 | |||
209 | def register_checker(self, checker): |
|
209 | def register_checker(self, checker): | |
210 | """Register a checker instance.""" |
|
210 | """Register a checker instance.""" | |
211 | if checker not in self._checkers: |
|
211 | if checker not in self._checkers: | |
212 | self._checkers.append(checker) |
|
212 | self._checkers.append(checker) | |
213 | self.sort_checkers() |
|
213 | self.sort_checkers() | |
214 |
|
214 | |||
215 | def unregister_checker(self, checker): |
|
215 | def unregister_checker(self, checker): | |
216 | """Unregister a checker instance.""" |
|
216 | """Unregister a checker instance.""" | |
217 | if checker in self._checkers: |
|
217 | if checker in self._checkers: | |
218 | self._checkers.remove(checker) |
|
218 | self._checkers.remove(checker) | |
219 |
|
219 | |||
220 | #------------------------------------------------------------------------- |
|
220 | #------------------------------------------------------------------------- | |
221 | # API for managing checkers |
|
221 | # API for managing checkers | |
222 | #------------------------------------------------------------------------- |
|
222 | #------------------------------------------------------------------------- | |
223 |
|
223 | |||
224 | def init_handlers(self): |
|
224 | def init_handlers(self): | |
225 | """Create the default handlers.""" |
|
225 | """Create the default handlers.""" | |
226 | self._handlers = {} |
|
226 | self._handlers = {} | |
227 | self._esc_handlers = {} |
|
227 | self._esc_handlers = {} | |
228 | for handler in _default_handlers: |
|
228 | for handler in _default_handlers: | |
229 | handler( |
|
229 | handler( | |
230 | shell=self.shell, prefilter_manager=self, config=self.config |
|
230 | shell=self.shell, prefilter_manager=self, config=self.config | |
231 | ) |
|
231 | ) | |
232 |
|
232 | |||
233 | @property |
|
233 | @property | |
234 | def handlers(self): |
|
234 | def handlers(self): | |
235 | """Return a dict of all the handlers.""" |
|
235 | """Return a dict of all the handlers.""" | |
236 | return self._handlers |
|
236 | return self._handlers | |
237 |
|
237 | |||
238 | def register_handler(self, name, handler, esc_strings): |
|
238 | def register_handler(self, name, handler, esc_strings): | |
239 | """Register a handler instance by name with esc_strings.""" |
|
239 | """Register a handler instance by name with esc_strings.""" | |
240 | self._handlers[name] = handler |
|
240 | self._handlers[name] = handler | |
241 | for esc_str in esc_strings: |
|
241 | for esc_str in esc_strings: | |
242 | self._esc_handlers[esc_str] = handler |
|
242 | self._esc_handlers[esc_str] = handler | |
243 |
|
243 | |||
244 | def unregister_handler(self, name, handler, esc_strings): |
|
244 | def unregister_handler(self, name, handler, esc_strings): | |
245 | """Unregister a handler instance by name with esc_strings.""" |
|
245 | """Unregister a handler instance by name with esc_strings.""" | |
246 | try: |
|
246 | try: | |
247 | del self._handlers[name] |
|
247 | del self._handlers[name] | |
248 | except KeyError: |
|
248 | except KeyError: | |
249 | pass |
|
249 | pass | |
250 | for esc_str in esc_strings: |
|
250 | for esc_str in esc_strings: | |
251 | h = self._esc_handlers.get(esc_str) |
|
251 | h = self._esc_handlers.get(esc_str) | |
252 | if h is handler: |
|
252 | if h is handler: | |
253 | del self._esc_handlers[esc_str] |
|
253 | del self._esc_handlers[esc_str] | |
254 |
|
254 | |||
255 | def get_handler_by_name(self, name): |
|
255 | def get_handler_by_name(self, name): | |
256 | """Get a handler by its name.""" |
|
256 | """Get a handler by its name.""" | |
257 | return self._handlers.get(name) |
|
257 | return self._handlers.get(name) | |
258 |
|
258 | |||
259 | def get_handler_by_esc(self, esc_str): |
|
259 | def get_handler_by_esc(self, esc_str): | |
260 | """Get a handler by its escape string.""" |
|
260 | """Get a handler by its escape string.""" | |
261 | return self._esc_handlers.get(esc_str) |
|
261 | return self._esc_handlers.get(esc_str) | |
262 |
|
262 | |||
263 | #------------------------------------------------------------------------- |
|
263 | #------------------------------------------------------------------------- | |
264 | # Main prefiltering API |
|
264 | # Main prefiltering API | |
265 | #------------------------------------------------------------------------- |
|
265 | #------------------------------------------------------------------------- | |
266 |
|
266 | |||
267 | def prefilter_line_info(self, line_info): |
|
267 | def prefilter_line_info(self, line_info): | |
268 | """Prefilter a line that has been converted to a LineInfo object. |
|
268 | """Prefilter a line that has been converted to a LineInfo object. | |
269 |
|
269 | |||
270 | This implements the checker/handler part of the prefilter pipe. |
|
270 | This implements the checker/handler part of the prefilter pipe. | |
271 | """ |
|
271 | """ | |
272 | # print "prefilter_line_info: ", line_info |
|
272 | # print "prefilter_line_info: ", line_info | |
273 | handler = self.find_handler(line_info) |
|
273 | handler = self.find_handler(line_info) | |
274 | return handler.handle(line_info) |
|
274 | return handler.handle(line_info) | |
275 |
|
275 | |||
276 | def find_handler(self, line_info): |
|
276 | def find_handler(self, line_info): | |
277 | """Find a handler for the line_info by trying checkers.""" |
|
277 | """Find a handler for the line_info by trying checkers.""" | |
278 | for checker in self.checkers: |
|
278 | for checker in self.checkers: | |
279 | if checker.enabled: |
|
279 | if checker.enabled: | |
280 | handler = checker.check(line_info) |
|
280 | handler = checker.check(line_info) | |
281 | if handler: |
|
281 | if handler: | |
282 | return handler |
|
282 | return handler | |
283 | return self.get_handler_by_name('normal') |
|
283 | return self.get_handler_by_name('normal') | |
284 |
|
284 | |||
285 | def transform_line(self, line, continue_prompt): |
|
285 | def transform_line(self, line, continue_prompt): | |
286 | """Calls the enabled transformers in order of increasing priority.""" |
|
286 | """Calls the enabled transformers in order of increasing priority.""" | |
287 | for transformer in self.transformers: |
|
287 | for transformer in self.transformers: | |
288 | if transformer.enabled: |
|
288 | if transformer.enabled: | |
289 | line = transformer.transform(line, continue_prompt) |
|
289 | line = transformer.transform(line, continue_prompt) | |
290 | return line |
|
290 | return line | |
291 |
|
291 | |||
292 | def prefilter_line(self, line, continue_prompt=False): |
|
292 | def prefilter_line(self, line, continue_prompt=False): | |
293 | """Prefilter a single input line as text. |
|
293 | """Prefilter a single input line as text. | |
294 |
|
294 | |||
295 | This method prefilters a single line of text by calling the |
|
295 | This method prefilters a single line of text by calling the | |
296 | transformers and then the checkers/handlers. |
|
296 | transformers and then the checkers/handlers. | |
297 | """ |
|
297 | """ | |
298 |
|
298 | |||
299 | # print "prefilter_line: ", line, continue_prompt |
|
299 | # print "prefilter_line: ", line, continue_prompt | |
300 | # All handlers *must* return a value, even if it's blank (''). |
|
300 | # All handlers *must* return a value, even if it's blank (''). | |
301 |
|
301 | |||
302 | # save the line away in case we crash, so the post-mortem handler can |
|
302 | # save the line away in case we crash, so the post-mortem handler can | |
303 | # record it |
|
303 | # record it | |
304 | self.shell._last_input_line = line |
|
304 | self.shell._last_input_line = line | |
305 |
|
305 | |||
306 | if not line: |
|
306 | if not line: | |
307 | # Return immediately on purely empty lines, so that if the user |
|
307 | # Return immediately on purely empty lines, so that if the user | |
308 | # previously typed some whitespace that started a continuation |
|
308 | # previously typed some whitespace that started a continuation | |
309 | # prompt, he can break out of that loop with just an empty line. |
|
309 | # prompt, he can break out of that loop with just an empty line. | |
310 | # This is how the default python prompt works. |
|
310 | # This is how the default python prompt works. | |
311 | return '' |
|
311 | return '' | |
312 |
|
312 | |||
313 | # At this point, we invoke our transformers. |
|
313 | # At this point, we invoke our transformers. | |
314 | if not continue_prompt or (continue_prompt and self.multi_line_specials): |
|
314 | if not continue_prompt or (continue_prompt and self.multi_line_specials): | |
315 | line = self.transform_line(line, continue_prompt) |
|
315 | line = self.transform_line(line, continue_prompt) | |
316 |
|
316 | |||
317 | # Now we compute line_info for the checkers and handlers |
|
317 | # Now we compute line_info for the checkers and handlers | |
318 | line_info = LineInfo(line, continue_prompt) |
|
318 | line_info = LineInfo(line, continue_prompt) | |
319 |
|
319 | |||
320 | # the input history needs to track even empty lines |
|
320 | # the input history needs to track even empty lines | |
321 | stripped = line.strip() |
|
321 | stripped = line.strip() | |
322 |
|
322 | |||
323 | normal_handler = self.get_handler_by_name('normal') |
|
323 | normal_handler = self.get_handler_by_name('normal') | |
324 | if not stripped: |
|
324 | if not stripped: | |
325 | if not continue_prompt: |
|
325 | if not continue_prompt: | |
326 | self.shell.displayhook.prompt_count -= 1 |
|
326 | self.shell.displayhook.prompt_count -= 1 | |
327 |
|
327 | |||
328 | return normal_handler.handle(line_info) |
|
328 | return normal_handler.handle(line_info) | |
329 |
|
329 | |||
330 | # special handlers are only allowed for single line statements |
|
330 | # special handlers are only allowed for single line statements | |
331 | if continue_prompt and not self.multi_line_specials: |
|
331 | if continue_prompt and not self.multi_line_specials: | |
332 | return normal_handler.handle(line_info) |
|
332 | return normal_handler.handle(line_info) | |
333 |
|
333 | |||
334 | prefiltered = self.prefilter_line_info(line_info) |
|
334 | prefiltered = self.prefilter_line_info(line_info) | |
335 | # print "prefiltered line: %r" % prefiltered |
|
335 | # print "prefiltered line: %r" % prefiltered | |
336 | return prefiltered |
|
336 | return prefiltered | |
337 |
|
337 | |||
338 | def prefilter_lines(self, lines, continue_prompt=False): |
|
338 | def prefilter_lines(self, lines, continue_prompt=False): | |
339 | """Prefilter multiple input lines of text. |
|
339 | """Prefilter multiple input lines of text. | |
340 |
|
340 | |||
341 | This is the main entry point for prefiltering multiple lines of |
|
341 | This is the main entry point for prefiltering multiple lines of | |
342 | input. This simply calls :meth:`prefilter_line` for each line of |
|
342 | input. This simply calls :meth:`prefilter_line` for each line of | |
343 | input. |
|
343 | input. | |
344 |
|
344 | |||
345 | This covers cases where there are multiple lines in the user entry, |
|
345 | This covers cases where there are multiple lines in the user entry, | |
346 | which is the case when the user goes back to a multiline history |
|
346 | which is the case when the user goes back to a multiline history | |
347 | entry and presses enter. |
|
347 | entry and presses enter. | |
348 | """ |
|
348 | """ | |
349 | llines = lines.rstrip('\n').split('\n') |
|
349 | llines = lines.rstrip('\n').split('\n') | |
350 | # We can get multiple lines in one shot, where multiline input 'blends' |
|
350 | # We can get multiple lines in one shot, where multiline input 'blends' | |
351 | # into one line, in cases like recalling from the readline history |
|
351 | # into one line, in cases like recalling from the readline history | |
352 | # buffer. We need to make sure that in such cases, we correctly |
|
352 | # buffer. We need to make sure that in such cases, we correctly | |
353 | # communicate downstream which line is first and which are continuation |
|
353 | # communicate downstream which line is first and which are continuation | |
354 | # ones. |
|
354 | # ones. | |
355 | if len(llines) > 1: |
|
355 | if len(llines) > 1: | |
356 | out = '\n'.join([self.prefilter_line(line, lnum>0) |
|
356 | out = '\n'.join([self.prefilter_line(line, lnum>0) | |
357 | for lnum, line in enumerate(llines) ]) |
|
357 | for lnum, line in enumerate(llines) ]) | |
358 | else: |
|
358 | else: | |
359 | out = self.prefilter_line(llines[0], continue_prompt) |
|
359 | out = self.prefilter_line(llines[0], continue_prompt) | |
360 |
|
360 | |||
361 | return out |
|
361 | return out | |
362 |
|
362 | |||
363 | #----------------------------------------------------------------------------- |
|
363 | #----------------------------------------------------------------------------- | |
364 | # Prefilter transformers |
|
364 | # Prefilter transformers | |
365 | #----------------------------------------------------------------------------- |
|
365 | #----------------------------------------------------------------------------- | |
366 |
|
366 | |||
367 |
|
367 | |||
368 | class PrefilterTransformer(Configurable): |
|
368 | class PrefilterTransformer(Configurable): | |
369 | """Transform a line of user input.""" |
|
369 | """Transform a line of user input.""" | |
370 |
|
370 | |||
371 | priority = Integer(100, config=True) |
|
371 | priority = Integer(100, config=True) | |
372 | # Transformers don't currently use shell or prefilter_manager, but as we |
|
372 | # Transformers don't currently use shell or prefilter_manager, but as we | |
373 | # move away from checkers and handlers, they will need them. |
|
373 | # move away from checkers and handlers, they will need them. | |
374 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
374 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
375 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
375 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
376 | enabled = Bool(True, config=True) |
|
376 | enabled = Bool(True, config=True) | |
377 |
|
377 | |||
378 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
378 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
379 | super(PrefilterTransformer, self).__init__( |
|
379 | super(PrefilterTransformer, self).__init__( | |
380 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
380 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
381 | ) |
|
381 | ) | |
382 | self.prefilter_manager.register_transformer(self) |
|
382 | self.prefilter_manager.register_transformer(self) | |
383 |
|
383 | |||
384 | def transform(self, line, continue_prompt): |
|
384 | def transform(self, line, continue_prompt): | |
385 | """Transform a line, returning the new one.""" |
|
385 | """Transform a line, returning the new one.""" | |
386 | return None |
|
386 | return None | |
387 |
|
387 | |||
388 | def __repr__(self): |
|
388 | def __repr__(self): | |
389 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
389 | return "<%s(priority=%r, enabled=%r)>" % ( | |
390 | self.__class__.__name__, self.priority, self.enabled) |
|
390 | self.__class__.__name__, self.priority, self.enabled) | |
391 |
|
391 | |||
392 |
|
392 | |||
393 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
393 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
394 | r'\s*=\s*!(?P<cmd>.*)') |
|
394 | r'\s*=\s*!(?P<cmd>.*)') | |
395 |
|
395 | |||
396 |
|
396 | |||
397 | class AssignSystemTransformer(PrefilterTransformer): |
|
397 | class AssignSystemTransformer(PrefilterTransformer): | |
398 | """Handle the `files = !ls` syntax.""" |
|
398 | """Handle the `files = !ls` syntax.""" | |
399 |
|
399 | |||
400 | priority = Integer(100, config=True) |
|
400 | priority = Integer(100, config=True) | |
401 |
|
401 | |||
402 | def transform(self, line, continue_prompt): |
|
402 | def transform(self, line, continue_prompt): | |
403 | m = _assign_system_re.match(line) |
|
403 | m = _assign_system_re.match(line) | |
404 | if m is not None: |
|
404 | if m is not None: | |
405 | cmd = m.group('cmd') |
|
405 | cmd = m.group('cmd') | |
406 | lhs = m.group('lhs') |
|
406 | lhs = m.group('lhs') | |
407 | expr = "sc =%s" % cmd |
|
407 | expr = "sc =%s" % cmd | |
408 | new_line = '%s = get_ipython().magic(%r)' % (lhs, expr) |
|
408 | new_line = '%s = get_ipython().magic(%r)' % (lhs, expr) | |
409 | return new_line |
|
409 | return new_line | |
410 | return line |
|
410 | return line | |
411 |
|
411 | |||
412 |
|
412 | |||
413 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
413 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
414 | r'\s*=\s*%(?P<cmd>.*)') |
|
414 | r'\s*=\s*%(?P<cmd>.*)') | |
415 |
|
415 | |||
416 | class AssignMagicTransformer(PrefilterTransformer): |
|
416 | class AssignMagicTransformer(PrefilterTransformer): | |
417 | """Handle the `a = %who` syntax.""" |
|
417 | """Handle the `a = %who` syntax.""" | |
418 |
|
418 | |||
419 | priority = Integer(200, config=True) |
|
419 | priority = Integer(200, config=True) | |
420 |
|
420 | |||
421 | def transform(self, line, continue_prompt): |
|
421 | def transform(self, line, continue_prompt): | |
422 | m = _assign_magic_re.match(line) |
|
422 | m = _assign_magic_re.match(line) | |
423 | if m is not None: |
|
423 | if m is not None: | |
424 | cmd = m.group('cmd') |
|
424 | cmd = m.group('cmd') | |
425 | lhs = m.group('lhs') |
|
425 | lhs = m.group('lhs') | |
426 | new_line = '%s = get_ipython().magic(%r)' % (lhs, cmd) |
|
426 | new_line = '%s = get_ipython().magic(%r)' % (lhs, cmd) | |
427 | return new_line |
|
427 | return new_line | |
428 | return line |
|
428 | return line | |
429 |
|
429 | |||
430 |
|
430 | |||
431 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') |
|
431 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') | |
432 |
|
432 | |||
433 | class PyPromptTransformer(PrefilterTransformer): |
|
433 | class PyPromptTransformer(PrefilterTransformer): | |
434 | """Handle inputs that start with '>>> ' syntax.""" |
|
434 | """Handle inputs that start with '>>> ' syntax.""" | |
435 |
|
435 | |||
436 | priority = Integer(50, config=True) |
|
436 | priority = Integer(50, config=True) | |
437 |
|
437 | |||
438 | def transform(self, line, continue_prompt): |
|
438 | def transform(self, line, continue_prompt): | |
439 |
|
439 | |||
440 | if not line or line.isspace() or line.strip() == '...': |
|
440 | if not line or line.isspace() or line.strip() == '...': | |
441 | # This allows us to recognize multiple input prompts separated by |
|
441 | # This allows us to recognize multiple input prompts separated by | |
442 | # blank lines and pasted in a single chunk, very common when |
|
442 | # blank lines and pasted in a single chunk, very common when | |
443 | # pasting doctests or long tutorial passages. |
|
443 | # pasting doctests or long tutorial passages. | |
444 | return '' |
|
444 | return '' | |
445 | m = _classic_prompt_re.match(line) |
|
445 | m = _classic_prompt_re.match(line) | |
446 | if m: |
|
446 | if m: | |
447 | return line[len(m.group(0)):] |
|
447 | return line[len(m.group(0)):] | |
448 | else: |
|
448 | else: | |
449 | return line |
|
449 | return line | |
450 |
|
450 | |||
451 |
|
451 | |||
452 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') |
|
452 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') | |
453 |
|
453 | |||
454 | class IPyPromptTransformer(PrefilterTransformer): |
|
454 | class IPyPromptTransformer(PrefilterTransformer): | |
455 | """Handle inputs that start classic IPython prompt syntax.""" |
|
455 | """Handle inputs that start classic IPython prompt syntax.""" | |
456 |
|
456 | |||
457 | priority = Integer(50, config=True) |
|
457 | priority = Integer(50, config=True) | |
458 |
|
458 | |||
459 | def transform(self, line, continue_prompt): |
|
459 | def transform(self, line, continue_prompt): | |
460 |
|
460 | |||
461 | if not line or line.isspace() or line.strip() == '...': |
|
461 | if not line or line.isspace() or line.strip() == '...': | |
462 | # This allows us to recognize multiple input prompts separated by |
|
462 | # This allows us to recognize multiple input prompts separated by | |
463 | # blank lines and pasted in a single chunk, very common when |
|
463 | # blank lines and pasted in a single chunk, very common when | |
464 | # pasting doctests or long tutorial passages. |
|
464 | # pasting doctests or long tutorial passages. | |
465 | return '' |
|
465 | return '' | |
466 | m = _ipy_prompt_re.match(line) |
|
466 | m = _ipy_prompt_re.match(line) | |
467 | if m: |
|
467 | if m: | |
468 | return line[len(m.group(0)):] |
|
468 | return line[len(m.group(0)):] | |
469 | else: |
|
469 | else: | |
470 | return line |
|
470 | return line | |
471 |
|
471 | |||
472 | #----------------------------------------------------------------------------- |
|
472 | #----------------------------------------------------------------------------- | |
473 | # Prefilter checkers |
|
473 | # Prefilter checkers | |
474 | #----------------------------------------------------------------------------- |
|
474 | #----------------------------------------------------------------------------- | |
475 |
|
475 | |||
476 |
|
476 | |||
477 | class PrefilterChecker(Configurable): |
|
477 | class PrefilterChecker(Configurable): | |
478 | """Inspect an input line and return a handler for that line.""" |
|
478 | """Inspect an input line and return a handler for that line.""" | |
479 |
|
479 | |||
480 | priority = Integer(100, config=True) |
|
480 | priority = Integer(100, config=True) | |
481 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
481 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
482 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
482 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
483 | enabled = Bool(True, config=True) |
|
483 | enabled = Bool(True, config=True) | |
484 |
|
484 | |||
485 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
485 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
486 | super(PrefilterChecker, self).__init__( |
|
486 | super(PrefilterChecker, self).__init__( | |
487 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
487 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
488 | ) |
|
488 | ) | |
489 | self.prefilter_manager.register_checker(self) |
|
489 | self.prefilter_manager.register_checker(self) | |
490 |
|
490 | |||
491 | def check(self, line_info): |
|
491 | def check(self, line_info): | |
492 | """Inspect line_info and return a handler instance or None.""" |
|
492 | """Inspect line_info and return a handler instance or None.""" | |
493 | return None |
|
493 | return None | |
494 |
|
494 | |||
495 | def __repr__(self): |
|
495 | def __repr__(self): | |
496 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
496 | return "<%s(priority=%r, enabled=%r)>" % ( | |
497 | self.__class__.__name__, self.priority, self.enabled) |
|
497 | self.__class__.__name__, self.priority, self.enabled) | |
498 |
|
498 | |||
499 |
|
499 | |||
500 | class EmacsChecker(PrefilterChecker): |
|
500 | class EmacsChecker(PrefilterChecker): | |
501 |
|
501 | |||
502 | priority = Integer(100, config=True) |
|
502 | priority = Integer(100, config=True) | |
503 | enabled = Bool(False, config=True) |
|
503 | enabled = Bool(False, config=True) | |
504 |
|
504 | |||
505 | def check(self, line_info): |
|
505 | def check(self, line_info): | |
506 | "Emacs ipython-mode tags certain input lines." |
|
506 | "Emacs ipython-mode tags certain input lines." | |
507 | if line_info.line.endswith('# PYTHON-MODE'): |
|
507 | if line_info.line.endswith('# PYTHON-MODE'): | |
508 | return self.prefilter_manager.get_handler_by_name('emacs') |
|
508 | return self.prefilter_manager.get_handler_by_name('emacs') | |
509 | else: |
|
509 | else: | |
510 | return None |
|
510 | return None | |
511 |
|
511 | |||
512 |
|
512 | |||
513 | class ShellEscapeChecker(PrefilterChecker): |
|
513 | class ShellEscapeChecker(PrefilterChecker): | |
514 |
|
514 | |||
515 | priority = Integer(200, config=True) |
|
515 | priority = Integer(200, config=True) | |
516 |
|
516 | |||
517 | def check(self, line_info): |
|
517 | def check(self, line_info): | |
518 | if line_info.line.lstrip().startswith(ESC_SHELL): |
|
518 | if line_info.line.lstrip().startswith(ESC_SHELL): | |
519 | return self.prefilter_manager.get_handler_by_name('shell') |
|
519 | return self.prefilter_manager.get_handler_by_name('shell') | |
520 |
|
520 | |||
521 |
|
521 | |||
522 | class MacroChecker(PrefilterChecker): |
|
522 | class MacroChecker(PrefilterChecker): | |
523 |
|
523 | |||
524 | priority = Integer(250, config=True) |
|
524 | priority = Integer(250, config=True) | |
525 |
|
525 | |||
526 | def check(self, line_info): |
|
526 | def check(self, line_info): | |
527 | obj = self.shell.user_ns.get(line_info.ifun) |
|
527 | obj = self.shell.user_ns.get(line_info.ifun) | |
528 | if isinstance(obj, Macro): |
|
528 | if isinstance(obj, Macro): | |
529 | return self.prefilter_manager.get_handler_by_name('macro') |
|
529 | return self.prefilter_manager.get_handler_by_name('macro') | |
530 | else: |
|
530 | else: | |
531 | return None |
|
531 | return None | |
532 |
|
532 | |||
533 |
|
533 | |||
534 | class IPyAutocallChecker(PrefilterChecker): |
|
534 | class IPyAutocallChecker(PrefilterChecker): | |
535 |
|
535 | |||
536 | priority = Integer(300, config=True) |
|
536 | priority = Integer(300, config=True) | |
537 |
|
537 | |||
538 | def check(self, line_info): |
|
538 | def check(self, line_info): | |
539 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
539 | "Instances of IPyAutocall in user_ns get autocalled immediately" | |
540 | obj = self.shell.user_ns.get(line_info.ifun, None) |
|
540 | obj = self.shell.user_ns.get(line_info.ifun, None) | |
541 | if isinstance(obj, IPyAutocall): |
|
541 | if isinstance(obj, IPyAutocall): | |
542 | obj.set_ip(self.shell) |
|
542 | obj.set_ip(self.shell) | |
543 | return self.prefilter_manager.get_handler_by_name('auto') |
|
543 | return self.prefilter_manager.get_handler_by_name('auto') | |
544 | else: |
|
544 | else: | |
545 | return None |
|
545 | return None | |
546 |
|
546 | |||
547 |
|
547 | |||
548 | class MultiLineMagicChecker(PrefilterChecker): |
|
548 | class MultiLineMagicChecker(PrefilterChecker): | |
549 |
|
549 | |||
550 | priority = Integer(400, config=True) |
|
550 | priority = Integer(400, config=True) | |
551 |
|
551 | |||
552 | def check(self, line_info): |
|
552 | def check(self, line_info): | |
553 | "Allow ! and !! in multi-line statements if multi_line_specials is on" |
|
553 | "Allow ! and !! in multi-line statements if multi_line_specials is on" | |
554 | # Note that this one of the only places we check the first character of |
|
554 | # Note that this one of the only places we check the first character of | |
555 | # ifun and *not* the pre_char. Also note that the below test matches |
|
555 | # ifun and *not* the pre_char. Also note that the below test matches | |
556 | # both ! and !!. |
|
556 | # both ! and !!. | |
557 | if line_info.continue_prompt \ |
|
557 | if line_info.continue_prompt \ | |
558 | and self.prefilter_manager.multi_line_specials: |
|
558 | and self.prefilter_manager.multi_line_specials: | |
559 | if line_info.esc == ESC_MAGIC: |
|
559 | if line_info.esc == ESC_MAGIC: | |
560 | return self.prefilter_manager.get_handler_by_name('magic') |
|
560 | return self.prefilter_manager.get_handler_by_name('magic') | |
561 | else: |
|
561 | else: | |
562 | return None |
|
562 | return None | |
563 |
|
563 | |||
564 |
|
564 | |||
565 | class EscCharsChecker(PrefilterChecker): |
|
565 | class EscCharsChecker(PrefilterChecker): | |
566 |
|
566 | |||
567 | priority = Integer(500, config=True) |
|
567 | priority = Integer(500, config=True) | |
568 |
|
568 | |||
569 | def check(self, line_info): |
|
569 | def check(self, line_info): | |
570 | """Check for escape character and return either a handler to handle it, |
|
570 | """Check for escape character and return either a handler to handle it, | |
571 | or None if there is no escape char.""" |
|
571 | or None if there is no escape char.""" | |
572 | if line_info.line[-1] == ESC_HELP \ |
|
572 | if line_info.line[-1] == ESC_HELP \ | |
573 | and line_info.esc != ESC_SHELL \ |
|
573 | and line_info.esc != ESC_SHELL \ | |
574 | and line_info.esc != ESC_SH_CAP: |
|
574 | and line_info.esc != ESC_SH_CAP: | |
575 | # the ? can be at the end, but *not* for either kind of shell escape, |
|
575 | # the ? can be at the end, but *not* for either kind of shell escape, | |
576 | # because a ? can be a vaild final char in a shell cmd |
|
576 | # because a ? can be a vaild final char in a shell cmd | |
577 | return self.prefilter_manager.get_handler_by_name('help') |
|
577 | return self.prefilter_manager.get_handler_by_name('help') | |
578 | else: |
|
578 | else: | |
579 | if line_info.pre: |
|
579 | if line_info.pre: | |
580 | return None |
|
580 | return None | |
581 | # This returns None like it should if no handler exists |
|
581 | # This returns None like it should if no handler exists | |
582 | return self.prefilter_manager.get_handler_by_esc(line_info.esc) |
|
582 | return self.prefilter_manager.get_handler_by_esc(line_info.esc) | |
583 |
|
583 | |||
584 |
|
584 | |||
585 | class AssignmentChecker(PrefilterChecker): |
|
585 | class AssignmentChecker(PrefilterChecker): | |
586 |
|
586 | |||
587 | priority = Integer(600, config=True) |
|
587 | priority = Integer(600, config=True) | |
588 |
|
588 | |||
589 | def check(self, line_info): |
|
589 | def check(self, line_info): | |
590 | """Check to see if user is assigning to a var for the first time, in |
|
590 | """Check to see if user is assigning to a var for the first time, in | |
591 | which case we want to avoid any sort of automagic / autocall games. |
|
591 | which case we want to avoid any sort of automagic / autocall games. | |
592 |
|
592 | |||
593 | This allows users to assign to either alias or magic names true python |
|
593 | This allows users to assign to either alias or magic names true python | |
594 | variables (the magic/alias systems always take second seat to true |
|
594 | variables (the magic/alias systems always take second seat to true | |
595 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
595 | python code). E.g. ls='hi', or ls,that=1,2""" | |
596 | if line_info.the_rest: |
|
596 | if line_info.the_rest: | |
597 | if line_info.the_rest[0] in '=,': |
|
597 | if line_info.the_rest[0] in '=,': | |
598 | return self.prefilter_manager.get_handler_by_name('normal') |
|
598 | return self.prefilter_manager.get_handler_by_name('normal') | |
599 | else: |
|
599 | else: | |
600 | return None |
|
600 | return None | |
601 |
|
601 | |||
602 |
|
602 | |||
603 | class AutoMagicChecker(PrefilterChecker): |
|
603 | class AutoMagicChecker(PrefilterChecker): | |
604 |
|
604 | |||
605 | priority = Integer(700, config=True) |
|
605 | priority = Integer(700, config=True) | |
606 |
|
606 | |||
607 | def check(self, line_info): |
|
607 | def check(self, line_info): | |
608 | """If the ifun is magic, and automagic is on, run it. Note: normal, |
|
608 | """If the ifun is magic, and automagic is on, run it. Note: normal, | |
609 | non-auto magic would already have been triggered via '%' in |
|
609 | non-auto magic would already have been triggered via '%' in | |
610 | check_esc_chars. This just checks for automagic. Also, before |
|
610 | check_esc_chars. This just checks for automagic. Also, before | |
611 | triggering the magic handler, make sure that there is nothing in the |
|
611 | triggering the magic handler, make sure that there is nothing in the | |
612 | user namespace which could shadow it.""" |
|
612 | user namespace which could shadow it.""" | |
613 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): |
|
613 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): | |
614 | return None |
|
614 | return None | |
615 |
|
615 | |||
616 | # We have a likely magic method. Make sure we should actually call it. |
|
616 | # We have a likely magic method. Make sure we should actually call it. | |
617 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: |
|
617 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: | |
618 | return None |
|
618 | return None | |
619 |
|
619 | |||
620 | head = line_info.ifun.split('.',1)[0] |
|
620 | head = line_info.ifun.split('.',1)[0] | |
621 | if is_shadowed(head, self.shell): |
|
621 | if is_shadowed(head, self.shell): | |
622 | return None |
|
622 | return None | |
623 |
|
623 | |||
624 | return self.prefilter_manager.get_handler_by_name('magic') |
|
624 | return self.prefilter_manager.get_handler_by_name('magic') | |
625 |
|
625 | |||
626 |
|
626 | |||
627 | class AliasChecker(PrefilterChecker): |
|
627 | class AliasChecker(PrefilterChecker): | |
628 |
|
628 | |||
629 | priority = Integer(800, config=True) |
|
629 | priority = Integer(800, config=True) | |
630 |
|
630 | |||
631 | def check(self, line_info): |
|
631 | def check(self, line_info): | |
632 | "Check if the initital identifier on the line is an alias." |
|
632 | "Check if the initital identifier on the line is an alias." | |
633 | # Note: aliases can not contain '.' |
|
633 | # Note: aliases can not contain '.' | |
634 | head = line_info.ifun.split('.',1)[0] |
|
634 | head = line_info.ifun.split('.',1)[0] | |
635 | if line_info.ifun not in self.shell.alias_manager \ |
|
635 | if line_info.ifun not in self.shell.alias_manager \ | |
636 | or head not in self.shell.alias_manager \ |
|
636 | or head not in self.shell.alias_manager \ | |
637 | or is_shadowed(head, self.shell): |
|
637 | or is_shadowed(head, self.shell): | |
638 | return None |
|
638 | return None | |
639 |
|
639 | |||
640 | return self.prefilter_manager.get_handler_by_name('alias') |
|
640 | return self.prefilter_manager.get_handler_by_name('alias') | |
641 |
|
641 | |||
642 |
|
642 | |||
643 | class PythonOpsChecker(PrefilterChecker): |
|
643 | class PythonOpsChecker(PrefilterChecker): | |
644 |
|
644 | |||
645 | priority = Integer(900, config=True) |
|
645 | priority = Integer(900, config=True) | |
646 |
|
646 | |||
647 | def check(self, line_info): |
|
647 | def check(self, line_info): | |
648 | """If the 'rest' of the line begins with a function call or pretty much |
|
648 | """If the 'rest' of the line begins with a function call or pretty much | |
649 | any python operator, we should simply execute the line (regardless of |
|
649 | any python operator, we should simply execute the line (regardless of | |
650 | whether or not there's a possible autocall expansion). This avoids |
|
650 | whether or not there's a possible autocall expansion). This avoids | |
651 | spurious (and very confusing) geattr() accesses.""" |
|
651 | spurious (and very confusing) geattr() accesses.""" | |
652 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': |
|
652 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': | |
653 | return self.prefilter_manager.get_handler_by_name('normal') |
|
653 | return self.prefilter_manager.get_handler_by_name('normal') | |
654 | else: |
|
654 | else: | |
655 | return None |
|
655 | return None | |
656 |
|
656 | |||
657 |
|
657 | |||
658 | class AutocallChecker(PrefilterChecker): |
|
658 | class AutocallChecker(PrefilterChecker): | |
659 |
|
659 | |||
660 | priority = Integer(1000, config=True) |
|
660 | priority = Integer(1000, config=True) | |
661 |
|
661 | |||
662 | def check(self, line_info): |
|
662 | def check(self, line_info): | |
663 | "Check if the initial word/function is callable and autocall is on." |
|
663 | "Check if the initial word/function is callable and autocall is on." | |
664 | if not self.shell.autocall: |
|
664 | if not self.shell.autocall: | |
665 | return None |
|
665 | return None | |
666 |
|
666 | |||
667 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr |
|
667 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr | |
668 | if not oinfo['found']: |
|
668 | if not oinfo['found']: | |
669 | return None |
|
669 | return None | |
670 |
|
670 | |||
671 | if callable(oinfo['obj']) \ |
|
671 | if callable(oinfo['obj']) \ | |
672 | and (not re_exclude_auto.match(line_info.the_rest)) \ |
|
672 | and (not re_exclude_auto.match(line_info.the_rest)) \ | |
673 | and re_fun_name.match(line_info.ifun): |
|
673 | and re_fun_name.match(line_info.ifun): | |
674 | return self.prefilter_manager.get_handler_by_name('auto') |
|
674 | return self.prefilter_manager.get_handler_by_name('auto') | |
675 | else: |
|
675 | else: | |
676 | return None |
|
676 | return None | |
677 |
|
677 | |||
678 |
|
678 | |||
679 | #----------------------------------------------------------------------------- |
|
679 | #----------------------------------------------------------------------------- | |
680 | # Prefilter handlers |
|
680 | # Prefilter handlers | |
681 | #----------------------------------------------------------------------------- |
|
681 | #----------------------------------------------------------------------------- | |
682 |
|
682 | |||
683 |
|
683 | |||
684 | class PrefilterHandler(Configurable): |
|
684 | class PrefilterHandler(Configurable): | |
685 |
|
685 | |||
686 | handler_name = Unicode('normal') |
|
686 | handler_name = Unicode('normal') | |
687 | esc_strings = List([]) |
|
687 | esc_strings = List([]) | |
688 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
688 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
689 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
689 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
690 |
|
690 | |||
691 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
691 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
692 | super(PrefilterHandler, self).__init__( |
|
692 | super(PrefilterHandler, self).__init__( | |
693 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
693 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
694 | ) |
|
694 | ) | |
695 | self.prefilter_manager.register_handler( |
|
695 | self.prefilter_manager.register_handler( | |
696 | self.handler_name, |
|
696 | self.handler_name, | |
697 | self, |
|
697 | self, | |
698 | self.esc_strings |
|
698 | self.esc_strings | |
699 | ) |
|
699 | ) | |
700 |
|
700 | |||
701 | def handle(self, line_info): |
|
701 | def handle(self, line_info): | |
702 | # print "normal: ", line_info |
|
702 | # print "normal: ", line_info | |
703 | """Handle normal input lines. Use as a template for handlers.""" |
|
703 | """Handle normal input lines. Use as a template for handlers.""" | |
704 |
|
704 | |||
705 | # With autoindent on, we need some way to exit the input loop, and I |
|
705 | # With autoindent on, we need some way to exit the input loop, and I | |
706 | # don't want to force the user to have to backspace all the way to |
|
706 | # don't want to force the user to have to backspace all the way to | |
707 | # clear the line. The rule will be in this case, that either two |
|
707 | # clear the line. The rule will be in this case, that either two | |
708 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
708 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
709 | # of a size different to the indent level, will exit the input loop. |
|
709 | # of a size different to the indent level, will exit the input loop. | |
710 | line = line_info.line |
|
710 | line = line_info.line | |
711 | continue_prompt = line_info.continue_prompt |
|
711 | continue_prompt = line_info.continue_prompt | |
712 |
|
712 | |||
713 | if (continue_prompt and |
|
713 | if (continue_prompt and | |
714 | self.shell.autoindent and |
|
714 | self.shell.autoindent and | |
715 | line.isspace() and |
|
715 | line.isspace() and | |
716 | 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): |
|
716 | 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): | |
717 | line = '' |
|
717 | line = '' | |
718 |
|
718 | |||
719 | return line |
|
719 | return line | |
720 |
|
720 | |||
721 | def __str__(self): |
|
721 | def __str__(self): | |
722 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) |
|
722 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) | |
723 |
|
723 | |||
724 |
|
724 | |||
725 | class AliasHandler(PrefilterHandler): |
|
725 | class AliasHandler(PrefilterHandler): | |
726 |
|
726 | |||
727 | handler_name = Unicode('alias') |
|
727 | handler_name = Unicode('alias') | |
728 |
|
728 | |||
729 | def handle(self, line_info): |
|
729 | def handle(self, line_info): | |
730 | """Handle alias input lines. """ |
|
730 | """Handle alias input lines. """ | |
731 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) |
|
731 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) | |
732 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
732 | # pre is needed, because it carries the leading whitespace. Otherwise | |
733 | # aliases won't work in indented sections. |
|
733 | # aliases won't work in indented sections. | |
734 | line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed) |
|
734 | line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed) | |
735 |
|
735 | |||
736 | return line_out |
|
736 | return line_out | |
737 |
|
737 | |||
738 |
|
738 | |||
739 | class ShellEscapeHandler(PrefilterHandler): |
|
739 | class ShellEscapeHandler(PrefilterHandler): | |
740 |
|
740 | |||
741 | handler_name = Unicode('shell') |
|
741 | handler_name = Unicode('shell') | |
742 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) |
|
742 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) | |
743 |
|
743 | |||
744 | def handle(self, line_info): |
|
744 | def handle(self, line_info): | |
745 | """Execute the line in a shell, empty return value""" |
|
745 | """Execute the line in a shell, empty return value""" | |
746 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') |
|
746 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') | |
747 |
|
747 | |||
748 | line = line_info.line |
|
748 | line = line_info.line | |
749 | if line.lstrip().startswith(ESC_SH_CAP): |
|
749 | if line.lstrip().startswith(ESC_SH_CAP): | |
750 | # rewrite LineInfo's line, ifun and the_rest to properly hold the |
|
750 | # rewrite LineInfo's line, ifun and the_rest to properly hold the | |
751 | # call to %sx and the actual command to be executed, so |
|
751 | # call to %sx and the actual command to be executed, so | |
752 | # handle_magic can work correctly. Note that this works even if |
|
752 | # handle_magic can work correctly. Note that this works even if | |
753 | # the line is indented, so it handles multi_line_specials |
|
753 | # the line is indented, so it handles multi_line_specials | |
754 | # properly. |
|
754 | # properly. | |
755 | new_rest = line.lstrip()[2:] |
|
755 | new_rest = line.lstrip()[2:] | |
756 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) |
|
756 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) | |
757 | line_info.ifun = 'sx' |
|
757 | line_info.ifun = 'sx' | |
758 | line_info.the_rest = new_rest |
|
758 | line_info.the_rest = new_rest | |
759 | return magic_handler.handle(line_info) |
|
759 | return magic_handler.handle(line_info) | |
760 | else: |
|
760 | else: | |
761 | cmd = line.lstrip().lstrip(ESC_SHELL) |
|
761 | cmd = line.lstrip().lstrip(ESC_SHELL) | |
762 | line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd) |
|
762 | line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd) | |
763 | return line_out |
|
763 | return line_out | |
764 |
|
764 | |||
765 |
|
765 | |||
766 | class MacroHandler(PrefilterHandler): |
|
766 | class MacroHandler(PrefilterHandler): | |
767 | handler_name = Unicode("macro") |
|
767 | handler_name = Unicode("macro") | |
768 |
|
768 | |||
769 | def handle(self, line_info): |
|
769 | def handle(self, line_info): | |
770 | obj = self.shell.user_ns.get(line_info.ifun) |
|
770 | obj = self.shell.user_ns.get(line_info.ifun) | |
771 | pre_space = line_info.pre_whitespace |
|
771 | pre_space = line_info.pre_whitespace | |
772 | line_sep = "\n" + pre_space |
|
772 | line_sep = "\n" + pre_space | |
773 | return pre_space + line_sep.join(obj.value.splitlines()) |
|
773 | return pre_space + line_sep.join(obj.value.splitlines()) | |
774 |
|
774 | |||
775 |
|
775 | |||
776 | class MagicHandler(PrefilterHandler): |
|
776 | class MagicHandler(PrefilterHandler): | |
777 |
|
777 | |||
778 | handler_name = Unicode('magic') |
|
778 | handler_name = Unicode('magic') | |
779 | esc_strings = List([ESC_MAGIC]) |
|
779 | esc_strings = List([ESC_MAGIC]) | |
780 |
|
780 | |||
781 | def handle(self, line_info): |
|
781 | def handle(self, line_info): | |
782 | """Execute magic functions.""" |
|
782 | """Execute magic functions.""" | |
783 | ifun = line_info.ifun |
|
783 | ifun = line_info.ifun | |
784 | the_rest = line_info.the_rest |
|
784 | the_rest = line_info.the_rest | |
785 | cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace, |
|
785 | cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace, | |
786 | (ifun + " " + the_rest)) |
|
786 | (ifun + " " + the_rest)) | |
787 | return cmd |
|
787 | return cmd | |
788 |
|
788 | |||
789 |
|
789 | |||
790 | class AutoHandler(PrefilterHandler): |
|
790 | class AutoHandler(PrefilterHandler): | |
791 |
|
791 | |||
792 | handler_name = Unicode('auto') |
|
792 | handler_name = Unicode('auto') | |
793 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) |
|
793 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) | |
794 |
|
794 | |||
795 | def handle(self, line_info): |
|
795 | def handle(self, line_info): | |
796 | """Handle lines which can be auto-executed, quoting if requested.""" |
|
796 | """Handle lines which can be auto-executed, quoting if requested.""" | |
797 | line = line_info.line |
|
797 | line = line_info.line | |
798 | ifun = line_info.ifun |
|
798 | ifun = line_info.ifun | |
799 | the_rest = line_info.the_rest |
|
799 | the_rest = line_info.the_rest | |
800 | pre = line_info.pre |
|
800 | pre = line_info.pre | |
801 | esc = line_info.esc |
|
801 | esc = line_info.esc | |
802 | continue_prompt = line_info.continue_prompt |
|
802 | continue_prompt = line_info.continue_prompt | |
803 | obj = line_info.ofind(self)['obj'] |
|
803 | obj = line_info.ofind(self)['obj'] | |
804 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg |
|
804 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg | |
805 |
|
805 | |||
806 | # This should only be active for single-line input! |
|
806 | # This should only be active for single-line input! | |
807 | if continue_prompt: |
|
807 | if continue_prompt: | |
808 | return line |
|
808 | return line | |
809 |
|
809 | |||
810 | force_auto = isinstance(obj, IPyAutocall) |
|
810 | force_auto = isinstance(obj, IPyAutocall) | |
811 |
|
811 | |||
812 | # User objects sometimes raise exceptions on attribute access other |
|
812 | # User objects sometimes raise exceptions on attribute access other | |
813 | # than AttributeError (we've seen it in the past), so it's safest to be |
|
813 | # than AttributeError (we've seen it in the past), so it's safest to be | |
814 | # ultra-conservative here and catch all. |
|
814 | # ultra-conservative here and catch all. | |
815 | try: |
|
815 | try: | |
816 | auto_rewrite = obj.rewrite |
|
816 | auto_rewrite = obj.rewrite | |
817 | except Exception: |
|
817 | except Exception: | |
818 | auto_rewrite = True |
|
818 | auto_rewrite = True | |
819 |
|
819 | |||
820 | if esc == ESC_QUOTE: |
|
820 | if esc == ESC_QUOTE: | |
821 | # Auto-quote splitting on whitespace |
|
821 | # Auto-quote splitting on whitespace | |
822 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) |
|
822 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) | |
823 | elif esc == ESC_QUOTE2: |
|
823 | elif esc == ESC_QUOTE2: | |
824 | # Auto-quote whole string |
|
824 | # Auto-quote whole string | |
825 | newcmd = '%s("%s")' % (ifun,the_rest) |
|
825 | newcmd = '%s("%s")' % (ifun,the_rest) | |
826 | elif esc == ESC_PAREN: |
|
826 | elif esc == ESC_PAREN: | |
827 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) |
|
827 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) | |
828 | else: |
|
828 | else: | |
829 | # Auto-paren. |
|
829 | # Auto-paren. | |
830 | # We only apply it to argument-less calls if the autocall |
|
830 | # We only apply it to argument-less calls if the autocall | |
831 | # parameter is set to 2. We only need to check that autocall is < |
|
831 | # parameter is set to 2. We only need to check that autocall is < | |
832 | # 2, since this function isn't called unless it's at least 1. |
|
832 | # 2, since this function isn't called unless it's at least 1. | |
833 | if not the_rest and (self.shell.autocall < 2) and not force_auto: |
|
833 | if not the_rest and (self.shell.autocall < 2) and not force_auto: | |
834 | newcmd = '%s %s' % (ifun,the_rest) |
|
834 | newcmd = '%s %s' % (ifun,the_rest) | |
835 | auto_rewrite = False |
|
835 | auto_rewrite = False | |
836 | else: |
|
836 | else: | |
837 | if not force_auto and the_rest.startswith('['): |
|
837 | if not force_auto and the_rest.startswith('['): | |
838 | if hasattr(obj,'__getitem__'): |
|
838 | if hasattr(obj,'__getitem__'): | |
839 | # Don't autocall in this case: item access for an object |
|
839 | # Don't autocall in this case: item access for an object | |
840 | # which is BOTH callable and implements __getitem__. |
|
840 | # which is BOTH callable and implements __getitem__. | |
841 | newcmd = '%s %s' % (ifun,the_rest) |
|
841 | newcmd = '%s %s' % (ifun,the_rest) | |
842 | auto_rewrite = False |
|
842 | auto_rewrite = False | |
843 | else: |
|
843 | else: | |
844 | # if the object doesn't support [] access, go ahead and |
|
844 | # if the object doesn't support [] access, go ahead and | |
845 | # autocall |
|
845 | # autocall | |
846 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) |
|
846 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) | |
847 | elif the_rest.endswith(';'): |
|
847 | elif the_rest.endswith(';'): | |
848 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) |
|
848 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) | |
849 | else: |
|
849 | else: | |
850 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) |
|
850 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) | |
851 |
|
851 | |||
852 | if auto_rewrite: |
|
852 | if auto_rewrite: | |
853 | self.shell.auto_rewrite_input(newcmd) |
|
853 | self.shell.auto_rewrite_input(newcmd) | |
854 |
|
854 | |||
855 | return newcmd |
|
855 | return newcmd | |
856 |
|
856 | |||
857 |
|
857 | |||
858 | class HelpHandler(PrefilterHandler): |
|
858 | class HelpHandler(PrefilterHandler): | |
859 |
|
859 | |||
860 | handler_name = Unicode('help') |
|
860 | handler_name = Unicode('help') | |
861 | esc_strings = List([ESC_HELP]) |
|
861 | esc_strings = List([ESC_HELP]) | |
862 |
|
862 | |||
863 | def handle(self, line_info): |
|
863 | def handle(self, line_info): | |
864 | """Try to get some help for the object. |
|
864 | """Try to get some help for the object. | |
865 |
|
865 | |||
866 | obj? or ?obj -> basic information. |
|
866 | obj? or ?obj -> basic information. | |
867 | obj?? or ??obj -> more details. |
|
867 | obj?? or ??obj -> more details. | |
868 | """ |
|
868 | """ | |
869 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') |
|
869 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') | |
870 | line = line_info.line |
|
870 | line = line_info.line | |
871 | # We need to make sure that we don't process lines which would be |
|
871 | # We need to make sure that we don't process lines which would be | |
872 | # otherwise valid python, such as "x=1 # what?" |
|
872 | # otherwise valid python, such as "x=1 # what?" | |
873 | try: |
|
873 | try: | |
874 | codeop.compile_command(line) |
|
874 | codeop.compile_command(line) | |
875 | except SyntaxError: |
|
875 | except SyntaxError: | |
876 | # We should only handle as help stuff which is NOT valid syntax |
|
876 | # We should only handle as help stuff which is NOT valid syntax | |
877 | if line[0]==ESC_HELP: |
|
877 | if line[0]==ESC_HELP: | |
878 | line = line[1:] |
|
878 | line = line[1:] | |
879 | elif line[-1]==ESC_HELP: |
|
879 | elif line[-1]==ESC_HELP: | |
880 | line = line[:-1] |
|
880 | line = line[:-1] | |
881 | if line: |
|
881 | if line: | |
882 | #print 'line:<%r>' % line # dbg |
|
882 | #print 'line:<%r>' % line # dbg | |
883 | self.shell.magic_pinfo(line_info.ifun) |
|
883 | self.shell.magic_pinfo(line_info.ifun) | |
884 | else: |
|
884 | else: | |
885 | self.shell.show_usage() |
|
885 | self.shell.show_usage() | |
886 | return '' # Empty string is needed here! |
|
886 | return '' # Empty string is needed here! | |
887 | except: |
|
887 | except: | |
888 | raise |
|
888 | raise | |
889 | # Pass any other exceptions through to the normal handler |
|
889 | # Pass any other exceptions through to the normal handler | |
890 | return normal_handler.handle(line_info) |
|
890 | return normal_handler.handle(line_info) | |
891 | else: |
|
891 | else: | |
892 | # If the code compiles ok, we should handle it normally |
|
892 | # If the code compiles ok, we should handle it normally | |
893 | return normal_handler.handle(line_info) |
|
893 | return normal_handler.handle(line_info) | |
894 |
|
894 | |||
895 |
|
895 | |||
896 | class EmacsHandler(PrefilterHandler): |
|
896 | class EmacsHandler(PrefilterHandler): | |
897 |
|
897 | |||
898 | handler_name = Unicode('emacs') |
|
898 | handler_name = Unicode('emacs') | |
899 | esc_strings = List([]) |
|
899 | esc_strings = List([]) | |
900 |
|
900 | |||
901 | def handle(self, line_info): |
|
901 | def handle(self, line_info): | |
902 | """Handle input lines marked by python-mode.""" |
|
902 | """Handle input lines marked by python-mode.""" | |
903 |
|
903 | |||
904 | # Currently, nothing is done. Later more functionality can be added |
|
904 | # Currently, nothing is done. Later more functionality can be added | |
905 | # here if needed. |
|
905 | # here if needed. | |
906 |
|
906 | |||
907 | # The input cache shouldn't be updated |
|
907 | # The input cache shouldn't be updated | |
908 | return line_info.line |
|
908 | return line_info.line | |
909 |
|
909 | |||
910 |
|
910 | |||
911 | #----------------------------------------------------------------------------- |
|
911 | #----------------------------------------------------------------------------- | |
912 | # Defaults |
|
912 | # Defaults | |
913 | #----------------------------------------------------------------------------- |
|
913 | #----------------------------------------------------------------------------- | |
914 |
|
914 | |||
915 |
|
915 | |||
916 | _default_transformers = [ |
|
916 | _default_transformers = [ | |
917 | AssignSystemTransformer, |
|
917 | AssignSystemTransformer, | |
918 | AssignMagicTransformer, |
|
918 | AssignMagicTransformer, | |
919 | PyPromptTransformer, |
|
919 | PyPromptTransformer, | |
920 | IPyPromptTransformer, |
|
920 | IPyPromptTransformer, | |
921 | ] |
|
921 | ] | |
922 |
|
922 | |||
923 | _default_checkers = [ |
|
923 | _default_checkers = [ | |
924 | EmacsChecker, |
|
924 | EmacsChecker, | |
925 | ShellEscapeChecker, |
|
925 | ShellEscapeChecker, | |
926 | MacroChecker, |
|
926 | MacroChecker, | |
927 | IPyAutocallChecker, |
|
927 | IPyAutocallChecker, | |
928 | MultiLineMagicChecker, |
|
928 | MultiLineMagicChecker, | |
929 | EscCharsChecker, |
|
929 | EscCharsChecker, | |
930 | AssignmentChecker, |
|
930 | AssignmentChecker, | |
931 | AutoMagicChecker, |
|
931 | AutoMagicChecker, | |
932 | AliasChecker, |
|
932 | AliasChecker, | |
933 | PythonOpsChecker, |
|
933 | PythonOpsChecker, | |
934 | AutocallChecker |
|
934 | AutocallChecker | |
935 | ] |
|
935 | ] | |
936 |
|
936 | |||
937 | _default_handlers = [ |
|
937 | _default_handlers = [ | |
938 | PrefilterHandler, |
|
938 | PrefilterHandler, | |
939 | AliasHandler, |
|
939 | AliasHandler, | |
940 | ShellEscapeHandler, |
|
940 | ShellEscapeHandler, | |
941 | MacroHandler, |
|
941 | MacroHandler, | |
942 | MagicHandler, |
|
942 | MagicHandler, | |
943 | AutoHandler, |
|
943 | AutoHandler, | |
944 | HelpHandler, |
|
944 | HelpHandler, | |
945 | EmacsHandler |
|
945 | EmacsHandler | |
946 | ] |
|
946 | ] |
@@ -1,271 +1,264 b'' | |||||
1 | """Tests for the key interactiveshell module, where the main ipython class is defined. |
|
1 | """Tests for the key interactiveshell module, where the main ipython class is defined. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Module imports |
|
4 | # Module imports | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 |
|
6 | |||
7 | # stdlib |
|
7 | # stdlib | |
8 | import os |
|
8 | import os | |
9 | import shutil |
|
9 | import shutil | |
10 | import tempfile |
|
10 | import tempfile | |
11 |
|
11 | |||
12 | # third party |
|
12 | # third party | |
13 | import nose.tools as nt |
|
13 | import nose.tools as nt | |
14 |
|
14 | |||
15 | # our own packages |
|
15 | # our own packages | |
16 | from IPython.testing import decorators as dec |
|
16 | from IPython.testing import decorators as dec | |
17 | from IPython.testing.globalipapp import get_ipython |
|
17 | from IPython.testing.globalipapp import get_ipython | |
18 | from IPython.utils import py3compat |
|
18 | from IPython.utils import py3compat | |
19 |
|
19 | |||
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # Globals |
|
21 | # Globals | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | # Get the public instance of IPython |
|
24 | # Get the public instance of IPython | |
25 | ip = get_ipython() |
|
25 | ip = get_ipython() | |
26 |
|
26 | |||
27 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
28 | # Test functions |
|
28 | # Test functions | |
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 |
|
30 | |||
31 | @dec.parametric |
|
31 | @dec.parametric | |
32 | def test_reset(): |
|
32 | def test_reset(): | |
33 | """reset must clear most namespaces.""" |
|
33 | """reset must clear most namespaces.""" | |
34 | # The number of variables in the private user_ns_hidden is not zero, but it |
|
34 | # The number of variables in the private user_ns_hidden is not zero, but it | |
35 | # should be constant regardless of what we do |
|
35 | # should be constant regardless of what we do | |
36 |
nvars_ |
|
36 | nvars_hidden = len(ip.user_ns_hidden) | |
37 |
|
37 | |||
38 | # Check that reset runs without error |
|
38 | # Check that reset runs without error | |
39 | ip.reset() |
|
39 | ip.reset() | |
40 |
|
40 | |||
41 | # Once we've reset it (to clear of any junk that might have been there from |
|
41 | # Once we've reset it (to clear of any junk that might have been there from | |
42 | # other tests, we can count how many variables are in the user's namespace |
|
42 | # other tests, we can count how many variables are in the user's namespace | |
43 | nvars_user_ns = len(ip.user_ns) |
|
43 | nvars_user_ns = len(ip.user_ns) | |
44 |
|
44 | |||
45 | # Now add a few variables to user_ns, and check that reset clears them |
|
45 | # Now add a few variables to user_ns, and check that reset clears them | |
46 | ip.user_ns['x'] = 1 |
|
46 | ip.user_ns['x'] = 1 | |
47 | ip.user_ns['y'] = 1 |
|
47 | ip.user_ns['y'] = 1 | |
48 | ip.reset() |
|
48 | ip.reset() | |
49 |
|
49 | |||
50 | # Finally, check that all namespaces have only as many variables as we |
|
50 | # Finally, check that all namespaces have only as many variables as we | |
51 | # expect to find in them: |
|
51 | # expect to find in them: | |
52 | for ns in ip.ns_refs_table: |
|
52 | yield nt.assert_equals(len(ip.user_ns), nvars_expected) | |
53 | if ns is ip.user_ns: |
|
53 | yield nt.assert_equals(len(ip.user_ns_hidden), nvars_hidden) | |
54 | nvars_expected = nvars_user_ns |
|
|||
55 | elif ns is ip.user_ns_hidden: |
|
|||
56 | nvars_expected = nvars_config_ns |
|
|||
57 | else: |
|
|||
58 | nvars_expected = 0 |
|
|||
59 |
|
||||
60 | yield nt.assert_equals(len(ns), nvars_expected) |
|
|||
61 |
|
54 | |||
62 |
|
55 | |||
63 | # Tests for reporting of exceptions in various modes, handling of SystemExit, |
|
56 | # Tests for reporting of exceptions in various modes, handling of SystemExit, | |
64 | # and %tb functionality. This is really a mix of testing ultraTB and interactiveshell. |
|
57 | # and %tb functionality. This is really a mix of testing ultraTB and interactiveshell. | |
65 |
|
58 | |||
66 | def doctest_tb_plain(): |
|
59 | def doctest_tb_plain(): | |
67 | """ |
|
60 | """ | |
68 | In [18]: xmode plain |
|
61 | In [18]: xmode plain | |
69 | Exception reporting mode: Plain |
|
62 | Exception reporting mode: Plain | |
70 |
|
63 | |||
71 | In [19]: run simpleerr.py |
|
64 | In [19]: run simpleerr.py | |
72 | Traceback (most recent call last): |
|
65 | Traceback (most recent call last): | |
73 | ...line 32, in <module> |
|
66 | ...line 32, in <module> | |
74 | bar(mode) |
|
67 | bar(mode) | |
75 | ...line 16, in bar |
|
68 | ...line 16, in bar | |
76 | div0() |
|
69 | div0() | |
77 | ...line 8, in div0 |
|
70 | ...line 8, in div0 | |
78 | x/y |
|
71 | x/y | |
79 | ZeroDivisionError: ... |
|
72 | ZeroDivisionError: ... | |
80 | """ |
|
73 | """ | |
81 |
|
74 | |||
82 |
|
75 | |||
83 | def doctest_tb_context(): |
|
76 | def doctest_tb_context(): | |
84 | """ |
|
77 | """ | |
85 | In [3]: xmode context |
|
78 | In [3]: xmode context | |
86 | Exception reporting mode: Context |
|
79 | Exception reporting mode: Context | |
87 |
|
80 | |||
88 | In [4]: run simpleerr.py |
|
81 | In [4]: run simpleerr.py | |
89 | --------------------------------------------------------------------------- |
|
82 | --------------------------------------------------------------------------- | |
90 | ZeroDivisionError Traceback (most recent call last) |
|
83 | ZeroDivisionError Traceback (most recent call last) | |
91 | <BLANKLINE> |
|
84 | <BLANKLINE> | |
92 | ... in <module>() |
|
85 | ... in <module>() | |
93 | 30 mode = 'div' |
|
86 | 30 mode = 'div' | |
94 | 31 |
|
87 | 31 | |
95 | ---> 32 bar(mode) |
|
88 | ---> 32 bar(mode) | |
96 | <BLANKLINE> |
|
89 | <BLANKLINE> | |
97 | ... in bar(mode) |
|
90 | ... in bar(mode) | |
98 | 14 "bar" |
|
91 | 14 "bar" | |
99 | 15 if mode=='div': |
|
92 | 15 if mode=='div': | |
100 | ---> 16 div0() |
|
93 | ---> 16 div0() | |
101 | 17 elif mode=='exit': |
|
94 | 17 elif mode=='exit': | |
102 | 18 try: |
|
95 | 18 try: | |
103 | <BLANKLINE> |
|
96 | <BLANKLINE> | |
104 | ... in div0() |
|
97 | ... in div0() | |
105 | 6 x = 1 |
|
98 | 6 x = 1 | |
106 | 7 y = 0 |
|
99 | 7 y = 0 | |
107 | ----> 8 x/y |
|
100 | ----> 8 x/y | |
108 | 9 |
|
101 | 9 | |
109 | 10 def sysexit(stat, mode): |
|
102 | 10 def sysexit(stat, mode): | |
110 | <BLANKLINE> |
|
103 | <BLANKLINE> | |
111 | ZeroDivisionError: ... |
|
104 | ZeroDivisionError: ... | |
112 | """ |
|
105 | """ | |
113 |
|
106 | |||
114 |
|
107 | |||
115 | def doctest_tb_verbose(): |
|
108 | def doctest_tb_verbose(): | |
116 | """ |
|
109 | """ | |
117 | In [5]: xmode verbose |
|
110 | In [5]: xmode verbose | |
118 | Exception reporting mode: Verbose |
|
111 | Exception reporting mode: Verbose | |
119 |
|
112 | |||
120 | In [6]: run simpleerr.py |
|
113 | In [6]: run simpleerr.py | |
121 | --------------------------------------------------------------------------- |
|
114 | --------------------------------------------------------------------------- | |
122 | ZeroDivisionError Traceback (most recent call last) |
|
115 | ZeroDivisionError Traceback (most recent call last) | |
123 | <BLANKLINE> |
|
116 | <BLANKLINE> | |
124 | ... in <module>() |
|
117 | ... in <module>() | |
125 | 30 mode = 'div' |
|
118 | 30 mode = 'div' | |
126 | 31 |
|
119 | 31 | |
127 | ---> 32 bar(mode) |
|
120 | ---> 32 bar(mode) | |
128 | global bar = <function bar at ...> |
|
121 | global bar = <function bar at ...> | |
129 | global mode = 'div' |
|
122 | global mode = 'div' | |
130 | <BLANKLINE> |
|
123 | <BLANKLINE> | |
131 | ... in bar(mode='div') |
|
124 | ... in bar(mode='div') | |
132 | 14 "bar" |
|
125 | 14 "bar" | |
133 | 15 if mode=='div': |
|
126 | 15 if mode=='div': | |
134 | ---> 16 div0() |
|
127 | ---> 16 div0() | |
135 | global div0 = <function div0 at ...> |
|
128 | global div0 = <function div0 at ...> | |
136 | 17 elif mode=='exit': |
|
129 | 17 elif mode=='exit': | |
137 | 18 try: |
|
130 | 18 try: | |
138 | <BLANKLINE> |
|
131 | <BLANKLINE> | |
139 | ... in div0() |
|
132 | ... in div0() | |
140 | 6 x = 1 |
|
133 | 6 x = 1 | |
141 | 7 y = 0 |
|
134 | 7 y = 0 | |
142 | ----> 8 x/y |
|
135 | ----> 8 x/y | |
143 | x = 1 |
|
136 | x = 1 | |
144 | y = 0 |
|
137 | y = 0 | |
145 | 9 |
|
138 | 9 | |
146 | 10 def sysexit(stat, mode): |
|
139 | 10 def sysexit(stat, mode): | |
147 | <BLANKLINE> |
|
140 | <BLANKLINE> | |
148 | ZeroDivisionError: ... |
|
141 | ZeroDivisionError: ... | |
149 | """ |
|
142 | """ | |
150 |
|
143 | |||
151 | def doctest_tb_sysexit(): |
|
144 | def doctest_tb_sysexit(): | |
152 | """ |
|
145 | """ | |
153 | In [17]: %xmode plain |
|
146 | In [17]: %xmode plain | |
154 | Exception reporting mode: Plain |
|
147 | Exception reporting mode: Plain | |
155 |
|
148 | |||
156 | In [18]: %run simpleerr.py exit |
|
149 | In [18]: %run simpleerr.py exit | |
157 | An exception has occurred, use %tb to see the full traceback. |
|
150 | An exception has occurred, use %tb to see the full traceback. | |
158 | SystemExit: (1, 'Mode = exit') |
|
151 | SystemExit: (1, 'Mode = exit') | |
159 |
|
152 | |||
160 | In [19]: %run simpleerr.py exit 2 |
|
153 | In [19]: %run simpleerr.py exit 2 | |
161 | An exception has occurred, use %tb to see the full traceback. |
|
154 | An exception has occurred, use %tb to see the full traceback. | |
162 | SystemExit: (2, 'Mode = exit') |
|
155 | SystemExit: (2, 'Mode = exit') | |
163 |
|
156 | |||
164 | In [20]: %tb |
|
157 | In [20]: %tb | |
165 | Traceback (most recent call last): |
|
158 | Traceback (most recent call last): | |
166 | File ... in <module> |
|
159 | File ... in <module> | |
167 | bar(mode) |
|
160 | bar(mode) | |
168 | File ... line 22, in bar |
|
161 | File ... line 22, in bar | |
169 | sysexit(stat, mode) |
|
162 | sysexit(stat, mode) | |
170 | File ... line 11, in sysexit |
|
163 | File ... line 11, in sysexit | |
171 | raise SystemExit(stat, 'Mode = %s' % mode) |
|
164 | raise SystemExit(stat, 'Mode = %s' % mode) | |
172 | SystemExit: (2, 'Mode = exit') |
|
165 | SystemExit: (2, 'Mode = exit') | |
173 |
|
166 | |||
174 | In [21]: %xmode context |
|
167 | In [21]: %xmode context | |
175 | Exception reporting mode: Context |
|
168 | Exception reporting mode: Context | |
176 |
|
169 | |||
177 | In [22]: %tb |
|
170 | In [22]: %tb | |
178 | --------------------------------------------------------------------------- |
|
171 | --------------------------------------------------------------------------- | |
179 | SystemExit Traceback (most recent call last) |
|
172 | SystemExit Traceback (most recent call last) | |
180 | <BLANKLINE> |
|
173 | <BLANKLINE> | |
181 | ...<module>() |
|
174 | ...<module>() | |
182 | 30 mode = 'div' |
|
175 | 30 mode = 'div' | |
183 | 31 |
|
176 | 31 | |
184 | ---> 32 bar(mode) |
|
177 | ---> 32 bar(mode) | |
185 | <BLANKLINE> |
|
178 | <BLANKLINE> | |
186 | ...bar(mode) |
|
179 | ...bar(mode) | |
187 | 20 except: |
|
180 | 20 except: | |
188 | 21 stat = 1 |
|
181 | 21 stat = 1 | |
189 | ---> 22 sysexit(stat, mode) |
|
182 | ---> 22 sysexit(stat, mode) | |
190 | 23 else: |
|
183 | 23 else: | |
191 | 24 raise ValueError('Unknown mode') |
|
184 | 24 raise ValueError('Unknown mode') | |
192 | <BLANKLINE> |
|
185 | <BLANKLINE> | |
193 | ...sysexit(stat, mode) |
|
186 | ...sysexit(stat, mode) | |
194 | 9 |
|
187 | 9 | |
195 | 10 def sysexit(stat, mode): |
|
188 | 10 def sysexit(stat, mode): | |
196 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) |
|
189 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) | |
197 | 12 |
|
190 | 12 | |
198 | 13 def bar(mode): |
|
191 | 13 def bar(mode): | |
199 | <BLANKLINE> |
|
192 | <BLANKLINE> | |
200 | SystemExit: (2, 'Mode = exit') |
|
193 | SystemExit: (2, 'Mode = exit') | |
201 |
|
194 | |||
202 | In [23]: %xmode verbose |
|
195 | In [23]: %xmode verbose | |
203 | Exception reporting mode: Verbose |
|
196 | Exception reporting mode: Verbose | |
204 |
|
197 | |||
205 | In [24]: %tb |
|
198 | In [24]: %tb | |
206 | --------------------------------------------------------------------------- |
|
199 | --------------------------------------------------------------------------- | |
207 | SystemExit Traceback (most recent call last) |
|
200 | SystemExit Traceback (most recent call last) | |
208 | <BLANKLINE> |
|
201 | <BLANKLINE> | |
209 | ... in <module>() |
|
202 | ... in <module>() | |
210 | 30 mode = 'div' |
|
203 | 30 mode = 'div' | |
211 | 31 |
|
204 | 31 | |
212 | ---> 32 bar(mode) |
|
205 | ---> 32 bar(mode) | |
213 | global bar = <function bar at ...> |
|
206 | global bar = <function bar at ...> | |
214 | global mode = 'exit' |
|
207 | global mode = 'exit' | |
215 | <BLANKLINE> |
|
208 | <BLANKLINE> | |
216 | ... in bar(mode='exit') |
|
209 | ... in bar(mode='exit') | |
217 | 20 except: |
|
210 | 20 except: | |
218 | 21 stat = 1 |
|
211 | 21 stat = 1 | |
219 | ---> 22 sysexit(stat, mode) |
|
212 | ---> 22 sysexit(stat, mode) | |
220 | global sysexit = <function sysexit at ...> |
|
213 | global sysexit = <function sysexit at ...> | |
221 | stat = 2 |
|
214 | stat = 2 | |
222 | mode = 'exit' |
|
215 | mode = 'exit' | |
223 | 23 else: |
|
216 | 23 else: | |
224 | 24 raise ValueError('Unknown mode') |
|
217 | 24 raise ValueError('Unknown mode') | |
225 | <BLANKLINE> |
|
218 | <BLANKLINE> | |
226 | ... in sysexit(stat=2, mode='exit') |
|
219 | ... in sysexit(stat=2, mode='exit') | |
227 | 9 |
|
220 | 9 | |
228 | 10 def sysexit(stat, mode): |
|
221 | 10 def sysexit(stat, mode): | |
229 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) |
|
222 | ---> 11 raise SystemExit(stat, 'Mode = %s' % mode) | |
230 | global SystemExit = undefined |
|
223 | global SystemExit = undefined | |
231 | stat = 2 |
|
224 | stat = 2 | |
232 | mode = 'exit' |
|
225 | mode = 'exit' | |
233 | 12 |
|
226 | 12 | |
234 | 13 def bar(mode): |
|
227 | 13 def bar(mode): | |
235 | <BLANKLINE> |
|
228 | <BLANKLINE> | |
236 | SystemExit: (2, 'Mode = exit') |
|
229 | SystemExit: (2, 'Mode = exit') | |
237 | """ |
|
230 | """ | |
238 |
|
231 | |||
239 |
|
232 | |||
240 | def test_run_cell(): |
|
233 | def test_run_cell(): | |
241 | import textwrap |
|
234 | import textwrap | |
242 | ip.run_cell('a = 10\na+=1') |
|
235 | ip.run_cell('a = 10\na+=1') | |
243 | ip.run_cell('assert a == 11\nassert 1') |
|
236 | ip.run_cell('assert a == 11\nassert 1') | |
244 |
|
237 | |||
245 | nt.assert_equals(ip.user_ns['a'], 11) |
|
238 | nt.assert_equals(ip.user_ns['a'], 11) | |
246 | complex = textwrap.dedent(""" |
|
239 | complex = textwrap.dedent(""" | |
247 | if 1: |
|
240 | if 1: | |
248 | print "hello" |
|
241 | print "hello" | |
249 | if 1: |
|
242 | if 1: | |
250 | print "world" |
|
243 | print "world" | |
251 |
|
244 | |||
252 | if 2: |
|
245 | if 2: | |
253 | print "foo" |
|
246 | print "foo" | |
254 |
|
247 | |||
255 | if 3: |
|
248 | if 3: | |
256 | print "bar" |
|
249 | print "bar" | |
257 |
|
250 | |||
258 | if 4: |
|
251 | if 4: | |
259 | print "bar" |
|
252 | print "bar" | |
260 |
|
253 | |||
261 | """) |
|
254 | """) | |
262 | # Simply verifies that this kind of input is run |
|
255 | # Simply verifies that this kind of input is run | |
263 | ip.run_cell(complex) |
|
256 | ip.run_cell(complex) | |
264 |
|
257 | |||
265 |
|
258 | |||
266 | def test_db(): |
|
259 | def test_db(): | |
267 | """Test the internal database used for variable persistence.""" |
|
260 | """Test the internal database used for variable persistence.""" | |
268 | ip.db['__unittest_'] = 12 |
|
261 | ip.db['__unittest_'] = 12 | |
269 | nt.assert_equals(ip.db['__unittest_'], 12) |
|
262 | nt.assert_equals(ip.db['__unittest_'], 12) | |
270 | del ip.db['__unittest_'] |
|
263 | del ip.db['__unittest_'] | |
271 | assert '__unittest_' not in ip.db |
|
264 | assert '__unittest_' not in ip.db |
General Comments 0
You need to be logged in to leave comments.
Login now