Show More
@@ -1,2329 +1,2336 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-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 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__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import codeop |
|
23 | import codeop | |
24 | import exceptions |
|
24 | import exceptions | |
25 | import new |
|
25 | import new | |
26 | import os |
|
26 | import os | |
27 | import re |
|
27 | import re | |
28 | import string |
|
28 | import string | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | from contextlib import nested |
|
31 | from contextlib import nested | |
32 |
|
32 | |||
33 | from IPython.config.configurable import Configurable |
|
33 | from IPython.config.configurable import Configurable | |
34 | from IPython.core import debugger, oinspect |
|
34 | from IPython.core import debugger, oinspect | |
35 | from IPython.core import history as ipcorehist |
|
35 | from IPython.core import history as ipcorehist | |
36 | from IPython.core import page |
|
36 | from IPython.core import page | |
37 | from IPython.core import prefilter |
|
37 | from IPython.core import prefilter | |
38 | from IPython.core import shadowns |
|
38 | from IPython.core import shadowns | |
39 | from IPython.core import ultratb |
|
39 | from IPython.core import ultratb | |
40 | from IPython.core.alias import AliasManager |
|
40 | from IPython.core.alias import AliasManager | |
41 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | from IPython.core.builtin_trap import BuiltinTrap | |
42 | from IPython.core.display_trap import DisplayTrap |
|
42 | from IPython.core.display_trap import DisplayTrap | |
43 | from IPython.core.displayhook import DisplayHook |
|
43 | from IPython.core.displayhook import DisplayHook | |
44 | from IPython.core.error import TryNext, UsageError |
|
44 | from IPython.core.error import TryNext, UsageError | |
45 | from IPython.core.extensions import ExtensionManager |
|
45 | from IPython.core.extensions import ExtensionManager | |
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
47 | from IPython.core.inputlist import InputList |
|
47 | from IPython.core.inputlist import InputList | |
48 | from IPython.core.logger import Logger |
|
48 | from IPython.core.logger import Logger | |
49 | from IPython.core.magic import Magic |
|
49 | from IPython.core.magic import Magic | |
50 | from IPython.core.payload import PayloadManager |
|
50 | from IPython.core.payload import PayloadManager | |
51 | from IPython.core.plugin import PluginManager |
|
51 | from IPython.core.plugin import PluginManager | |
52 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
52 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
53 | from IPython.external.Itpl import ItplNS |
|
53 | from IPython.external.Itpl import ItplNS | |
54 | from IPython.utils import PyColorize |
|
54 | from IPython.utils import PyColorize | |
55 | from IPython.utils import io |
|
55 | from IPython.utils import io | |
56 | from IPython.utils import pickleshare |
|
56 | from IPython.utils import pickleshare | |
57 | from IPython.utils.doctestreload import doctest_reload |
|
57 | from IPython.utils.doctestreload import doctest_reload | |
58 | from IPython.utils.io import ask_yes_no, rprint |
|
58 | from IPython.utils.io import ask_yes_no, rprint | |
59 | from IPython.utils.ipstruct import Struct |
|
59 | from IPython.utils.ipstruct import Struct | |
60 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
60 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
61 | from IPython.utils.process import system, getoutput |
|
61 | from IPython.utils.process import system, getoutput | |
62 | from IPython.utils.strdispatch import StrDispatch |
|
62 | from IPython.utils.strdispatch import StrDispatch | |
63 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
63 | from IPython.utils.syspathcontext import prepended_to_syspath | |
64 | from IPython.utils.text import num_ini_spaces |
|
64 | from IPython.utils.text import num_ini_spaces, format_screen | |
65 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
65 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
66 | List, Unicode, Instance, Type) |
|
66 | List, Unicode, Instance, Type) | |
67 | from IPython.utils.warn import warn, error, fatal |
|
67 | from IPython.utils.warn import warn, error, fatal | |
68 | import IPython.core.hooks |
|
68 | import IPython.core.hooks | |
69 |
|
69 | |||
70 | # from IPython.utils import growl |
|
70 | # from IPython.utils import growl | |
71 | # growl.start("IPython") |
|
71 | # growl.start("IPython") | |
72 |
|
72 | |||
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 | # Globals |
|
74 | # Globals | |
75 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
76 |
|
76 | |||
77 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
79 |
|
79 | |||
80 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
81 | # Utilities |
|
81 | # Utilities | |
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 |
|
83 | |||
84 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | # store the builtin raw_input globally, and use this always, in case user code | |
85 | # overwrites it (like wx.py.PyShell does) |
|
85 | # overwrites it (like wx.py.PyShell does) | |
86 | raw_input_original = raw_input |
|
86 | raw_input_original = raw_input | |
87 |
|
87 | |||
88 | def softspace(file, newvalue): |
|
88 | def softspace(file, newvalue): | |
89 | """Copied from code.py, to remove the dependency""" |
|
89 | """Copied from code.py, to remove the dependency""" | |
90 |
|
90 | |||
91 | oldvalue = 0 |
|
91 | oldvalue = 0 | |
92 | try: |
|
92 | try: | |
93 | oldvalue = file.softspace |
|
93 | oldvalue = file.softspace | |
94 | except AttributeError: |
|
94 | except AttributeError: | |
95 | pass |
|
95 | pass | |
96 | try: |
|
96 | try: | |
97 | file.softspace = newvalue |
|
97 | file.softspace = newvalue | |
98 | except (AttributeError, TypeError): |
|
98 | except (AttributeError, TypeError): | |
99 | # "attribute-less object" or "read-only attributes" |
|
99 | # "attribute-less object" or "read-only attributes" | |
100 | pass |
|
100 | pass | |
101 | return oldvalue |
|
101 | return oldvalue | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | def no_op(*a, **kw): pass |
|
104 | def no_op(*a, **kw): pass | |
105 |
|
105 | |||
106 | class SpaceInInput(exceptions.Exception): pass |
|
106 | class SpaceInInput(exceptions.Exception): pass | |
107 |
|
107 | |||
108 | class Bunch: pass |
|
108 | class Bunch: pass | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | def get_default_colors(): |
|
111 | def get_default_colors(): | |
112 | if sys.platform=='darwin': |
|
112 | if sys.platform=='darwin': | |
113 | return "LightBG" |
|
113 | return "LightBG" | |
114 | elif os.name=='nt': |
|
114 | elif os.name=='nt': | |
115 | return 'Linux' |
|
115 | return 'Linux' | |
116 | else: |
|
116 | else: | |
117 | return 'Linux' |
|
117 | return 'Linux' | |
118 |
|
118 | |||
119 |
|
119 | |||
120 | class SeparateStr(Str): |
|
120 | class SeparateStr(Str): | |
121 | """A Str subclass to validate separate_in, separate_out, etc. |
|
121 | """A Str subclass to validate separate_in, separate_out, etc. | |
122 |
|
122 | |||
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
124 | """ |
|
124 | """ | |
125 |
|
125 | |||
126 | def validate(self, obj, value): |
|
126 | def validate(self, obj, value): | |
127 | if value == '0': value = '' |
|
127 | if value == '0': value = '' | |
128 | value = value.replace('\\n','\n') |
|
128 | value = value.replace('\\n','\n') | |
129 | return super(SeparateStr, self).validate(obj, value) |
|
129 | return super(SeparateStr, self).validate(obj, value) | |
130 |
|
130 | |||
131 | class MultipleInstanceError(Exception): |
|
131 | class MultipleInstanceError(Exception): | |
132 | pass |
|
132 | pass | |
133 |
|
133 | |||
134 |
|
134 | |||
135 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
136 | # Main IPython class |
|
136 | # Main IPython class | |
137 | #----------------------------------------------------------------------------- |
|
137 | #----------------------------------------------------------------------------- | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | class InteractiveShell(Configurable, Magic): |
|
140 | class InteractiveShell(Configurable, Magic): | |
141 | """An enhanced, interactive shell for Python.""" |
|
141 | """An enhanced, interactive shell for Python.""" | |
142 |
|
142 | |||
143 | _instance = None |
|
143 | _instance = None | |
144 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
144 | autocall = Enum((0,1,2), default_value=1, config=True) | |
145 | # TODO: remove all autoindent logic and put into frontends. |
|
145 | # TODO: remove all autoindent logic and put into frontends. | |
146 | # We can't do this yet because even runlines uses the autoindent. |
|
146 | # We can't do this yet because even runlines uses the autoindent. | |
147 | autoindent = CBool(True, config=True) |
|
147 | autoindent = CBool(True, config=True) | |
148 | automagic = CBool(True, config=True) |
|
148 | automagic = CBool(True, config=True) | |
149 | cache_size = Int(1000, config=True) |
|
149 | cache_size = Int(1000, config=True) | |
150 | color_info = CBool(True, config=True) |
|
150 | color_info = CBool(True, config=True) | |
151 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
151 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
152 | default_value=get_default_colors(), config=True) |
|
152 | default_value=get_default_colors(), config=True) | |
153 | debug = CBool(False, config=True) |
|
153 | debug = CBool(False, config=True) | |
154 | deep_reload = CBool(False, config=True) |
|
154 | deep_reload = CBool(False, config=True) | |
155 | displayhook_class = Type(DisplayHook) |
|
155 | displayhook_class = Type(DisplayHook) | |
156 | filename = Str("<ipython console>") |
|
156 | filename = Str("<ipython console>") | |
157 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
157 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
158 | logstart = CBool(False, config=True) |
|
158 | logstart = CBool(False, config=True) | |
159 | logfile = Str('', config=True) |
|
159 | logfile = Str('', config=True) | |
160 | logappend = Str('', config=True) |
|
160 | logappend = Str('', config=True) | |
161 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
161 | object_info_string_level = Enum((0,1,2), default_value=0, | |
162 | config=True) |
|
162 | config=True) | |
163 | pdb = CBool(False, config=True) |
|
163 | pdb = CBool(False, config=True) | |
164 | pprint = CBool(True, config=True) |
|
164 | pprint = CBool(True, config=True) | |
165 | profile = Str('', config=True) |
|
165 | profile = Str('', config=True) | |
166 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
166 | prompt_in1 = Str('In [\\#]: ', config=True) | |
167 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
167 | prompt_in2 = Str(' .\\D.: ', config=True) | |
168 | prompt_out = Str('Out[\\#]: ', config=True) |
|
168 | prompt_out = Str('Out[\\#]: ', config=True) | |
169 | prompts_pad_left = CBool(True, config=True) |
|
169 | prompts_pad_left = CBool(True, config=True) | |
170 | quiet = CBool(False, config=True) |
|
170 | quiet = CBool(False, config=True) | |
171 |
|
171 | |||
172 | # The readline stuff will eventually be moved to the terminal subclass |
|
172 | # The readline stuff will eventually be moved to the terminal subclass | |
173 | # but for now, we can't do that as readline is welded in everywhere. |
|
173 | # but for now, we can't do that as readline is welded in everywhere. | |
174 | readline_use = CBool(True, config=True) |
|
174 | readline_use = CBool(True, config=True) | |
175 | readline_merge_completions = CBool(True, config=True) |
|
175 | readline_merge_completions = CBool(True, config=True) | |
176 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
176 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) | |
177 | readline_remove_delims = Str('-/~', config=True) |
|
177 | readline_remove_delims = Str('-/~', config=True) | |
178 | readline_parse_and_bind = List([ |
|
178 | readline_parse_and_bind = List([ | |
179 | 'tab: complete', |
|
179 | 'tab: complete', | |
180 | '"\C-l": clear-screen', |
|
180 | '"\C-l": clear-screen', | |
181 | 'set show-all-if-ambiguous on', |
|
181 | 'set show-all-if-ambiguous on', | |
182 | '"\C-o": tab-insert', |
|
182 | '"\C-o": tab-insert', | |
183 | '"\M-i": " "', |
|
183 | '"\M-i": " "', | |
184 | '"\M-o": "\d\d\d\d"', |
|
184 | '"\M-o": "\d\d\d\d"', | |
185 | '"\M-I": "\d\d\d\d"', |
|
185 | '"\M-I": "\d\d\d\d"', | |
186 | '"\C-r": reverse-search-history', |
|
186 | '"\C-r": reverse-search-history', | |
187 | '"\C-s": forward-search-history', |
|
187 | '"\C-s": forward-search-history', | |
188 | '"\C-p": history-search-backward', |
|
188 | '"\C-p": history-search-backward', | |
189 | '"\C-n": history-search-forward', |
|
189 | '"\C-n": history-search-forward', | |
190 | '"\e[A": history-search-backward', |
|
190 | '"\e[A": history-search-backward', | |
191 | '"\e[B": history-search-forward', |
|
191 | '"\e[B": history-search-forward', | |
192 | '"\C-k": kill-line', |
|
192 | '"\C-k": kill-line', | |
193 | '"\C-u": unix-line-discard', |
|
193 | '"\C-u": unix-line-discard', | |
194 | ], allow_none=False, config=True) |
|
194 | ], allow_none=False, config=True) | |
195 |
|
195 | |||
196 | # TODO: this part of prompt management should be moved to the frontends. |
|
196 | # TODO: this part of prompt management should be moved to the frontends. | |
197 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
197 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
198 | separate_in = SeparateStr('\n', config=True) |
|
198 | separate_in = SeparateStr('\n', config=True) | |
199 | separate_out = SeparateStr('', config=True) |
|
199 | separate_out = SeparateStr('', config=True) | |
200 | separate_out2 = SeparateStr('', config=True) |
|
200 | separate_out2 = SeparateStr('', config=True) | |
201 | wildcards_case_sensitive = CBool(True, config=True) |
|
201 | wildcards_case_sensitive = CBool(True, config=True) | |
202 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
202 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
203 | default_value='Context', config=True) |
|
203 | default_value='Context', config=True) | |
204 |
|
204 | |||
205 | # Subcomponents of InteractiveShell |
|
205 | # Subcomponents of InteractiveShell | |
206 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
206 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
207 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
207 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
208 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
208 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
209 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
209 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
210 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
210 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
211 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
211 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
212 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
212 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
213 |
|
213 | |||
214 | def __init__(self, config=None, ipython_dir=None, |
|
214 | def __init__(self, config=None, ipython_dir=None, | |
215 | user_ns=None, user_global_ns=None, |
|
215 | user_ns=None, user_global_ns=None, | |
216 | custom_exceptions=((),None)): |
|
216 | custom_exceptions=((),None)): | |
217 |
|
217 | |||
218 | # This is where traits with a config_key argument are updated |
|
218 | # This is where traits with a config_key argument are updated | |
219 | # from the values on config. |
|
219 | # from the values on config. | |
220 | super(InteractiveShell, self).__init__(config=config) |
|
220 | super(InteractiveShell, self).__init__(config=config) | |
221 |
|
221 | |||
222 | # These are relatively independent and stateless |
|
222 | # These are relatively independent and stateless | |
223 | self.init_ipython_dir(ipython_dir) |
|
223 | self.init_ipython_dir(ipython_dir) | |
224 | self.init_instance_attrs() |
|
224 | self.init_instance_attrs() | |
225 |
|
225 | |||
226 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
226 | # Create namespaces (user_ns, user_global_ns, etc.) | |
227 | self.init_create_namespaces(user_ns, user_global_ns) |
|
227 | self.init_create_namespaces(user_ns, user_global_ns) | |
228 | # This has to be done after init_create_namespaces because it uses |
|
228 | # This has to be done after init_create_namespaces because it uses | |
229 | # something in self.user_ns, but before init_sys_modules, which |
|
229 | # something in self.user_ns, but before init_sys_modules, which | |
230 | # is the first thing to modify sys. |
|
230 | # is the first thing to modify sys. | |
231 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
231 | # TODO: When we override sys.stdout and sys.stderr before this class | |
232 | # is created, we are saving the overridden ones here. Not sure if this |
|
232 | # is created, we are saving the overridden ones here. Not sure if this | |
233 | # is what we want to do. |
|
233 | # is what we want to do. | |
234 | self.save_sys_module_state() |
|
234 | self.save_sys_module_state() | |
235 | self.init_sys_modules() |
|
235 | self.init_sys_modules() | |
236 |
|
236 | |||
237 | self.init_history() |
|
237 | self.init_history() | |
238 | self.init_encoding() |
|
238 | self.init_encoding() | |
239 | self.init_prefilter() |
|
239 | self.init_prefilter() | |
240 |
|
240 | |||
241 | Magic.__init__(self, self) |
|
241 | Magic.__init__(self, self) | |
242 |
|
242 | |||
243 | self.init_syntax_highlighting() |
|
243 | self.init_syntax_highlighting() | |
244 | self.init_hooks() |
|
244 | self.init_hooks() | |
245 | self.init_pushd_popd_magic() |
|
245 | self.init_pushd_popd_magic() | |
246 | # self.init_traceback_handlers use to be here, but we moved it below |
|
246 | # self.init_traceback_handlers use to be here, but we moved it below | |
247 | # because it and init_io have to come after init_readline. |
|
247 | # because it and init_io have to come after init_readline. | |
248 | self.init_user_ns() |
|
248 | self.init_user_ns() | |
249 | self.init_logger() |
|
249 | self.init_logger() | |
250 | self.init_alias() |
|
250 | self.init_alias() | |
251 | self.init_builtins() |
|
251 | self.init_builtins() | |
252 |
|
252 | |||
253 | # pre_config_initialization |
|
253 | # pre_config_initialization | |
254 | self.init_shadow_hist() |
|
254 | self.init_shadow_hist() | |
255 |
|
255 | |||
256 | # The next section should contain averything that was in ipmaker. |
|
256 | # The next section should contain averything that was in ipmaker. | |
257 | self.init_logstart() |
|
257 | self.init_logstart() | |
258 |
|
258 | |||
259 | # The following was in post_config_initialization |
|
259 | # The following was in post_config_initialization | |
260 | self.init_inspector() |
|
260 | self.init_inspector() | |
261 | # init_readline() must come before init_io(), because init_io uses |
|
261 | # init_readline() must come before init_io(), because init_io uses | |
262 | # readline related things. |
|
262 | # readline related things. | |
263 | self.init_readline() |
|
263 | self.init_readline() | |
264 | # TODO: init_io() needs to happen before init_traceback handlers |
|
264 | # TODO: init_io() needs to happen before init_traceback handlers | |
265 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
265 | # because the traceback handlers hardcode the stdout/stderr streams. | |
266 | # This logic in in debugger.Pdb and should eventually be changed. |
|
266 | # This logic in in debugger.Pdb and should eventually be changed. | |
267 | self.init_io() |
|
267 | self.init_io() | |
268 | self.init_traceback_handlers(custom_exceptions) |
|
268 | self.init_traceback_handlers(custom_exceptions) | |
269 | self.init_prompts() |
|
269 | self.init_prompts() | |
270 | self.init_displayhook() |
|
270 | self.init_displayhook() | |
271 | self.init_reload_doctest() |
|
271 | self.init_reload_doctest() | |
272 | self.init_magics() |
|
272 | self.init_magics() | |
273 | self.init_pdb() |
|
273 | self.init_pdb() | |
274 | self.init_extension_manager() |
|
274 | self.init_extension_manager() | |
275 | self.init_plugin_manager() |
|
275 | self.init_plugin_manager() | |
276 | self.init_payload() |
|
276 | self.init_payload() | |
277 | self.hooks.late_startup_hook() |
|
277 | self.hooks.late_startup_hook() | |
278 |
|
278 | |||
279 | @classmethod |
|
279 | @classmethod | |
280 | def instance(cls, *args, **kwargs): |
|
280 | def instance(cls, *args, **kwargs): | |
281 | """Returns a global InteractiveShell instance.""" |
|
281 | """Returns a global InteractiveShell instance.""" | |
282 | if cls._instance is None: |
|
282 | if cls._instance is None: | |
283 | inst = cls(*args, **kwargs) |
|
283 | inst = cls(*args, **kwargs) | |
284 | # Now make sure that the instance will also be returned by |
|
284 | # Now make sure that the instance will also be returned by | |
285 | # the subclasses instance attribute. |
|
285 | # the subclasses instance attribute. | |
286 | for subclass in cls.mro(): |
|
286 | for subclass in cls.mro(): | |
287 | if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell): |
|
287 | if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell): | |
288 | subclass._instance = inst |
|
288 | subclass._instance = inst | |
289 | else: |
|
289 | else: | |
290 | break |
|
290 | break | |
291 | if isinstance(cls._instance, cls): |
|
291 | if isinstance(cls._instance, cls): | |
292 | return cls._instance |
|
292 | return cls._instance | |
293 | else: |
|
293 | else: | |
294 | raise MultipleInstanceError( |
|
294 | raise MultipleInstanceError( | |
295 | 'Multiple incompatible subclass instances of ' |
|
295 | 'Multiple incompatible subclass instances of ' | |
296 | 'InteractiveShell are being created.' |
|
296 | 'InteractiveShell are being created.' | |
297 | ) |
|
297 | ) | |
298 |
|
298 | |||
299 | @classmethod |
|
299 | @classmethod | |
300 | def initialized(cls): |
|
300 | def initialized(cls): | |
301 | return hasattr(cls, "_instance") |
|
301 | return hasattr(cls, "_instance") | |
302 |
|
302 | |||
303 | def get_ipython(self): |
|
303 | def get_ipython(self): | |
304 | """Return the currently running IPython instance.""" |
|
304 | """Return the currently running IPython instance.""" | |
305 | return self |
|
305 | return self | |
306 |
|
306 | |||
307 | #------------------------------------------------------------------------- |
|
307 | #------------------------------------------------------------------------- | |
308 | # Trait changed handlers |
|
308 | # Trait changed handlers | |
309 | #------------------------------------------------------------------------- |
|
309 | #------------------------------------------------------------------------- | |
310 |
|
310 | |||
311 | def _ipython_dir_changed(self, name, new): |
|
311 | def _ipython_dir_changed(self, name, new): | |
312 | if not os.path.isdir(new): |
|
312 | if not os.path.isdir(new): | |
313 | os.makedirs(new, mode = 0777) |
|
313 | os.makedirs(new, mode = 0777) | |
314 |
|
314 | |||
315 | def set_autoindent(self,value=None): |
|
315 | def set_autoindent(self,value=None): | |
316 | """Set the autoindent flag, checking for readline support. |
|
316 | """Set the autoindent flag, checking for readline support. | |
317 |
|
317 | |||
318 | If called with no arguments, it acts as a toggle.""" |
|
318 | If called with no arguments, it acts as a toggle.""" | |
319 |
|
319 | |||
320 | if not self.has_readline: |
|
320 | if not self.has_readline: | |
321 | if os.name == 'posix': |
|
321 | if os.name == 'posix': | |
322 | warn("The auto-indent feature requires the readline library") |
|
322 | warn("The auto-indent feature requires the readline library") | |
323 | self.autoindent = 0 |
|
323 | self.autoindent = 0 | |
324 | return |
|
324 | return | |
325 | if value is None: |
|
325 | if value is None: | |
326 | self.autoindent = not self.autoindent |
|
326 | self.autoindent = not self.autoindent | |
327 | else: |
|
327 | else: | |
328 | self.autoindent = value |
|
328 | self.autoindent = value | |
329 |
|
329 | |||
330 | #------------------------------------------------------------------------- |
|
330 | #------------------------------------------------------------------------- | |
331 | # init_* methods called by __init__ |
|
331 | # init_* methods called by __init__ | |
332 | #------------------------------------------------------------------------- |
|
332 | #------------------------------------------------------------------------- | |
333 |
|
333 | |||
334 | def init_ipython_dir(self, ipython_dir): |
|
334 | def init_ipython_dir(self, ipython_dir): | |
335 | if ipython_dir is not None: |
|
335 | if ipython_dir is not None: | |
336 | self.ipython_dir = ipython_dir |
|
336 | self.ipython_dir = ipython_dir | |
337 | self.config.Global.ipython_dir = self.ipython_dir |
|
337 | self.config.Global.ipython_dir = self.ipython_dir | |
338 | return |
|
338 | return | |
339 |
|
339 | |||
340 | if hasattr(self.config.Global, 'ipython_dir'): |
|
340 | if hasattr(self.config.Global, 'ipython_dir'): | |
341 | self.ipython_dir = self.config.Global.ipython_dir |
|
341 | self.ipython_dir = self.config.Global.ipython_dir | |
342 | else: |
|
342 | else: | |
343 | self.ipython_dir = get_ipython_dir() |
|
343 | self.ipython_dir = get_ipython_dir() | |
344 |
|
344 | |||
345 | # All children can just read this |
|
345 | # All children can just read this | |
346 | self.config.Global.ipython_dir = self.ipython_dir |
|
346 | self.config.Global.ipython_dir = self.ipython_dir | |
347 |
|
347 | |||
348 | def init_instance_attrs(self): |
|
348 | def init_instance_attrs(self): | |
349 | self.more = False |
|
349 | self.more = False | |
350 |
|
350 | |||
351 | # command compiler |
|
351 | # command compiler | |
352 | self.compile = codeop.CommandCompiler() |
|
352 | self.compile = codeop.CommandCompiler() | |
353 |
|
353 | |||
354 | # User input buffer |
|
354 | # User input buffer | |
355 | self.buffer = [] |
|
355 | self.buffer = [] | |
356 |
|
356 | |||
357 | # Make an empty namespace, which extension writers can rely on both |
|
357 | # Make an empty namespace, which extension writers can rely on both | |
358 | # existing and NEVER being used by ipython itself. This gives them a |
|
358 | # existing and NEVER being used by ipython itself. This gives them a | |
359 | # convenient location for storing additional information and state |
|
359 | # convenient location for storing additional information and state | |
360 | # their extensions may require, without fear of collisions with other |
|
360 | # their extensions may require, without fear of collisions with other | |
361 | # ipython names that may develop later. |
|
361 | # ipython names that may develop later. | |
362 | self.meta = Struct() |
|
362 | self.meta = Struct() | |
363 |
|
363 | |||
364 | # Object variable to store code object waiting execution. This is |
|
364 | # Object variable to store code object waiting execution. This is | |
365 | # used mainly by the multithreaded shells, but it can come in handy in |
|
365 | # used mainly by the multithreaded shells, but it can come in handy in | |
366 | # other situations. No need to use a Queue here, since it's a single |
|
366 | # other situations. No need to use a Queue here, since it's a single | |
367 | # item which gets cleared once run. |
|
367 | # item which gets cleared once run. | |
368 | self.code_to_run = None |
|
368 | self.code_to_run = None | |
369 |
|
369 | |||
370 | # Temporary files used for various purposes. Deleted at exit. |
|
370 | # Temporary files used for various purposes. Deleted at exit. | |
371 | self.tempfiles = [] |
|
371 | self.tempfiles = [] | |
372 |
|
372 | |||
373 | # Keep track of readline usage (later set by init_readline) |
|
373 | # Keep track of readline usage (later set by init_readline) | |
374 | self.has_readline = False |
|
374 | self.has_readline = False | |
375 |
|
375 | |||
376 | # keep track of where we started running (mainly for crash post-mortem) |
|
376 | # keep track of where we started running (mainly for crash post-mortem) | |
377 | # This is not being used anywhere currently. |
|
377 | # This is not being used anywhere currently. | |
378 | self.starting_dir = os.getcwd() |
|
378 | self.starting_dir = os.getcwd() | |
379 |
|
379 | |||
380 | # Indentation management |
|
380 | # Indentation management | |
381 | self.indent_current_nsp = 0 |
|
381 | self.indent_current_nsp = 0 | |
382 |
|
382 | |||
383 | def init_encoding(self): |
|
383 | def init_encoding(self): | |
384 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
384 | # Get system encoding at startup time. Certain terminals (like Emacs | |
385 | # under Win32 have it set to None, and we need to have a known valid |
|
385 | # under Win32 have it set to None, and we need to have a known valid | |
386 | # encoding to use in the raw_input() method |
|
386 | # encoding to use in the raw_input() method | |
387 | try: |
|
387 | try: | |
388 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
388 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
389 | except AttributeError: |
|
389 | except AttributeError: | |
390 | self.stdin_encoding = 'ascii' |
|
390 | self.stdin_encoding = 'ascii' | |
391 |
|
391 | |||
392 | def init_syntax_highlighting(self): |
|
392 | def init_syntax_highlighting(self): | |
393 | # Python source parser/formatter for syntax highlighting |
|
393 | # Python source parser/formatter for syntax highlighting | |
394 | pyformat = PyColorize.Parser().format |
|
394 | pyformat = PyColorize.Parser().format | |
395 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
395 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
396 |
|
396 | |||
397 | def init_pushd_popd_magic(self): |
|
397 | def init_pushd_popd_magic(self): | |
398 | # for pushd/popd management |
|
398 | # for pushd/popd management | |
399 | try: |
|
399 | try: | |
400 | self.home_dir = get_home_dir() |
|
400 | self.home_dir = get_home_dir() | |
401 | except HomeDirError, msg: |
|
401 | except HomeDirError, msg: | |
402 | fatal(msg) |
|
402 | fatal(msg) | |
403 |
|
403 | |||
404 | self.dir_stack = [] |
|
404 | self.dir_stack = [] | |
405 |
|
405 | |||
406 | def init_logger(self): |
|
406 | def init_logger(self): | |
407 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
407 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
408 | # local shortcut, this is used a LOT |
|
408 | # local shortcut, this is used a LOT | |
409 | self.log = self.logger.log |
|
409 | self.log = self.logger.log | |
410 |
|
410 | |||
411 | def init_logstart(self): |
|
411 | def init_logstart(self): | |
412 | if self.logappend: |
|
412 | if self.logappend: | |
413 | self.magic_logstart(self.logappend + ' append') |
|
413 | self.magic_logstart(self.logappend + ' append') | |
414 | elif self.logfile: |
|
414 | elif self.logfile: | |
415 | self.magic_logstart(self.logfile) |
|
415 | self.magic_logstart(self.logfile) | |
416 | elif self.logstart: |
|
416 | elif self.logstart: | |
417 | self.magic_logstart() |
|
417 | self.magic_logstart() | |
418 |
|
418 | |||
419 | def init_builtins(self): |
|
419 | def init_builtins(self): | |
420 | self.builtin_trap = BuiltinTrap(shell=self) |
|
420 | self.builtin_trap = BuiltinTrap(shell=self) | |
421 |
|
421 | |||
422 | def init_inspector(self): |
|
422 | def init_inspector(self): | |
423 | # Object inspector |
|
423 | # Object inspector | |
424 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
424 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
425 | PyColorize.ANSICodeColors, |
|
425 | PyColorize.ANSICodeColors, | |
426 | 'NoColor', |
|
426 | 'NoColor', | |
427 | self.object_info_string_level) |
|
427 | self.object_info_string_level) | |
428 |
|
428 | |||
429 | def init_io(self): |
|
429 | def init_io(self): | |
430 | import IPython.utils.io |
|
430 | import IPython.utils.io | |
431 | if sys.platform == 'win32' and self.has_readline: |
|
431 | if sys.platform == 'win32' and self.has_readline: | |
432 | Term = io.IOTerm( |
|
432 | Term = io.IOTerm( | |
433 | cout=self.readline._outputfile,cerr=self.readline._outputfile |
|
433 | cout=self.readline._outputfile,cerr=self.readline._outputfile | |
434 | ) |
|
434 | ) | |
435 | else: |
|
435 | else: | |
436 | Term = io.IOTerm() |
|
436 | Term = io.IOTerm() | |
437 | io.Term = Term |
|
437 | io.Term = Term | |
438 |
|
438 | |||
439 | def init_prompts(self): |
|
439 | def init_prompts(self): | |
440 | # TODO: This is a pass for now because the prompts are managed inside |
|
440 | # TODO: This is a pass for now because the prompts are managed inside | |
441 | # the DisplayHook. Once there is a separate prompt manager, this |
|
441 | # the DisplayHook. Once there is a separate prompt manager, this | |
442 | # will initialize that object and all prompt related information. |
|
442 | # will initialize that object and all prompt related information. | |
443 | pass |
|
443 | pass | |
444 |
|
444 | |||
445 | def init_displayhook(self): |
|
445 | def init_displayhook(self): | |
446 | # Initialize displayhook, set in/out prompts and printing system |
|
446 | # Initialize displayhook, set in/out prompts and printing system | |
447 | self.displayhook = self.displayhook_class( |
|
447 | self.displayhook = self.displayhook_class( | |
448 | shell=self, |
|
448 | shell=self, | |
449 | cache_size=self.cache_size, |
|
449 | cache_size=self.cache_size, | |
450 | input_sep = self.separate_in, |
|
450 | input_sep = self.separate_in, | |
451 | output_sep = self.separate_out, |
|
451 | output_sep = self.separate_out, | |
452 | output_sep2 = self.separate_out2, |
|
452 | output_sep2 = self.separate_out2, | |
453 | ps1 = self.prompt_in1, |
|
453 | ps1 = self.prompt_in1, | |
454 | ps2 = self.prompt_in2, |
|
454 | ps2 = self.prompt_in2, | |
455 | ps_out = self.prompt_out, |
|
455 | ps_out = self.prompt_out, | |
456 | pad_left = self.prompts_pad_left |
|
456 | pad_left = self.prompts_pad_left | |
457 | ) |
|
457 | ) | |
458 | # This is a context manager that installs/revmoes the displayhook at |
|
458 | # This is a context manager that installs/revmoes the displayhook at | |
459 | # the appropriate time. |
|
459 | # the appropriate time. | |
460 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
460 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
461 |
|
461 | |||
462 | def init_reload_doctest(self): |
|
462 | def init_reload_doctest(self): | |
463 | # Do a proper resetting of doctest, including the necessary displayhook |
|
463 | # Do a proper resetting of doctest, including the necessary displayhook | |
464 | # monkeypatching |
|
464 | # monkeypatching | |
465 | try: |
|
465 | try: | |
466 | doctest_reload() |
|
466 | doctest_reload() | |
467 | except ImportError: |
|
467 | except ImportError: | |
468 | warn("doctest module does not exist.") |
|
468 | warn("doctest module does not exist.") | |
469 |
|
469 | |||
470 | #------------------------------------------------------------------------- |
|
470 | #------------------------------------------------------------------------- | |
471 | # Things related to injections into the sys module |
|
471 | # Things related to injections into the sys module | |
472 | #------------------------------------------------------------------------- |
|
472 | #------------------------------------------------------------------------- | |
473 |
|
473 | |||
474 | def save_sys_module_state(self): |
|
474 | def save_sys_module_state(self): | |
475 | """Save the state of hooks in the sys module. |
|
475 | """Save the state of hooks in the sys module. | |
476 |
|
476 | |||
477 | This has to be called after self.user_ns is created. |
|
477 | This has to be called after self.user_ns is created. | |
478 | """ |
|
478 | """ | |
479 | self._orig_sys_module_state = {} |
|
479 | self._orig_sys_module_state = {} | |
480 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
480 | self._orig_sys_module_state['stdin'] = sys.stdin | |
481 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
481 | self._orig_sys_module_state['stdout'] = sys.stdout | |
482 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
482 | self._orig_sys_module_state['stderr'] = sys.stderr | |
483 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
483 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
484 | try: |
|
484 | try: | |
485 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
485 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
486 | except KeyError: |
|
486 | except KeyError: | |
487 | pass |
|
487 | pass | |
488 |
|
488 | |||
489 | def restore_sys_module_state(self): |
|
489 | def restore_sys_module_state(self): | |
490 | """Restore the state of the sys module.""" |
|
490 | """Restore the state of the sys module.""" | |
491 | try: |
|
491 | try: | |
492 | for k, v in self._orig_sys_module_state.items(): |
|
492 | for k, v in self._orig_sys_module_state.items(): | |
493 | setattr(sys, k, v) |
|
493 | setattr(sys, k, v) | |
494 | except AttributeError: |
|
494 | except AttributeError: | |
495 | pass |
|
495 | pass | |
496 | try: |
|
496 | try: | |
497 | delattr(sys, 'ipcompleter') |
|
497 | delattr(sys, 'ipcompleter') | |
498 | except AttributeError: |
|
498 | except AttributeError: | |
499 | pass |
|
499 | pass | |
500 | # Reset what what done in self.init_sys_modules |
|
500 | # Reset what what done in self.init_sys_modules | |
501 | try: |
|
501 | try: | |
502 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
502 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
503 | except (AttributeError, KeyError): |
|
503 | except (AttributeError, KeyError): | |
504 | pass |
|
504 | pass | |
505 |
|
505 | |||
506 | #------------------------------------------------------------------------- |
|
506 | #------------------------------------------------------------------------- | |
507 | # Things related to hooks |
|
507 | # Things related to hooks | |
508 | #------------------------------------------------------------------------- |
|
508 | #------------------------------------------------------------------------- | |
509 |
|
509 | |||
510 | def init_hooks(self): |
|
510 | def init_hooks(self): | |
511 | # hooks holds pointers used for user-side customizations |
|
511 | # hooks holds pointers used for user-side customizations | |
512 | self.hooks = Struct() |
|
512 | self.hooks = Struct() | |
513 |
|
513 | |||
514 | self.strdispatchers = {} |
|
514 | self.strdispatchers = {} | |
515 |
|
515 | |||
516 | # Set all default hooks, defined in the IPython.hooks module. |
|
516 | # Set all default hooks, defined in the IPython.hooks module. | |
517 | hooks = IPython.core.hooks |
|
517 | hooks = IPython.core.hooks | |
518 | for hook_name in hooks.__all__: |
|
518 | for hook_name in hooks.__all__: | |
519 | # default hooks have priority 100, i.e. low; user hooks should have |
|
519 | # default hooks have priority 100, i.e. low; user hooks should have | |
520 | # 0-100 priority |
|
520 | # 0-100 priority | |
521 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
521 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
522 |
|
522 | |||
523 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
523 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
524 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
524 | """set_hook(name,hook) -> sets an internal IPython hook. | |
525 |
|
525 | |||
526 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
526 | IPython exposes some of its internal API as user-modifiable hooks. By | |
527 | adding your function to one of these hooks, you can modify IPython's |
|
527 | adding your function to one of these hooks, you can modify IPython's | |
528 | behavior to call at runtime your own routines.""" |
|
528 | behavior to call at runtime your own routines.""" | |
529 |
|
529 | |||
530 | # At some point in the future, this should validate the hook before it |
|
530 | # At some point in the future, this should validate the hook before it | |
531 | # accepts it. Probably at least check that the hook takes the number |
|
531 | # accepts it. Probably at least check that the hook takes the number | |
532 | # of args it's supposed to. |
|
532 | # of args it's supposed to. | |
533 |
|
533 | |||
534 | f = new.instancemethod(hook,self,self.__class__) |
|
534 | f = new.instancemethod(hook,self,self.__class__) | |
535 |
|
535 | |||
536 | # check if the hook is for strdispatcher first |
|
536 | # check if the hook is for strdispatcher first | |
537 | if str_key is not None: |
|
537 | if str_key is not None: | |
538 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
538 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
539 | sdp.add_s(str_key, f, priority ) |
|
539 | sdp.add_s(str_key, f, priority ) | |
540 | self.strdispatchers[name] = sdp |
|
540 | self.strdispatchers[name] = sdp | |
541 | return |
|
541 | return | |
542 | if re_key is not None: |
|
542 | if re_key is not None: | |
543 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
543 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
544 | sdp.add_re(re.compile(re_key), f, priority ) |
|
544 | sdp.add_re(re.compile(re_key), f, priority ) | |
545 | self.strdispatchers[name] = sdp |
|
545 | self.strdispatchers[name] = sdp | |
546 | return |
|
546 | return | |
547 |
|
547 | |||
548 | dp = getattr(self.hooks, name, None) |
|
548 | dp = getattr(self.hooks, name, None) | |
549 | if name not in IPython.core.hooks.__all__: |
|
549 | if name not in IPython.core.hooks.__all__: | |
550 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
550 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
551 | if not dp: |
|
551 | if not dp: | |
552 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
552 | dp = IPython.core.hooks.CommandChainDispatcher() | |
553 |
|
553 | |||
554 | try: |
|
554 | try: | |
555 | dp.add(f,priority) |
|
555 | dp.add(f,priority) | |
556 | except AttributeError: |
|
556 | except AttributeError: | |
557 | # it was not commandchain, plain old func - replace |
|
557 | # it was not commandchain, plain old func - replace | |
558 | dp = f |
|
558 | dp = f | |
559 |
|
559 | |||
560 | setattr(self.hooks,name, dp) |
|
560 | setattr(self.hooks,name, dp) | |
561 |
|
561 | |||
562 | #------------------------------------------------------------------------- |
|
562 | #------------------------------------------------------------------------- | |
563 | # Things related to the "main" module |
|
563 | # Things related to the "main" module | |
564 | #------------------------------------------------------------------------- |
|
564 | #------------------------------------------------------------------------- | |
565 |
|
565 | |||
566 | def new_main_mod(self,ns=None): |
|
566 | def new_main_mod(self,ns=None): | |
567 | """Return a new 'main' module object for user code execution. |
|
567 | """Return a new 'main' module object for user code execution. | |
568 | """ |
|
568 | """ | |
569 | main_mod = self._user_main_module |
|
569 | main_mod = self._user_main_module | |
570 | init_fakemod_dict(main_mod,ns) |
|
570 | init_fakemod_dict(main_mod,ns) | |
571 | return main_mod |
|
571 | return main_mod | |
572 |
|
572 | |||
573 | def cache_main_mod(self,ns,fname): |
|
573 | def cache_main_mod(self,ns,fname): | |
574 | """Cache a main module's namespace. |
|
574 | """Cache a main module's namespace. | |
575 |
|
575 | |||
576 | When scripts are executed via %run, we must keep a reference to the |
|
576 | When scripts are executed via %run, we must keep a reference to the | |
577 | namespace of their __main__ module (a FakeModule instance) around so |
|
577 | namespace of their __main__ module (a FakeModule instance) around so | |
578 | that Python doesn't clear it, rendering objects defined therein |
|
578 | that Python doesn't clear it, rendering objects defined therein | |
579 | useless. |
|
579 | useless. | |
580 |
|
580 | |||
581 | This method keeps said reference in a private dict, keyed by the |
|
581 | This method keeps said reference in a private dict, keyed by the | |
582 | absolute path of the module object (which corresponds to the script |
|
582 | absolute path of the module object (which corresponds to the script | |
583 | path). This way, for multiple executions of the same script we only |
|
583 | path). This way, for multiple executions of the same script we only | |
584 | keep one copy of the namespace (the last one), thus preventing memory |
|
584 | keep one copy of the namespace (the last one), thus preventing memory | |
585 | leaks from old references while allowing the objects from the last |
|
585 | leaks from old references while allowing the objects from the last | |
586 | execution to be accessible. |
|
586 | execution to be accessible. | |
587 |
|
587 | |||
588 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
588 | Note: we can not allow the actual FakeModule instances to be deleted, | |
589 | because of how Python tears down modules (it hard-sets all their |
|
589 | because of how Python tears down modules (it hard-sets all their | |
590 | references to None without regard for reference counts). This method |
|
590 | references to None without regard for reference counts). This method | |
591 | must therefore make a *copy* of the given namespace, to allow the |
|
591 | must therefore make a *copy* of the given namespace, to allow the | |
592 | original module's __dict__ to be cleared and reused. |
|
592 | original module's __dict__ to be cleared and reused. | |
593 |
|
593 | |||
594 |
|
594 | |||
595 | Parameters |
|
595 | Parameters | |
596 | ---------- |
|
596 | ---------- | |
597 | ns : a namespace (a dict, typically) |
|
597 | ns : a namespace (a dict, typically) | |
598 |
|
598 | |||
599 | fname : str |
|
599 | fname : str | |
600 | Filename associated with the namespace. |
|
600 | Filename associated with the namespace. | |
601 |
|
601 | |||
602 | Examples |
|
602 | Examples | |
603 | -------- |
|
603 | -------- | |
604 |
|
604 | |||
605 | In [10]: import IPython |
|
605 | In [10]: import IPython | |
606 |
|
606 | |||
607 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
607 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
608 |
|
608 | |||
609 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
609 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
610 | Out[12]: True |
|
610 | Out[12]: True | |
611 | """ |
|
611 | """ | |
612 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
612 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
613 |
|
613 | |||
614 | def clear_main_mod_cache(self): |
|
614 | def clear_main_mod_cache(self): | |
615 | """Clear the cache of main modules. |
|
615 | """Clear the cache of main modules. | |
616 |
|
616 | |||
617 | Mainly for use by utilities like %reset. |
|
617 | Mainly for use by utilities like %reset. | |
618 |
|
618 | |||
619 | Examples |
|
619 | Examples | |
620 | -------- |
|
620 | -------- | |
621 |
|
621 | |||
622 | In [15]: import IPython |
|
622 | In [15]: import IPython | |
623 |
|
623 | |||
624 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
624 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
625 |
|
625 | |||
626 | In [17]: len(_ip._main_ns_cache) > 0 |
|
626 | In [17]: len(_ip._main_ns_cache) > 0 | |
627 | Out[17]: True |
|
627 | Out[17]: True | |
628 |
|
628 | |||
629 | In [18]: _ip.clear_main_mod_cache() |
|
629 | In [18]: _ip.clear_main_mod_cache() | |
630 |
|
630 | |||
631 | In [19]: len(_ip._main_ns_cache) == 0 |
|
631 | In [19]: len(_ip._main_ns_cache) == 0 | |
632 | Out[19]: True |
|
632 | Out[19]: True | |
633 | """ |
|
633 | """ | |
634 | self._main_ns_cache.clear() |
|
634 | self._main_ns_cache.clear() | |
635 |
|
635 | |||
636 | #------------------------------------------------------------------------- |
|
636 | #------------------------------------------------------------------------- | |
637 | # Things related to debugging |
|
637 | # Things related to debugging | |
638 | #------------------------------------------------------------------------- |
|
638 | #------------------------------------------------------------------------- | |
639 |
|
639 | |||
640 | def init_pdb(self): |
|
640 | def init_pdb(self): | |
641 | # Set calling of pdb on exceptions |
|
641 | # Set calling of pdb on exceptions | |
642 | # self.call_pdb is a property |
|
642 | # self.call_pdb is a property | |
643 | self.call_pdb = self.pdb |
|
643 | self.call_pdb = self.pdb | |
644 |
|
644 | |||
645 | def _get_call_pdb(self): |
|
645 | def _get_call_pdb(self): | |
646 | return self._call_pdb |
|
646 | return self._call_pdb | |
647 |
|
647 | |||
648 | def _set_call_pdb(self,val): |
|
648 | def _set_call_pdb(self,val): | |
649 |
|
649 | |||
650 | if val not in (0,1,False,True): |
|
650 | if val not in (0,1,False,True): | |
651 | raise ValueError,'new call_pdb value must be boolean' |
|
651 | raise ValueError,'new call_pdb value must be boolean' | |
652 |
|
652 | |||
653 | # store value in instance |
|
653 | # store value in instance | |
654 | self._call_pdb = val |
|
654 | self._call_pdb = val | |
655 |
|
655 | |||
656 | # notify the actual exception handlers |
|
656 | # notify the actual exception handlers | |
657 | self.InteractiveTB.call_pdb = val |
|
657 | self.InteractiveTB.call_pdb = val | |
658 |
|
658 | |||
659 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
659 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
660 | 'Control auto-activation of pdb at exceptions') |
|
660 | 'Control auto-activation of pdb at exceptions') | |
661 |
|
661 | |||
662 | def debugger(self,force=False): |
|
662 | def debugger(self,force=False): | |
663 | """Call the pydb/pdb debugger. |
|
663 | """Call the pydb/pdb debugger. | |
664 |
|
664 | |||
665 | Keywords: |
|
665 | Keywords: | |
666 |
|
666 | |||
667 | - force(False): by default, this routine checks the instance call_pdb |
|
667 | - force(False): by default, this routine checks the instance call_pdb | |
668 | flag and does not actually invoke the debugger if the flag is false. |
|
668 | flag and does not actually invoke the debugger if the flag is false. | |
669 | The 'force' option forces the debugger to activate even if the flag |
|
669 | The 'force' option forces the debugger to activate even if the flag | |
670 | is false. |
|
670 | is false. | |
671 | """ |
|
671 | """ | |
672 |
|
672 | |||
673 | if not (force or self.call_pdb): |
|
673 | if not (force or self.call_pdb): | |
674 | return |
|
674 | return | |
675 |
|
675 | |||
676 | if not hasattr(sys,'last_traceback'): |
|
676 | if not hasattr(sys,'last_traceback'): | |
677 | error('No traceback has been produced, nothing to debug.') |
|
677 | error('No traceback has been produced, nothing to debug.') | |
678 | return |
|
678 | return | |
679 |
|
679 | |||
680 | # use pydb if available |
|
680 | # use pydb if available | |
681 | if debugger.has_pydb: |
|
681 | if debugger.has_pydb: | |
682 | from pydb import pm |
|
682 | from pydb import pm | |
683 | else: |
|
683 | else: | |
684 | # fallback to our internal debugger |
|
684 | # fallback to our internal debugger | |
685 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
685 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
686 | self.history_saving_wrapper(pm)() |
|
686 | self.history_saving_wrapper(pm)() | |
687 |
|
687 | |||
688 | #------------------------------------------------------------------------- |
|
688 | #------------------------------------------------------------------------- | |
689 | # Things related to IPython's various namespaces |
|
689 | # Things related to IPython's various namespaces | |
690 | #------------------------------------------------------------------------- |
|
690 | #------------------------------------------------------------------------- | |
691 |
|
691 | |||
692 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
692 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
693 | # Create the namespace where the user will operate. user_ns is |
|
693 | # Create the namespace where the user will operate. user_ns is | |
694 | # normally the only one used, and it is passed to the exec calls as |
|
694 | # normally the only one used, and it is passed to the exec calls as | |
695 | # the locals argument. But we do carry a user_global_ns namespace |
|
695 | # the locals argument. But we do carry a user_global_ns namespace | |
696 | # given as the exec 'globals' argument, This is useful in embedding |
|
696 | # given as the exec 'globals' argument, This is useful in embedding | |
697 | # situations where the ipython shell opens in a context where the |
|
697 | # situations where the ipython shell opens in a context where the | |
698 | # distinction between locals and globals is meaningful. For |
|
698 | # distinction between locals and globals is meaningful. For | |
699 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
699 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
700 |
|
700 | |||
701 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
701 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
702 | # level as a dict instead of a module. This is a manual fix, but I |
|
702 | # level as a dict instead of a module. This is a manual fix, but I | |
703 | # should really track down where the problem is coming from. Alex |
|
703 | # should really track down where the problem is coming from. Alex | |
704 | # Schmolck reported this problem first. |
|
704 | # Schmolck reported this problem first. | |
705 |
|
705 | |||
706 | # A useful post by Alex Martelli on this topic: |
|
706 | # A useful post by Alex Martelli on this topic: | |
707 | # Re: inconsistent value from __builtins__ |
|
707 | # Re: inconsistent value from __builtins__ | |
708 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
708 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
709 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
709 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
710 | # Gruppen: comp.lang.python |
|
710 | # Gruppen: comp.lang.python | |
711 |
|
711 | |||
712 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
712 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
713 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
713 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
714 | # > <type 'dict'> |
|
714 | # > <type 'dict'> | |
715 | # > >>> print type(__builtins__) |
|
715 | # > >>> print type(__builtins__) | |
716 | # > <type 'module'> |
|
716 | # > <type 'module'> | |
717 | # > Is this difference in return value intentional? |
|
717 | # > Is this difference in return value intentional? | |
718 |
|
718 | |||
719 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
719 | # Well, it's documented that '__builtins__' can be either a dictionary | |
720 | # or a module, and it's been that way for a long time. Whether it's |
|
720 | # or a module, and it's been that way for a long time. Whether it's | |
721 | # intentional (or sensible), I don't know. In any case, the idea is |
|
721 | # intentional (or sensible), I don't know. In any case, the idea is | |
722 | # that if you need to access the built-in namespace directly, you |
|
722 | # that if you need to access the built-in namespace directly, you | |
723 | # should start with "import __builtin__" (note, no 's') which will |
|
723 | # should start with "import __builtin__" (note, no 's') which will | |
724 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
724 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
725 |
|
725 | |||
726 | # These routines return properly built dicts as needed by the rest of |
|
726 | # These routines return properly built dicts as needed by the rest of | |
727 | # the code, and can also be used by extension writers to generate |
|
727 | # the code, and can also be used by extension writers to generate | |
728 | # properly initialized namespaces. |
|
728 | # properly initialized namespaces. | |
729 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns) |
|
729 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns) | |
730 |
|
730 | |||
731 | # Assign namespaces |
|
731 | # Assign namespaces | |
732 | # This is the namespace where all normal user variables live |
|
732 | # This is the namespace where all normal user variables live | |
733 | self.user_ns = user_ns |
|
733 | self.user_ns = user_ns | |
734 | self.user_global_ns = user_global_ns |
|
734 | self.user_global_ns = user_global_ns | |
735 |
|
735 | |||
736 | # An auxiliary namespace that checks what parts of the user_ns were |
|
736 | # An auxiliary namespace that checks what parts of the user_ns were | |
737 | # loaded at startup, so we can list later only variables defined in |
|
737 | # loaded at startup, so we can list later only variables defined in | |
738 | # actual interactive use. Since it is always a subset of user_ns, it |
|
738 | # actual interactive use. Since it is always a subset of user_ns, it | |
739 | # doesn't need to be separately tracked in the ns_table. |
|
739 | # doesn't need to be separately tracked in the ns_table. | |
740 | self.user_ns_hidden = {} |
|
740 | self.user_ns_hidden = {} | |
741 |
|
741 | |||
742 | # A namespace to keep track of internal data structures to prevent |
|
742 | # A namespace to keep track of internal data structures to prevent | |
743 | # them from cluttering user-visible stuff. Will be updated later |
|
743 | # them from cluttering user-visible stuff. Will be updated later | |
744 | self.internal_ns = {} |
|
744 | self.internal_ns = {} | |
745 |
|
745 | |||
746 | # Now that FakeModule produces a real module, we've run into a nasty |
|
746 | # Now that FakeModule produces a real module, we've run into a nasty | |
747 | # problem: after script execution (via %run), the module where the user |
|
747 | # problem: after script execution (via %run), the module where the user | |
748 | # code ran is deleted. Now that this object is a true module (needed |
|
748 | # code ran is deleted. Now that this object is a true module (needed | |
749 | # so docetst and other tools work correctly), the Python module |
|
749 | # so docetst and other tools work correctly), the Python module | |
750 | # teardown mechanism runs over it, and sets to None every variable |
|
750 | # teardown mechanism runs over it, and sets to None every variable | |
751 | # present in that module. Top-level references to objects from the |
|
751 | # present in that module. Top-level references to objects from the | |
752 | # script survive, because the user_ns is updated with them. However, |
|
752 | # script survive, because the user_ns is updated with them. However, | |
753 | # calling functions defined in the script that use other things from |
|
753 | # calling functions defined in the script that use other things from | |
754 | # the script will fail, because the function's closure had references |
|
754 | # the script will fail, because the function's closure had references | |
755 | # to the original objects, which are now all None. So we must protect |
|
755 | # to the original objects, which are now all None. So we must protect | |
756 | # these modules from deletion by keeping a cache. |
|
756 | # these modules from deletion by keeping a cache. | |
757 | # |
|
757 | # | |
758 | # To avoid keeping stale modules around (we only need the one from the |
|
758 | # To avoid keeping stale modules around (we only need the one from the | |
759 | # last run), we use a dict keyed with the full path to the script, so |
|
759 | # last run), we use a dict keyed with the full path to the script, so | |
760 | # only the last version of the module is held in the cache. Note, |
|
760 | # only the last version of the module is held in the cache. Note, | |
761 | # however, that we must cache the module *namespace contents* (their |
|
761 | # however, that we must cache the module *namespace contents* (their | |
762 | # __dict__). Because if we try to cache the actual modules, old ones |
|
762 | # __dict__). Because if we try to cache the actual modules, old ones | |
763 | # (uncached) could be destroyed while still holding references (such as |
|
763 | # (uncached) could be destroyed while still holding references (such as | |
764 | # those held by GUI objects that tend to be long-lived)> |
|
764 | # those held by GUI objects that tend to be long-lived)> | |
765 | # |
|
765 | # | |
766 | # The %reset command will flush this cache. See the cache_main_mod() |
|
766 | # The %reset command will flush this cache. See the cache_main_mod() | |
767 | # and clear_main_mod_cache() methods for details on use. |
|
767 | # and clear_main_mod_cache() methods for details on use. | |
768 |
|
768 | |||
769 | # This is the cache used for 'main' namespaces |
|
769 | # This is the cache used for 'main' namespaces | |
770 | self._main_ns_cache = {} |
|
770 | self._main_ns_cache = {} | |
771 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
771 | # And this is the single instance of FakeModule whose __dict__ we keep | |
772 | # copying and clearing for reuse on each %run |
|
772 | # copying and clearing for reuse on each %run | |
773 | self._user_main_module = FakeModule() |
|
773 | self._user_main_module = FakeModule() | |
774 |
|
774 | |||
775 | # A table holding all the namespaces IPython deals with, so that |
|
775 | # A table holding all the namespaces IPython deals with, so that | |
776 | # introspection facilities can search easily. |
|
776 | # introspection facilities can search easily. | |
777 | self.ns_table = {'user':user_ns, |
|
777 | self.ns_table = {'user':user_ns, | |
778 | 'user_global':user_global_ns, |
|
778 | 'user_global':user_global_ns, | |
779 | 'internal':self.internal_ns, |
|
779 | 'internal':self.internal_ns, | |
780 | 'builtin':__builtin__.__dict__ |
|
780 | 'builtin':__builtin__.__dict__ | |
781 | } |
|
781 | } | |
782 |
|
782 | |||
783 | # Similarly, track all namespaces where references can be held and that |
|
783 | # Similarly, track all namespaces where references can be held and that | |
784 | # we can safely clear (so it can NOT include builtin). This one can be |
|
784 | # we can safely clear (so it can NOT include builtin). This one can be | |
785 | # a simple list. |
|
785 | # a simple list. | |
786 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, |
|
786 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, | |
787 | self.internal_ns, self._main_ns_cache ] |
|
787 | self.internal_ns, self._main_ns_cache ] | |
788 |
|
788 | |||
789 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
789 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
790 | """Return a valid local and global user interactive namespaces. |
|
790 | """Return a valid local and global user interactive namespaces. | |
791 |
|
791 | |||
792 | This builds a dict with the minimal information needed to operate as a |
|
792 | This builds a dict with the minimal information needed to operate as a | |
793 | valid IPython user namespace, which you can pass to the various |
|
793 | valid IPython user namespace, which you can pass to the various | |
794 | embedding classes in ipython. The default implementation returns the |
|
794 | embedding classes in ipython. The default implementation returns the | |
795 | same dict for both the locals and the globals to allow functions to |
|
795 | same dict for both the locals and the globals to allow functions to | |
796 | refer to variables in the namespace. Customized implementations can |
|
796 | refer to variables in the namespace. Customized implementations can | |
797 | return different dicts. The locals dictionary can actually be anything |
|
797 | return different dicts. The locals dictionary can actually be anything | |
798 | following the basic mapping protocol of a dict, but the globals dict |
|
798 | following the basic mapping protocol of a dict, but the globals dict | |
799 | must be a true dict, not even a subclass. It is recommended that any |
|
799 | must be a true dict, not even a subclass. It is recommended that any | |
800 | custom object for the locals namespace synchronize with the globals |
|
800 | custom object for the locals namespace synchronize with the globals | |
801 | dict somehow. |
|
801 | dict somehow. | |
802 |
|
802 | |||
803 | Raises TypeError if the provided globals namespace is not a true dict. |
|
803 | Raises TypeError if the provided globals namespace is not a true dict. | |
804 |
|
804 | |||
805 | Parameters |
|
805 | Parameters | |
806 | ---------- |
|
806 | ---------- | |
807 | user_ns : dict-like, optional |
|
807 | user_ns : dict-like, optional | |
808 | The current user namespace. The items in this namespace should |
|
808 | The current user namespace. The items in this namespace should | |
809 | be included in the output. If None, an appropriate blank |
|
809 | be included in the output. If None, an appropriate blank | |
810 | namespace should be created. |
|
810 | namespace should be created. | |
811 | user_global_ns : dict, optional |
|
811 | user_global_ns : dict, optional | |
812 | The current user global namespace. The items in this namespace |
|
812 | The current user global namespace. The items in this namespace | |
813 | should be included in the output. If None, an appropriate |
|
813 | should be included in the output. If None, an appropriate | |
814 | blank namespace should be created. |
|
814 | blank namespace should be created. | |
815 |
|
815 | |||
816 | Returns |
|
816 | Returns | |
817 | ------- |
|
817 | ------- | |
818 | A pair of dictionary-like object to be used as the local namespace |
|
818 | A pair of dictionary-like object to be used as the local namespace | |
819 | of the interpreter and a dict to be used as the global namespace. |
|
819 | of the interpreter and a dict to be used as the global namespace. | |
820 | """ |
|
820 | """ | |
821 |
|
821 | |||
822 |
|
822 | |||
823 | # We must ensure that __builtin__ (without the final 's') is always |
|
823 | # We must ensure that __builtin__ (without the final 's') is always | |
824 | # available and pointing to the __builtin__ *module*. For more details: |
|
824 | # available and pointing to the __builtin__ *module*. For more details: | |
825 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
825 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
826 |
|
826 | |||
827 | if user_ns is None: |
|
827 | if user_ns is None: | |
828 | # Set __name__ to __main__ to better match the behavior of the |
|
828 | # Set __name__ to __main__ to better match the behavior of the | |
829 | # normal interpreter. |
|
829 | # normal interpreter. | |
830 | user_ns = {'__name__' :'__main__', |
|
830 | user_ns = {'__name__' :'__main__', | |
831 | '__builtin__' : __builtin__, |
|
831 | '__builtin__' : __builtin__, | |
832 | '__builtins__' : __builtin__, |
|
832 | '__builtins__' : __builtin__, | |
833 | } |
|
833 | } | |
834 | else: |
|
834 | else: | |
835 | user_ns.setdefault('__name__','__main__') |
|
835 | user_ns.setdefault('__name__','__main__') | |
836 | user_ns.setdefault('__builtin__',__builtin__) |
|
836 | user_ns.setdefault('__builtin__',__builtin__) | |
837 | user_ns.setdefault('__builtins__',__builtin__) |
|
837 | user_ns.setdefault('__builtins__',__builtin__) | |
838 |
|
838 | |||
839 | if user_global_ns is None: |
|
839 | if user_global_ns is None: | |
840 | user_global_ns = user_ns |
|
840 | user_global_ns = user_ns | |
841 | if type(user_global_ns) is not dict: |
|
841 | if type(user_global_ns) is not dict: | |
842 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
842 | raise TypeError("user_global_ns must be a true dict; got %r" | |
843 | % type(user_global_ns)) |
|
843 | % type(user_global_ns)) | |
844 |
|
844 | |||
845 | return user_ns, user_global_ns |
|
845 | return user_ns, user_global_ns | |
846 |
|
846 | |||
847 | def init_sys_modules(self): |
|
847 | def init_sys_modules(self): | |
848 | # We need to insert into sys.modules something that looks like a |
|
848 | # We need to insert into sys.modules something that looks like a | |
849 | # module but which accesses the IPython namespace, for shelve and |
|
849 | # module but which accesses the IPython namespace, for shelve and | |
850 | # pickle to work interactively. Normally they rely on getting |
|
850 | # pickle to work interactively. Normally they rely on getting | |
851 | # everything out of __main__, but for embedding purposes each IPython |
|
851 | # everything out of __main__, but for embedding purposes each IPython | |
852 | # instance has its own private namespace, so we can't go shoving |
|
852 | # instance has its own private namespace, so we can't go shoving | |
853 | # everything into __main__. |
|
853 | # everything into __main__. | |
854 |
|
854 | |||
855 | # note, however, that we should only do this for non-embedded |
|
855 | # note, however, that we should only do this for non-embedded | |
856 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
856 | # ipythons, which really mimic the __main__.__dict__ with their own | |
857 | # namespace. Embedded instances, on the other hand, should not do |
|
857 | # namespace. Embedded instances, on the other hand, should not do | |
858 | # this because they need to manage the user local/global namespaces |
|
858 | # this because they need to manage the user local/global namespaces | |
859 | # only, but they live within a 'normal' __main__ (meaning, they |
|
859 | # only, but they live within a 'normal' __main__ (meaning, they | |
860 | # shouldn't overtake the execution environment of the script they're |
|
860 | # shouldn't overtake the execution environment of the script they're | |
861 | # embedded in). |
|
861 | # embedded in). | |
862 |
|
862 | |||
863 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
863 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
864 |
|
864 | |||
865 | try: |
|
865 | try: | |
866 | main_name = self.user_ns['__name__'] |
|
866 | main_name = self.user_ns['__name__'] | |
867 | except KeyError: |
|
867 | except KeyError: | |
868 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
868 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
869 | else: |
|
869 | else: | |
870 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
870 | sys.modules[main_name] = FakeModule(self.user_ns) | |
871 |
|
871 | |||
872 | def init_user_ns(self): |
|
872 | def init_user_ns(self): | |
873 | """Initialize all user-visible namespaces to their minimum defaults. |
|
873 | """Initialize all user-visible namespaces to their minimum defaults. | |
874 |
|
874 | |||
875 | Certain history lists are also initialized here, as they effectively |
|
875 | Certain history lists are also initialized here, as they effectively | |
876 | act as user namespaces. |
|
876 | act as user namespaces. | |
877 |
|
877 | |||
878 | Notes |
|
878 | Notes | |
879 | ----- |
|
879 | ----- | |
880 | All data structures here are only filled in, they are NOT reset by this |
|
880 | All data structures here are only filled in, they are NOT reset by this | |
881 | method. If they were not empty before, data will simply be added to |
|
881 | method. If they were not empty before, data will simply be added to | |
882 | therm. |
|
882 | therm. | |
883 | """ |
|
883 | """ | |
884 | # This function works in two parts: first we put a few things in |
|
884 | # This function works in two parts: first we put a few things in | |
885 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
885 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
886 | # initial variables aren't shown by %who. After the sync, we add the |
|
886 | # initial variables aren't shown by %who. After the sync, we add the | |
887 | # rest of what we *do* want the user to see with %who even on a new |
|
887 | # rest of what we *do* want the user to see with %who even on a new | |
888 | # session (probably nothing, so theye really only see their own stuff) |
|
888 | # session (probably nothing, so theye really only see their own stuff) | |
889 |
|
889 | |||
890 | # The user dict must *always* have a __builtin__ reference to the |
|
890 | # The user dict must *always* have a __builtin__ reference to the | |
891 | # Python standard __builtin__ namespace, which must be imported. |
|
891 | # Python standard __builtin__ namespace, which must be imported. | |
892 | # This is so that certain operations in prompt evaluation can be |
|
892 | # This is so that certain operations in prompt evaluation can be | |
893 | # reliably executed with builtins. Note that we can NOT use |
|
893 | # reliably executed with builtins. Note that we can NOT use | |
894 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
894 | # __builtins__ (note the 's'), because that can either be a dict or a | |
895 | # module, and can even mutate at runtime, depending on the context |
|
895 | # module, and can even mutate at runtime, depending on the context | |
896 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
896 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
897 | # always a module object, though it must be explicitly imported. |
|
897 | # always a module object, though it must be explicitly imported. | |
898 |
|
898 | |||
899 | # For more details: |
|
899 | # For more details: | |
900 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
900 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
901 | ns = dict(__builtin__ = __builtin__) |
|
901 | ns = dict(__builtin__ = __builtin__) | |
902 |
|
902 | |||
903 | # Put 'help' in the user namespace |
|
903 | # Put 'help' in the user namespace | |
904 | try: |
|
904 | try: | |
905 | from site import _Helper |
|
905 | from site import _Helper | |
906 | ns['help'] = _Helper() |
|
906 | ns['help'] = _Helper() | |
907 | except ImportError: |
|
907 | except ImportError: | |
908 | warn('help() not available - check site.py') |
|
908 | warn('help() not available - check site.py') | |
909 |
|
909 | |||
910 | # make global variables for user access to the histories |
|
910 | # make global variables for user access to the histories | |
911 | ns['_ih'] = self.input_hist |
|
911 | ns['_ih'] = self.input_hist | |
912 | ns['_oh'] = self.output_hist |
|
912 | ns['_oh'] = self.output_hist | |
913 | ns['_dh'] = self.dir_hist |
|
913 | ns['_dh'] = self.dir_hist | |
914 |
|
914 | |||
915 | ns['_sh'] = shadowns |
|
915 | ns['_sh'] = shadowns | |
916 |
|
916 | |||
917 | # user aliases to input and output histories. These shouldn't show up |
|
917 | # user aliases to input and output histories. These shouldn't show up | |
918 | # in %who, as they can have very large reprs. |
|
918 | # in %who, as they can have very large reprs. | |
919 | ns['In'] = self.input_hist |
|
919 | ns['In'] = self.input_hist | |
920 | ns['Out'] = self.output_hist |
|
920 | ns['Out'] = self.output_hist | |
921 |
|
921 | |||
922 | # Store myself as the public api!!! |
|
922 | # Store myself as the public api!!! | |
923 | ns['get_ipython'] = self.get_ipython |
|
923 | ns['get_ipython'] = self.get_ipython | |
924 |
|
924 | |||
925 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
925 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
926 | # by %who |
|
926 | # by %who | |
927 | self.user_ns_hidden.update(ns) |
|
927 | self.user_ns_hidden.update(ns) | |
928 |
|
928 | |||
929 | # Anything put into ns now would show up in %who. Think twice before |
|
929 | # Anything put into ns now would show up in %who. Think twice before | |
930 | # putting anything here, as we really want %who to show the user their |
|
930 | # putting anything here, as we really want %who to show the user their | |
931 | # stuff, not our variables. |
|
931 | # stuff, not our variables. | |
932 |
|
932 | |||
933 | # Finally, update the real user's namespace |
|
933 | # Finally, update the real user's namespace | |
934 | self.user_ns.update(ns) |
|
934 | self.user_ns.update(ns) | |
935 |
|
935 | |||
936 |
|
936 | |||
937 | def reset(self): |
|
937 | def reset(self): | |
938 | """Clear all internal namespaces. |
|
938 | """Clear all internal namespaces. | |
939 |
|
939 | |||
940 | Note that this is much more aggressive than %reset, since it clears |
|
940 | Note that this is much more aggressive than %reset, since it clears | |
941 | fully all namespaces, as well as all input/output lists. |
|
941 | fully all namespaces, as well as all input/output lists. | |
942 | """ |
|
942 | """ | |
943 | for ns in self.ns_refs_table: |
|
943 | for ns in self.ns_refs_table: | |
944 | ns.clear() |
|
944 | ns.clear() | |
945 |
|
945 | |||
946 | self.alias_manager.clear_aliases() |
|
946 | self.alias_manager.clear_aliases() | |
947 |
|
947 | |||
948 | # Clear input and output histories |
|
948 | # Clear input and output histories | |
949 | self.input_hist[:] = [] |
|
949 | self.input_hist[:] = [] | |
950 | self.input_hist_raw[:] = [] |
|
950 | self.input_hist_raw[:] = [] | |
951 | self.output_hist.clear() |
|
951 | self.output_hist.clear() | |
952 |
|
952 | |||
953 | # Restore the user namespaces to minimal usability |
|
953 | # Restore the user namespaces to minimal usability | |
954 | self.init_user_ns() |
|
954 | self.init_user_ns() | |
955 |
|
955 | |||
956 | # Restore the default and user aliases |
|
956 | # Restore the default and user aliases | |
957 | self.alias_manager.init_aliases() |
|
957 | self.alias_manager.init_aliases() | |
958 |
|
958 | |||
959 | def reset_selective(self, regex=None): |
|
959 | def reset_selective(self, regex=None): | |
960 | """Clear selective variables from internal namespaces based on a specified regular expression. |
|
960 | """Clear selective variables from internal namespaces based on a specified regular expression. | |
961 |
|
961 | |||
962 | Parameters |
|
962 | Parameters | |
963 | ---------- |
|
963 | ---------- | |
964 | regex : string or compiled pattern, optional |
|
964 | regex : string or compiled pattern, optional | |
965 | A regular expression pattern that will be used in searching variable names in the users |
|
965 | A regular expression pattern that will be used in searching variable names in the users | |
966 | namespaces. |
|
966 | namespaces. | |
967 | """ |
|
967 | """ | |
968 | if regex is not None: |
|
968 | if regex is not None: | |
969 | try: |
|
969 | try: | |
970 | m = re.compile(regex) |
|
970 | m = re.compile(regex) | |
971 | except TypeError: |
|
971 | except TypeError: | |
972 | raise TypeError('regex must be a string or compiled pattern') |
|
972 | raise TypeError('regex must be a string or compiled pattern') | |
973 | # Search for keys in each namespace that match the given regex |
|
973 | # Search for keys in each namespace that match the given regex | |
974 | # If a match is found, delete the key/value pair. |
|
974 | # If a match is found, delete the key/value pair. | |
975 | for ns in self.ns_refs_table: |
|
975 | for ns in self.ns_refs_table: | |
976 | for var in ns: |
|
976 | for var in ns: | |
977 | if m.search(var): |
|
977 | if m.search(var): | |
978 | del ns[var] |
|
978 | del ns[var] | |
979 |
|
979 | |||
980 | def push(self, variables, interactive=True): |
|
980 | def push(self, variables, interactive=True): | |
981 | """Inject a group of variables into the IPython user namespace. |
|
981 | """Inject a group of variables into the IPython user namespace. | |
982 |
|
982 | |||
983 | Parameters |
|
983 | Parameters | |
984 | ---------- |
|
984 | ---------- | |
985 | variables : dict, str or list/tuple of str |
|
985 | variables : dict, str or list/tuple of str | |
986 | The variables to inject into the user's namespace. If a dict, |
|
986 | The variables to inject into the user's namespace. If a dict, | |
987 | a simple update is done. If a str, the string is assumed to |
|
987 | a simple update is done. If a str, the string is assumed to | |
988 | have variable names separated by spaces. A list/tuple of str |
|
988 | have variable names separated by spaces. A list/tuple of str | |
989 | can also be used to give the variable names. If just the variable |
|
989 | can also be used to give the variable names. If just the variable | |
990 | names are give (list/tuple/str) then the variable values looked |
|
990 | names are give (list/tuple/str) then the variable values looked | |
991 | up in the callers frame. |
|
991 | up in the callers frame. | |
992 | interactive : bool |
|
992 | interactive : bool | |
993 | If True (default), the variables will be listed with the ``who`` |
|
993 | If True (default), the variables will be listed with the ``who`` | |
994 | magic. |
|
994 | magic. | |
995 | """ |
|
995 | """ | |
996 | vdict = None |
|
996 | vdict = None | |
997 |
|
997 | |||
998 | # We need a dict of name/value pairs to do namespace updates. |
|
998 | # We need a dict of name/value pairs to do namespace updates. | |
999 | if isinstance(variables, dict): |
|
999 | if isinstance(variables, dict): | |
1000 | vdict = variables |
|
1000 | vdict = variables | |
1001 | elif isinstance(variables, (basestring, list, tuple)): |
|
1001 | elif isinstance(variables, (basestring, list, tuple)): | |
1002 | if isinstance(variables, basestring): |
|
1002 | if isinstance(variables, basestring): | |
1003 | vlist = variables.split() |
|
1003 | vlist = variables.split() | |
1004 | else: |
|
1004 | else: | |
1005 | vlist = variables |
|
1005 | vlist = variables | |
1006 | vdict = {} |
|
1006 | vdict = {} | |
1007 | cf = sys._getframe(1) |
|
1007 | cf = sys._getframe(1) | |
1008 | for name in vlist: |
|
1008 | for name in vlist: | |
1009 | try: |
|
1009 | try: | |
1010 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1010 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1011 | except: |
|
1011 | except: | |
1012 | print ('Could not get variable %s from %s' % |
|
1012 | print ('Could not get variable %s from %s' % | |
1013 | (name,cf.f_code.co_name)) |
|
1013 | (name,cf.f_code.co_name)) | |
1014 | else: |
|
1014 | else: | |
1015 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1015 | raise ValueError('variables must be a dict/str/list/tuple') | |
1016 |
|
1016 | |||
1017 | # Propagate variables to user namespace |
|
1017 | # Propagate variables to user namespace | |
1018 | self.user_ns.update(vdict) |
|
1018 | self.user_ns.update(vdict) | |
1019 |
|
1019 | |||
1020 | # And configure interactive visibility |
|
1020 | # And configure interactive visibility | |
1021 | config_ns = self.user_ns_hidden |
|
1021 | config_ns = self.user_ns_hidden | |
1022 | if interactive: |
|
1022 | if interactive: | |
1023 | for name, val in vdict.iteritems(): |
|
1023 | for name, val in vdict.iteritems(): | |
1024 | config_ns.pop(name, None) |
|
1024 | config_ns.pop(name, None) | |
1025 | else: |
|
1025 | else: | |
1026 | for name,val in vdict.iteritems(): |
|
1026 | for name,val in vdict.iteritems(): | |
1027 | config_ns[name] = val |
|
1027 | config_ns[name] = val | |
1028 |
|
1028 | |||
1029 | #------------------------------------------------------------------------- |
|
1029 | #------------------------------------------------------------------------- | |
1030 | # Things related to object introspection |
|
1030 | # Things related to object introspection | |
1031 | #------------------------------------------------------------------------- |
|
1031 | #------------------------------------------------------------------------- | |
1032 | def _ofind(self, oname, namespaces=None): |
|
1032 | def _ofind(self, oname, namespaces=None): | |
1033 | """Find an object in the available namespaces. |
|
1033 | """Find an object in the available namespaces. | |
1034 |
|
1034 | |||
1035 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1035 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1036 |
|
1036 | |||
1037 | Has special code to detect magic functions. |
|
1037 | Has special code to detect magic functions. | |
1038 | """ |
|
1038 | """ | |
1039 | oname = oname.strip() |
|
1039 | #oname = oname.strip() | |
|
1040 | #print '1- oname: <%r>' % oname # dbg | |||
|
1041 | try: | |||
|
1042 | oname = oname.strip().encode('ascii') | |||
|
1043 | #print '2- oname: <%r>' % oname # dbg | |||
|
1044 | except UnicodeEncodeError: | |||
|
1045 | print 'Python identifiers can only contain ascii characters.' | |||
|
1046 | return dict(found=False) | |||
|
1047 | ||||
1040 | alias_ns = None |
|
1048 | alias_ns = None | |
1041 | if namespaces is None: |
|
1049 | if namespaces is None: | |
1042 | # Namespaces to search in: |
|
1050 | # Namespaces to search in: | |
1043 | # Put them in a list. The order is important so that we |
|
1051 | # Put them in a list. The order is important so that we | |
1044 | # find things in the same order that Python finds them. |
|
1052 | # find things in the same order that Python finds them. | |
1045 | namespaces = [ ('Interactive', self.user_ns), |
|
1053 | namespaces = [ ('Interactive', self.user_ns), | |
1046 | ('IPython internal', self.internal_ns), |
|
1054 | ('IPython internal', self.internal_ns), | |
1047 | ('Python builtin', __builtin__.__dict__), |
|
1055 | ('Python builtin', __builtin__.__dict__), | |
1048 | ('Alias', self.alias_manager.alias_table), |
|
1056 | ('Alias', self.alias_manager.alias_table), | |
1049 | ] |
|
1057 | ] | |
1050 | alias_ns = self.alias_manager.alias_table |
|
1058 | alias_ns = self.alias_manager.alias_table | |
1051 |
|
1059 | |||
1052 | # initialize results to 'null' |
|
1060 | # initialize results to 'null' | |
1053 | found = False; obj = None; ospace = None; ds = None; |
|
1061 | found = False; obj = None; ospace = None; ds = None; | |
1054 | ismagic = False; isalias = False; parent = None |
|
1062 | ismagic = False; isalias = False; parent = None | |
1055 |
|
1063 | |||
1056 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1064 | # We need to special-case 'print', which as of python2.6 registers as a | |
1057 | # function but should only be treated as one if print_function was |
|
1065 | # function but should only be treated as one if print_function was | |
1058 | # loaded with a future import. In this case, just bail. |
|
1066 | # loaded with a future import. In this case, just bail. | |
1059 | if (oname == 'print' and not (self.compile.compiler.flags & |
|
1067 | if (oname == 'print' and not (self.compile.compiler.flags & | |
1060 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1068 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1061 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1069 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1062 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1070 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1063 |
|
1071 | |||
1064 | # Look for the given name by splitting it in parts. If the head is |
|
1072 | # Look for the given name by splitting it in parts. If the head is | |
1065 | # found, then we look for all the remaining parts as members, and only |
|
1073 | # found, then we look for all the remaining parts as members, and only | |
1066 | # declare success if we can find them all. |
|
1074 | # declare success if we can find them all. | |
1067 | oname_parts = oname.split('.') |
|
1075 | oname_parts = oname.split('.') | |
1068 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1076 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1069 | for nsname,ns in namespaces: |
|
1077 | for nsname,ns in namespaces: | |
1070 | try: |
|
1078 | try: | |
1071 | obj = ns[oname_head] |
|
1079 | obj = ns[oname_head] | |
1072 | except KeyError: |
|
1080 | except KeyError: | |
1073 | continue |
|
1081 | continue | |
1074 | else: |
|
1082 | else: | |
1075 | #print 'oname_rest:', oname_rest # dbg |
|
1083 | #print 'oname_rest:', oname_rest # dbg | |
1076 | for part in oname_rest: |
|
1084 | for part in oname_rest: | |
1077 | try: |
|
1085 | try: | |
1078 | parent = obj |
|
1086 | parent = obj | |
1079 | obj = getattr(obj,part) |
|
1087 | obj = getattr(obj,part) | |
1080 | except: |
|
1088 | except: | |
1081 | # Blanket except b/c some badly implemented objects |
|
1089 | # Blanket except b/c some badly implemented objects | |
1082 | # allow __getattr__ to raise exceptions other than |
|
1090 | # allow __getattr__ to raise exceptions other than | |
1083 | # AttributeError, which then crashes IPython. |
|
1091 | # AttributeError, which then crashes IPython. | |
1084 | break |
|
1092 | break | |
1085 | else: |
|
1093 | else: | |
1086 | # If we finish the for loop (no break), we got all members |
|
1094 | # If we finish the for loop (no break), we got all members | |
1087 | found = True |
|
1095 | found = True | |
1088 | ospace = nsname |
|
1096 | ospace = nsname | |
1089 | if ns == alias_ns: |
|
1097 | if ns == alias_ns: | |
1090 | isalias = True |
|
1098 | isalias = True | |
1091 | break # namespace loop |
|
1099 | break # namespace loop | |
1092 |
|
1100 | |||
1093 | # Try to see if it's magic |
|
1101 | # Try to see if it's magic | |
1094 | if not found: |
|
1102 | if not found: | |
1095 | if oname.startswith(ESC_MAGIC): |
|
1103 | if oname.startswith(ESC_MAGIC): | |
1096 | oname = oname[1:] |
|
1104 | oname = oname[1:] | |
1097 | obj = getattr(self,'magic_'+oname,None) |
|
1105 | obj = getattr(self,'magic_'+oname,None) | |
1098 | if obj is not None: |
|
1106 | if obj is not None: | |
1099 | found = True |
|
1107 | found = True | |
1100 | ospace = 'IPython internal' |
|
1108 | ospace = 'IPython internal' | |
1101 | ismagic = True |
|
1109 | ismagic = True | |
1102 |
|
1110 | |||
1103 | # Last try: special-case some literals like '', [], {}, etc: |
|
1111 | # Last try: special-case some literals like '', [], {}, etc: | |
1104 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1112 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1105 | obj = eval(oname_head) |
|
1113 | obj = eval(oname_head) | |
1106 | found = True |
|
1114 | found = True | |
1107 | ospace = 'Interactive' |
|
1115 | ospace = 'Interactive' | |
1108 |
|
1116 | |||
1109 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1117 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1110 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1118 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1111 |
|
1119 | |||
1112 |
def _ |
|
1120 | def _ofind_property(self, oname, info): | |
1113 | """Generic interface to the inspector system. |
|
1121 | """Second part of object finding, to look for property details.""" | |
1114 |
|
||||
1115 | This function is meant to be called by pdef, pdoc & friends.""" |
|
|||
1116 |
|
||||
1117 | #oname = oname.strip() |
|
|||
1118 | #print '1- oname: <%r>' % oname # dbg |
|
|||
1119 | try: |
|
|||
1120 | oname = oname.strip().encode('ascii') |
|
|||
1121 | #print '2- oname: <%r>' % oname # dbg |
|
|||
1122 | except UnicodeEncodeError: |
|
|||
1123 | print 'Python identifiers can only contain ascii characters.' |
|
|||
1124 | return 'not found' |
|
|||
1125 |
|
||||
1126 | info = Struct(self._ofind(oname, namespaces)) |
|
|||
1127 |
|
||||
1128 | if info.found: |
|
1122 | if info.found: | |
1129 | try: |
|
|||
1130 | IPython.utils.generics.inspect_object(info.obj) |
|
|||
1131 | return |
|
|||
1132 | except TryNext: |
|
|||
1133 | pass |
|
|||
1134 | # Get the docstring of the class property if it exists. |
|
1123 | # Get the docstring of the class property if it exists. | |
1135 | path = oname.split('.') |
|
1124 | path = oname.split('.') | |
1136 | root = '.'.join(path[:-1]) |
|
1125 | root = '.'.join(path[:-1]) | |
1137 | if info.parent is not None: |
|
1126 | if info.parent is not None: | |
1138 | try: |
|
1127 | try: | |
1139 | target = getattr(info.parent, '__class__') |
|
1128 | target = getattr(info.parent, '__class__') | |
1140 | # The object belongs to a class instance. |
|
1129 | # The object belongs to a class instance. | |
1141 | try: |
|
1130 | try: | |
1142 | target = getattr(target, path[-1]) |
|
1131 | target = getattr(target, path[-1]) | |
1143 | # The class defines the object. |
|
1132 | # The class defines the object. | |
1144 | if isinstance(target, property): |
|
1133 | if isinstance(target, property): | |
1145 | oname = root + '.__class__.' + path[-1] |
|
1134 | oname = root + '.__class__.' + path[-1] | |
1146 | info = Struct(self._ofind(oname)) |
|
1135 | info = Struct(self._ofind(oname)) | |
1147 | except AttributeError: pass |
|
1136 | except AttributeError: pass | |
1148 | except AttributeError: pass |
|
1137 | except AttributeError: pass | |
1149 |
|
1138 | |||
1150 | pmethod = getattr(self.inspector,meth) |
|
1139 | # We return either the new info or the unmodified input if the object | |
1151 | formatter = info.ismagic and self.format_screen or None |
|
1140 | # hadn't been found | |
|
1141 | return info | |||
|
1142 | ||||
|
1143 | def _object_find(self, oname, namespaces=None): | |||
|
1144 | """Find an object and return a struct with info about it.""" | |||
|
1145 | inf = Struct(self._ofind(oname, namespaces)) | |||
|
1146 | return Struct(self._ofind_property(oname, inf)) | |||
|
1147 | ||||
|
1148 | def _inspect(self, meth, oname, namespaces=None, **kw): | |||
|
1149 | """Generic interface to the inspector system. | |||
|
1150 | ||||
|
1151 | This function is meant to be called by pdef, pdoc & friends.""" | |||
|
1152 | info = self._object_find(oname) | |||
|
1153 | if info.found: | |||
|
1154 | pmethod = getattr(self.inspector, meth) | |||
|
1155 | formatter = format_screen if info.ismagic else None | |||
1152 | if meth == 'pdoc': |
|
1156 | if meth == 'pdoc': | |
1153 | pmethod(info.obj,oname,formatter) |
|
1157 | pmethod(info.obj, oname, formatter) | |
1154 | elif meth == 'pinfo': |
|
1158 | elif meth == 'pinfo': | |
1155 | pmethod(info.obj,oname,formatter,info,**kw) |
|
1159 | pmethod(info.obj, oname, formatter, info, **kw) | |
1156 | else: |
|
1160 | else: | |
1157 | pmethod(info.obj,oname) |
|
1161 | pmethod(info.obj, oname) | |
1158 | else: |
|
1162 | else: | |
1159 | print 'Object `%s` not found.' % oname |
|
1163 | print 'Object `%s` not found.' % oname | |
1160 | return 'not found' # so callers can take other action |
|
1164 | return 'not found' # so callers can take other action | |
|
1165 | ||||
|
1166 | def object_inspect(self, oname): | |||
|
1167 | info = self._object_find(oname) | |||
1161 |
|
1168 | |||
1162 | #------------------------------------------------------------------------- |
|
1169 | #------------------------------------------------------------------------- | |
1163 | # Things related to history management |
|
1170 | # Things related to history management | |
1164 | #------------------------------------------------------------------------- |
|
1171 | #------------------------------------------------------------------------- | |
1165 |
|
1172 | |||
1166 | def init_history(self): |
|
1173 | def init_history(self): | |
1167 | # List of input with multi-line handling. |
|
1174 | # List of input with multi-line handling. | |
1168 | self.input_hist = InputList() |
|
1175 | self.input_hist = InputList() | |
1169 | # This one will hold the 'raw' input history, without any |
|
1176 | # This one will hold the 'raw' input history, without any | |
1170 | # pre-processing. This will allow users to retrieve the input just as |
|
1177 | # pre-processing. This will allow users to retrieve the input just as | |
1171 | # it was exactly typed in by the user, with %hist -r. |
|
1178 | # it was exactly typed in by the user, with %hist -r. | |
1172 | self.input_hist_raw = InputList() |
|
1179 | self.input_hist_raw = InputList() | |
1173 |
|
1180 | |||
1174 | # list of visited directories |
|
1181 | # list of visited directories | |
1175 | try: |
|
1182 | try: | |
1176 | self.dir_hist = [os.getcwd()] |
|
1183 | self.dir_hist = [os.getcwd()] | |
1177 | except OSError: |
|
1184 | except OSError: | |
1178 | self.dir_hist = [] |
|
1185 | self.dir_hist = [] | |
1179 |
|
1186 | |||
1180 | # dict of output history |
|
1187 | # dict of output history | |
1181 | self.output_hist = {} |
|
1188 | self.output_hist = {} | |
1182 |
|
1189 | |||
1183 | # Now the history file |
|
1190 | # Now the history file | |
1184 | if self.profile: |
|
1191 | if self.profile: | |
1185 | histfname = 'history-%s' % self.profile |
|
1192 | histfname = 'history-%s' % self.profile | |
1186 | else: |
|
1193 | else: | |
1187 | histfname = 'history' |
|
1194 | histfname = 'history' | |
1188 | self.histfile = os.path.join(self.ipython_dir, histfname) |
|
1195 | self.histfile = os.path.join(self.ipython_dir, histfname) | |
1189 |
|
1196 | |||
1190 | # Fill the history zero entry, user counter starts at 1 |
|
1197 | # Fill the history zero entry, user counter starts at 1 | |
1191 | self.input_hist.append('\n') |
|
1198 | self.input_hist.append('\n') | |
1192 | self.input_hist_raw.append('\n') |
|
1199 | self.input_hist_raw.append('\n') | |
1193 |
|
1200 | |||
1194 | def init_shadow_hist(self): |
|
1201 | def init_shadow_hist(self): | |
1195 | try: |
|
1202 | try: | |
1196 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") |
|
1203 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
1197 | except exceptions.UnicodeDecodeError: |
|
1204 | except exceptions.UnicodeDecodeError: | |
1198 | print "Your ipython_dir can't be decoded to unicode!" |
|
1205 | print "Your ipython_dir can't be decoded to unicode!" | |
1199 | print "Please set HOME environment variable to something that" |
|
1206 | print "Please set HOME environment variable to something that" | |
1200 | print r"only has ASCII characters, e.g. c:\home" |
|
1207 | print r"only has ASCII characters, e.g. c:\home" | |
1201 | print "Now it is", self.ipython_dir |
|
1208 | print "Now it is", self.ipython_dir | |
1202 | sys.exit() |
|
1209 | sys.exit() | |
1203 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1210 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1204 |
|
1211 | |||
1205 | def savehist(self): |
|
1212 | def savehist(self): | |
1206 | """Save input history to a file (via readline library).""" |
|
1213 | """Save input history to a file (via readline library).""" | |
1207 |
|
1214 | |||
1208 | try: |
|
1215 | try: | |
1209 | self.readline.write_history_file(self.histfile) |
|
1216 | self.readline.write_history_file(self.histfile) | |
1210 | except: |
|
1217 | except: | |
1211 | print 'Unable to save IPython command history to file: ' + \ |
|
1218 | print 'Unable to save IPython command history to file: ' + \ | |
1212 | `self.histfile` |
|
1219 | `self.histfile` | |
1213 |
|
1220 | |||
1214 | def reloadhist(self): |
|
1221 | def reloadhist(self): | |
1215 | """Reload the input history from disk file.""" |
|
1222 | """Reload the input history from disk file.""" | |
1216 |
|
1223 | |||
1217 | try: |
|
1224 | try: | |
1218 | self.readline.clear_history() |
|
1225 | self.readline.clear_history() | |
1219 | self.readline.read_history_file(self.shell.histfile) |
|
1226 | self.readline.read_history_file(self.shell.histfile) | |
1220 | except AttributeError: |
|
1227 | except AttributeError: | |
1221 | pass |
|
1228 | pass | |
1222 |
|
1229 | |||
1223 | def history_saving_wrapper(self, func): |
|
1230 | def history_saving_wrapper(self, func): | |
1224 | """ Wrap func for readline history saving |
|
1231 | """ Wrap func for readline history saving | |
1225 |
|
1232 | |||
1226 | Convert func into callable that saves & restores |
|
1233 | Convert func into callable that saves & restores | |
1227 | history around the call """ |
|
1234 | history around the call """ | |
1228 |
|
1235 | |||
1229 | if self.has_readline: |
|
1236 | if self.has_readline: | |
1230 | from IPython.utils import rlineimpl as readline |
|
1237 | from IPython.utils import rlineimpl as readline | |
1231 | else: |
|
1238 | else: | |
1232 | return func |
|
1239 | return func | |
1233 |
|
1240 | |||
1234 | def wrapper(): |
|
1241 | def wrapper(): | |
1235 | self.savehist() |
|
1242 | self.savehist() | |
1236 | try: |
|
1243 | try: | |
1237 | func() |
|
1244 | func() | |
1238 | finally: |
|
1245 | finally: | |
1239 | readline.read_history_file(self.histfile) |
|
1246 | readline.read_history_file(self.histfile) | |
1240 | return wrapper |
|
1247 | return wrapper | |
1241 |
|
1248 | |||
1242 | def get_history(self, index=None, raw=False, output=True): |
|
1249 | def get_history(self, index=None, raw=False, output=True): | |
1243 | """Get the history list. |
|
1250 | """Get the history list. | |
1244 |
|
1251 | |||
1245 | Get the input and output history. |
|
1252 | Get the input and output history. | |
1246 |
|
1253 | |||
1247 | Parameters |
|
1254 | Parameters | |
1248 | ---------- |
|
1255 | ---------- | |
1249 | index : n or (n1, n2) or None |
|
1256 | index : n or (n1, n2) or None | |
1250 | If n, then the last entries. If a tuple, then all in |
|
1257 | If n, then the last entries. If a tuple, then all in | |
1251 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
1258 | range(n1, n2). If None, then all entries. Raises IndexError if | |
1252 | the format of index is incorrect. |
|
1259 | the format of index is incorrect. | |
1253 | raw : bool |
|
1260 | raw : bool | |
1254 | If True, return the raw input. |
|
1261 | If True, return the raw input. | |
1255 | output : bool |
|
1262 | output : bool | |
1256 | If True, then return the output as well. |
|
1263 | If True, then return the output as well. | |
1257 |
|
1264 | |||
1258 | Returns |
|
1265 | Returns | |
1259 | ------- |
|
1266 | ------- | |
1260 | If output is True, then return a dict of tuples, keyed by the prompt |
|
1267 | If output is True, then return a dict of tuples, keyed by the prompt | |
1261 | numbers and with values of (input, output). If output is False, then |
|
1268 | numbers and with values of (input, output). If output is False, then | |
1262 | a dict, keyed by the prompt number with the values of input. Raises |
|
1269 | a dict, keyed by the prompt number with the values of input. Raises | |
1263 | IndexError if no history is found. |
|
1270 | IndexError if no history is found. | |
1264 | """ |
|
1271 | """ | |
1265 | if raw: |
|
1272 | if raw: | |
1266 | input_hist = self.input_hist_raw |
|
1273 | input_hist = self.input_hist_raw | |
1267 | else: |
|
1274 | else: | |
1268 | input_hist = self.input_hist |
|
1275 | input_hist = self.input_hist | |
1269 | if output: |
|
1276 | if output: | |
1270 | output_hist = self.user_ns['Out'] |
|
1277 | output_hist = self.user_ns['Out'] | |
1271 | n = len(input_hist) |
|
1278 | n = len(input_hist) | |
1272 | if index is None: |
|
1279 | if index is None: | |
1273 | start=0; stop=n |
|
1280 | start=0; stop=n | |
1274 | elif isinstance(index, int): |
|
1281 | elif isinstance(index, int): | |
1275 | start=n-index; stop=n |
|
1282 | start=n-index; stop=n | |
1276 | elif isinstance(index, tuple) and len(index) == 2: |
|
1283 | elif isinstance(index, tuple) and len(index) == 2: | |
1277 | start=index[0]; stop=index[1] |
|
1284 | start=index[0]; stop=index[1] | |
1278 | else: |
|
1285 | else: | |
1279 | raise IndexError('Not a valid index for the input history: %r' % index) |
|
1286 | raise IndexError('Not a valid index for the input history: %r' % index) | |
1280 | hist = {} |
|
1287 | hist = {} | |
1281 | for i in range(start, stop): |
|
1288 | for i in range(start, stop): | |
1282 | if output: |
|
1289 | if output: | |
1283 | hist[i] = (input_hist[i], output_hist.get(i)) |
|
1290 | hist[i] = (input_hist[i], output_hist.get(i)) | |
1284 | else: |
|
1291 | else: | |
1285 | hist[i] = input_hist[i] |
|
1292 | hist[i] = input_hist[i] | |
1286 | if len(hist)==0: |
|
1293 | if len(hist)==0: | |
1287 | raise IndexError('No history for range of indices: %r' % index) |
|
1294 | raise IndexError('No history for range of indices: %r' % index) | |
1288 | return hist |
|
1295 | return hist | |
1289 |
|
1296 | |||
1290 | #------------------------------------------------------------------------- |
|
1297 | #------------------------------------------------------------------------- | |
1291 | # Things related to exception handling and tracebacks (not debugging) |
|
1298 | # Things related to exception handling and tracebacks (not debugging) | |
1292 | #------------------------------------------------------------------------- |
|
1299 | #------------------------------------------------------------------------- | |
1293 |
|
1300 | |||
1294 | def init_traceback_handlers(self, custom_exceptions): |
|
1301 | def init_traceback_handlers(self, custom_exceptions): | |
1295 | # Syntax error handler. |
|
1302 | # Syntax error handler. | |
1296 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1303 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1297 |
|
1304 | |||
1298 | # The interactive one is initialized with an offset, meaning we always |
|
1305 | # The interactive one is initialized with an offset, meaning we always | |
1299 | # want to remove the topmost item in the traceback, which is our own |
|
1306 | # want to remove the topmost item in the traceback, which is our own | |
1300 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1307 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1301 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1308 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1302 | color_scheme='NoColor', |
|
1309 | color_scheme='NoColor', | |
1303 | tb_offset = 1) |
|
1310 | tb_offset = 1) | |
1304 |
|
1311 | |||
1305 | # The instance will store a pointer to the system-wide exception hook, |
|
1312 | # The instance will store a pointer to the system-wide exception hook, | |
1306 | # so that runtime code (such as magics) can access it. This is because |
|
1313 | # so that runtime code (such as magics) can access it. This is because | |
1307 | # during the read-eval loop, it may get temporarily overwritten. |
|
1314 | # during the read-eval loop, it may get temporarily overwritten. | |
1308 | self.sys_excepthook = sys.excepthook |
|
1315 | self.sys_excepthook = sys.excepthook | |
1309 |
|
1316 | |||
1310 | # and add any custom exception handlers the user may have specified |
|
1317 | # and add any custom exception handlers the user may have specified | |
1311 | self.set_custom_exc(*custom_exceptions) |
|
1318 | self.set_custom_exc(*custom_exceptions) | |
1312 |
|
1319 | |||
1313 | # Set the exception mode |
|
1320 | # Set the exception mode | |
1314 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1321 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1315 |
|
1322 | |||
1316 | def set_custom_exc(self, exc_tuple, handler): |
|
1323 | def set_custom_exc(self, exc_tuple, handler): | |
1317 | """set_custom_exc(exc_tuple,handler) |
|
1324 | """set_custom_exc(exc_tuple,handler) | |
1318 |
|
1325 | |||
1319 | Set a custom exception handler, which will be called if any of the |
|
1326 | Set a custom exception handler, which will be called if any of the | |
1320 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1327 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1321 | runcode() method. |
|
1328 | runcode() method. | |
1322 |
|
1329 | |||
1323 | Inputs: |
|
1330 | Inputs: | |
1324 |
|
1331 | |||
1325 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1332 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1326 | handler for. It is very important that you use a tuple, and NOT A |
|
1333 | handler for. It is very important that you use a tuple, and NOT A | |
1327 | LIST here, because of the way Python's except statement works. If |
|
1334 | LIST here, because of the way Python's except statement works. If | |
1328 | you only want to trap a single exception, use a singleton tuple: |
|
1335 | you only want to trap a single exception, use a singleton tuple: | |
1329 |
|
1336 | |||
1330 | exc_tuple == (MyCustomException,) |
|
1337 | exc_tuple == (MyCustomException,) | |
1331 |
|
1338 | |||
1332 | - handler: this must be defined as a function with the following |
|
1339 | - handler: this must be defined as a function with the following | |
1333 | basic interface:: |
|
1340 | basic interface:: | |
1334 |
|
1341 | |||
1335 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1342 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1336 | ... |
|
1343 | ... | |
1337 | # The return value must be |
|
1344 | # The return value must be | |
1338 | return structured_traceback |
|
1345 | return structured_traceback | |
1339 |
|
1346 | |||
1340 | This will be made into an instance method (via new.instancemethod) |
|
1347 | This will be made into an instance method (via new.instancemethod) | |
1341 | of IPython itself, and it will be called if any of the exceptions |
|
1348 | of IPython itself, and it will be called if any of the exceptions | |
1342 | listed in the exc_tuple are caught. If the handler is None, an |
|
1349 | listed in the exc_tuple are caught. If the handler is None, an | |
1343 | internal basic one is used, which just prints basic info. |
|
1350 | internal basic one is used, which just prints basic info. | |
1344 |
|
1351 | |||
1345 | WARNING: by putting in your own exception handler into IPython's main |
|
1352 | WARNING: by putting in your own exception handler into IPython's main | |
1346 | execution loop, you run a very good chance of nasty crashes. This |
|
1353 | execution loop, you run a very good chance of nasty crashes. This | |
1347 | facility should only be used if you really know what you are doing.""" |
|
1354 | facility should only be used if you really know what you are doing.""" | |
1348 |
|
1355 | |||
1349 | assert type(exc_tuple)==type(()) , \ |
|
1356 | assert type(exc_tuple)==type(()) , \ | |
1350 | "The custom exceptions must be given AS A TUPLE." |
|
1357 | "The custom exceptions must be given AS A TUPLE." | |
1351 |
|
1358 | |||
1352 | def dummy_handler(self,etype,value,tb): |
|
1359 | def dummy_handler(self,etype,value,tb): | |
1353 | print '*** Simple custom exception handler ***' |
|
1360 | print '*** Simple custom exception handler ***' | |
1354 | print 'Exception type :',etype |
|
1361 | print 'Exception type :',etype | |
1355 | print 'Exception value:',value |
|
1362 | print 'Exception value:',value | |
1356 | print 'Traceback :',tb |
|
1363 | print 'Traceback :',tb | |
1357 | print 'Source code :','\n'.join(self.buffer) |
|
1364 | print 'Source code :','\n'.join(self.buffer) | |
1358 |
|
1365 | |||
1359 | if handler is None: handler = dummy_handler |
|
1366 | if handler is None: handler = dummy_handler | |
1360 |
|
1367 | |||
1361 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1368 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1362 | self.custom_exceptions = exc_tuple |
|
1369 | self.custom_exceptions = exc_tuple | |
1363 |
|
1370 | |||
1364 | def excepthook(self, etype, value, tb): |
|
1371 | def excepthook(self, etype, value, tb): | |
1365 | """One more defense for GUI apps that call sys.excepthook. |
|
1372 | """One more defense for GUI apps that call sys.excepthook. | |
1366 |
|
1373 | |||
1367 | GUI frameworks like wxPython trap exceptions and call |
|
1374 | GUI frameworks like wxPython trap exceptions and call | |
1368 | sys.excepthook themselves. I guess this is a feature that |
|
1375 | sys.excepthook themselves. I guess this is a feature that | |
1369 | enables them to keep running after exceptions that would |
|
1376 | enables them to keep running after exceptions that would | |
1370 | otherwise kill their mainloop. This is a bother for IPython |
|
1377 | otherwise kill their mainloop. This is a bother for IPython | |
1371 | which excepts to catch all of the program exceptions with a try: |
|
1378 | which excepts to catch all of the program exceptions with a try: | |
1372 | except: statement. |
|
1379 | except: statement. | |
1373 |
|
1380 | |||
1374 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1381 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1375 | any app directly invokes sys.excepthook, it will look to the user like |
|
1382 | any app directly invokes sys.excepthook, it will look to the user like | |
1376 | IPython crashed. In order to work around this, we can disable the |
|
1383 | IPython crashed. In order to work around this, we can disable the | |
1377 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1384 | CrashHandler and replace it with this excepthook instead, which prints a | |
1378 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1385 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1379 | call sys.excepthook will generate a regular-looking exception from |
|
1386 | call sys.excepthook will generate a regular-looking exception from | |
1380 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1387 | IPython, and the CrashHandler will only be triggered by real IPython | |
1381 | crashes. |
|
1388 | crashes. | |
1382 |
|
1389 | |||
1383 | This hook should be used sparingly, only in places which are not likely |
|
1390 | This hook should be used sparingly, only in places which are not likely | |
1384 | to be true IPython errors. |
|
1391 | to be true IPython errors. | |
1385 | """ |
|
1392 | """ | |
1386 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1393 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1387 |
|
1394 | |||
1388 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1395 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1389 | exception_only=False): |
|
1396 | exception_only=False): | |
1390 | """Display the exception that just occurred. |
|
1397 | """Display the exception that just occurred. | |
1391 |
|
1398 | |||
1392 | If nothing is known about the exception, this is the method which |
|
1399 | If nothing is known about the exception, this is the method which | |
1393 | should be used throughout the code for presenting user tracebacks, |
|
1400 | should be used throughout the code for presenting user tracebacks, | |
1394 | rather than directly invoking the InteractiveTB object. |
|
1401 | rather than directly invoking the InteractiveTB object. | |
1395 |
|
1402 | |||
1396 | A specific showsyntaxerror() also exists, but this method can take |
|
1403 | A specific showsyntaxerror() also exists, but this method can take | |
1397 | care of calling it if needed, so unless you are explicitly catching a |
|
1404 | care of calling it if needed, so unless you are explicitly catching a | |
1398 | SyntaxError exception, don't try to analyze the stack manually and |
|
1405 | SyntaxError exception, don't try to analyze the stack manually and | |
1399 | simply call this method.""" |
|
1406 | simply call this method.""" | |
1400 |
|
1407 | |||
1401 | try: |
|
1408 | try: | |
1402 | if exc_tuple is None: |
|
1409 | if exc_tuple is None: | |
1403 | etype, value, tb = sys.exc_info() |
|
1410 | etype, value, tb = sys.exc_info() | |
1404 | else: |
|
1411 | else: | |
1405 | etype, value, tb = exc_tuple |
|
1412 | etype, value, tb = exc_tuple | |
1406 |
|
1413 | |||
1407 | if etype is None: |
|
1414 | if etype is None: | |
1408 | if hasattr(sys, 'last_type'): |
|
1415 | if hasattr(sys, 'last_type'): | |
1409 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1416 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1410 | sys.last_traceback |
|
1417 | sys.last_traceback | |
1411 | else: |
|
1418 | else: | |
1412 | self.write_err('No traceback available to show.\n') |
|
1419 | self.write_err('No traceback available to show.\n') | |
1413 | return |
|
1420 | return | |
1414 |
|
1421 | |||
1415 | if etype is SyntaxError: |
|
1422 | if etype is SyntaxError: | |
1416 | # Though this won't be called by syntax errors in the input |
|
1423 | # Though this won't be called by syntax errors in the input | |
1417 | # line, there may be SyntaxError cases whith imported code. |
|
1424 | # line, there may be SyntaxError cases whith imported code. | |
1418 | self.showsyntaxerror(filename) |
|
1425 | self.showsyntaxerror(filename) | |
1419 | elif etype is UsageError: |
|
1426 | elif etype is UsageError: | |
1420 | print "UsageError:", value |
|
1427 | print "UsageError:", value | |
1421 | else: |
|
1428 | else: | |
1422 | # WARNING: these variables are somewhat deprecated and not |
|
1429 | # WARNING: these variables are somewhat deprecated and not | |
1423 | # necessarily safe to use in a threaded environment, but tools |
|
1430 | # necessarily safe to use in a threaded environment, but tools | |
1424 | # like pdb depend on their existence, so let's set them. If we |
|
1431 | # like pdb depend on their existence, so let's set them. If we | |
1425 | # find problems in the field, we'll need to revisit their use. |
|
1432 | # find problems in the field, we'll need to revisit their use. | |
1426 | sys.last_type = etype |
|
1433 | sys.last_type = etype | |
1427 | sys.last_value = value |
|
1434 | sys.last_value = value | |
1428 | sys.last_traceback = tb |
|
1435 | sys.last_traceback = tb | |
1429 |
|
1436 | |||
1430 | if etype in self.custom_exceptions: |
|
1437 | if etype in self.custom_exceptions: | |
1431 | # FIXME: Old custom traceback objects may just return a |
|
1438 | # FIXME: Old custom traceback objects may just return a | |
1432 | # string, in that case we just put it into a list |
|
1439 | # string, in that case we just put it into a list | |
1433 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1440 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1434 | if isinstance(ctb, basestring): |
|
1441 | if isinstance(ctb, basestring): | |
1435 | stb = [stb] |
|
1442 | stb = [stb] | |
1436 | else: |
|
1443 | else: | |
1437 | if exception_only: |
|
1444 | if exception_only: | |
1438 | stb = ['An exception has occurred, use %tb to see ' |
|
1445 | stb = ['An exception has occurred, use %tb to see ' | |
1439 | 'the full traceback.\n'] |
|
1446 | 'the full traceback.\n'] | |
1440 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1447 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1441 | value)) |
|
1448 | value)) | |
1442 | else: |
|
1449 | else: | |
1443 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1450 | stb = self.InteractiveTB.structured_traceback(etype, | |
1444 | value, tb, tb_offset=tb_offset) |
|
1451 | value, tb, tb_offset=tb_offset) | |
1445 | # FIXME: the pdb calling should be done by us, not by |
|
1452 | # FIXME: the pdb calling should be done by us, not by | |
1446 | # the code computing the traceback. |
|
1453 | # the code computing the traceback. | |
1447 | if self.InteractiveTB.call_pdb: |
|
1454 | if self.InteractiveTB.call_pdb: | |
1448 | # pdb mucks up readline, fix it back |
|
1455 | # pdb mucks up readline, fix it back | |
1449 | self.set_completer() |
|
1456 | self.set_completer() | |
1450 |
|
1457 | |||
1451 | # Actually show the traceback |
|
1458 | # Actually show the traceback | |
1452 | self._showtraceback(etype, value, stb) |
|
1459 | self._showtraceback(etype, value, stb) | |
1453 |
|
1460 | |||
1454 | except KeyboardInterrupt: |
|
1461 | except KeyboardInterrupt: | |
1455 | self.write_err("\nKeyboardInterrupt\n") |
|
1462 | self.write_err("\nKeyboardInterrupt\n") | |
1456 |
|
1463 | |||
1457 | def _showtraceback(self, etype, evalue, stb): |
|
1464 | def _showtraceback(self, etype, evalue, stb): | |
1458 | """Actually show a traceback. |
|
1465 | """Actually show a traceback. | |
1459 |
|
1466 | |||
1460 | Subclasses may override this method to put the traceback on a different |
|
1467 | Subclasses may override this method to put the traceback on a different | |
1461 | place, like a side channel. |
|
1468 | place, like a side channel. | |
1462 | """ |
|
1469 | """ | |
1463 | # FIXME: this should use the proper write channels, but our test suite |
|
1470 | # FIXME: this should use the proper write channels, but our test suite | |
1464 | # relies on it coming out of stdout... |
|
1471 | # relies on it coming out of stdout... | |
1465 | print >> sys.stdout, self.InteractiveTB.stb2text(stb) |
|
1472 | print >> sys.stdout, self.InteractiveTB.stb2text(stb) | |
1466 |
|
1473 | |||
1467 | def showsyntaxerror(self, filename=None): |
|
1474 | def showsyntaxerror(self, filename=None): | |
1468 | """Display the syntax error that just occurred. |
|
1475 | """Display the syntax error that just occurred. | |
1469 |
|
1476 | |||
1470 | This doesn't display a stack trace because there isn't one. |
|
1477 | This doesn't display a stack trace because there isn't one. | |
1471 |
|
1478 | |||
1472 | If a filename is given, it is stuffed in the exception instead |
|
1479 | If a filename is given, it is stuffed in the exception instead | |
1473 | of what was there before (because Python's parser always uses |
|
1480 | of what was there before (because Python's parser always uses | |
1474 | "<string>" when reading from a string). |
|
1481 | "<string>" when reading from a string). | |
1475 | """ |
|
1482 | """ | |
1476 | etype, value, last_traceback = sys.exc_info() |
|
1483 | etype, value, last_traceback = sys.exc_info() | |
1477 |
|
1484 | |||
1478 | # See note about these variables in showtraceback() above |
|
1485 | # See note about these variables in showtraceback() above | |
1479 | sys.last_type = etype |
|
1486 | sys.last_type = etype | |
1480 | sys.last_value = value |
|
1487 | sys.last_value = value | |
1481 | sys.last_traceback = last_traceback |
|
1488 | sys.last_traceback = last_traceback | |
1482 |
|
1489 | |||
1483 | if filename and etype is SyntaxError: |
|
1490 | if filename and etype is SyntaxError: | |
1484 | # Work hard to stuff the correct filename in the exception |
|
1491 | # Work hard to stuff the correct filename in the exception | |
1485 | try: |
|
1492 | try: | |
1486 | msg, (dummy_filename, lineno, offset, line) = value |
|
1493 | msg, (dummy_filename, lineno, offset, line) = value | |
1487 | except: |
|
1494 | except: | |
1488 | # Not the format we expect; leave it alone |
|
1495 | # Not the format we expect; leave it alone | |
1489 | pass |
|
1496 | pass | |
1490 | else: |
|
1497 | else: | |
1491 | # Stuff in the right filename |
|
1498 | # Stuff in the right filename | |
1492 | try: |
|
1499 | try: | |
1493 | # Assume SyntaxError is a class exception |
|
1500 | # Assume SyntaxError is a class exception | |
1494 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1501 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1495 | except: |
|
1502 | except: | |
1496 | # If that failed, assume SyntaxError is a string |
|
1503 | # If that failed, assume SyntaxError is a string | |
1497 | value = msg, (filename, lineno, offset, line) |
|
1504 | value = msg, (filename, lineno, offset, line) | |
1498 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1505 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1499 | self._showtraceback(etype, value, stb) |
|
1506 | self._showtraceback(etype, value, stb) | |
1500 |
|
1507 | |||
1501 | #------------------------------------------------------------------------- |
|
1508 | #------------------------------------------------------------------------- | |
1502 | # Things related to tab completion |
|
1509 | # Things related to tab completion | |
1503 | #------------------------------------------------------------------------- |
|
1510 | #------------------------------------------------------------------------- | |
1504 |
|
1511 | |||
1505 | def complete(self, text, line=None, cursor_pos=None): |
|
1512 | def complete(self, text, line=None, cursor_pos=None): | |
1506 | """Return the completed text and a list of completions. |
|
1513 | """Return the completed text and a list of completions. | |
1507 |
|
1514 | |||
1508 | Parameters |
|
1515 | Parameters | |
1509 | ---------- |
|
1516 | ---------- | |
1510 |
|
1517 | |||
1511 | text : string |
|
1518 | text : string | |
1512 | A string of text to be completed on. It can be given as empty and |
|
1519 | A string of text to be completed on. It can be given as empty and | |
1513 | instead a line/position pair are given. In this case, the |
|
1520 | instead a line/position pair are given. In this case, the | |
1514 | completer itself will split the line like readline does. |
|
1521 | completer itself will split the line like readline does. | |
1515 |
|
1522 | |||
1516 | line : string, optional |
|
1523 | line : string, optional | |
1517 | The complete line that text is part of. |
|
1524 | The complete line that text is part of. | |
1518 |
|
1525 | |||
1519 | cursor_pos : int, optional |
|
1526 | cursor_pos : int, optional | |
1520 | The position of the cursor on the input line. |
|
1527 | The position of the cursor on the input line. | |
1521 |
|
1528 | |||
1522 | Returns |
|
1529 | Returns | |
1523 | ------- |
|
1530 | ------- | |
1524 | text : string |
|
1531 | text : string | |
1525 | The actual text that was completed. |
|
1532 | The actual text that was completed. | |
1526 |
|
1533 | |||
1527 | matches : list |
|
1534 | matches : list | |
1528 | A sorted list with all possible completions. |
|
1535 | A sorted list with all possible completions. | |
1529 |
|
1536 | |||
1530 | The optional arguments allow the completion to take more context into |
|
1537 | The optional arguments allow the completion to take more context into | |
1531 | account, and are part of the low-level completion API. |
|
1538 | account, and are part of the low-level completion API. | |
1532 |
|
1539 | |||
1533 | This is a wrapper around the completion mechanism, similar to what |
|
1540 | This is a wrapper around the completion mechanism, similar to what | |
1534 | readline does at the command line when the TAB key is hit. By |
|
1541 | readline does at the command line when the TAB key is hit. By | |
1535 | exposing it as a method, it can be used by other non-readline |
|
1542 | exposing it as a method, it can be used by other non-readline | |
1536 | environments (such as GUIs) for text completion. |
|
1543 | environments (such as GUIs) for text completion. | |
1537 |
|
1544 | |||
1538 | Simple usage example: |
|
1545 | Simple usage example: | |
1539 |
|
1546 | |||
1540 | In [1]: x = 'hello' |
|
1547 | In [1]: x = 'hello' | |
1541 |
|
1548 | |||
1542 | In [2]: _ip.complete('x.l') |
|
1549 | In [2]: _ip.complete('x.l') | |
1543 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1550 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1544 | """ |
|
1551 | """ | |
1545 |
|
1552 | |||
1546 | # Inject names into __builtin__ so we can complete on the added names. |
|
1553 | # Inject names into __builtin__ so we can complete on the added names. | |
1547 | with self.builtin_trap: |
|
1554 | with self.builtin_trap: | |
1548 | return self.Completer.complete(text, line, cursor_pos) |
|
1555 | return self.Completer.complete(text, line, cursor_pos) | |
1549 |
|
1556 | |||
1550 | def set_custom_completer(self, completer, pos=0): |
|
1557 | def set_custom_completer(self, completer, pos=0): | |
1551 | """Adds a new custom completer function. |
|
1558 | """Adds a new custom completer function. | |
1552 |
|
1559 | |||
1553 | The position argument (defaults to 0) is the index in the completers |
|
1560 | The position argument (defaults to 0) is the index in the completers | |
1554 | list where you want the completer to be inserted.""" |
|
1561 | list where you want the completer to be inserted.""" | |
1555 |
|
1562 | |||
1556 | newcomp = new.instancemethod(completer,self.Completer, |
|
1563 | newcomp = new.instancemethod(completer,self.Completer, | |
1557 | self.Completer.__class__) |
|
1564 | self.Completer.__class__) | |
1558 | self.Completer.matchers.insert(pos,newcomp) |
|
1565 | self.Completer.matchers.insert(pos,newcomp) | |
1559 |
|
1566 | |||
1560 | def set_completer(self): |
|
1567 | def set_completer(self): | |
1561 | """Reset readline's completer to be our own.""" |
|
1568 | """Reset readline's completer to be our own.""" | |
1562 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1569 | self.readline.set_completer(self.Completer.rlcomplete) | |
1563 |
|
1570 | |||
1564 | def set_completer_frame(self, frame=None): |
|
1571 | def set_completer_frame(self, frame=None): | |
1565 | """Set the frame of the completer.""" |
|
1572 | """Set the frame of the completer.""" | |
1566 | if frame: |
|
1573 | if frame: | |
1567 | self.Completer.namespace = frame.f_locals |
|
1574 | self.Completer.namespace = frame.f_locals | |
1568 | self.Completer.global_namespace = frame.f_globals |
|
1575 | self.Completer.global_namespace = frame.f_globals | |
1569 | else: |
|
1576 | else: | |
1570 | self.Completer.namespace = self.user_ns |
|
1577 | self.Completer.namespace = self.user_ns | |
1571 | self.Completer.global_namespace = self.user_global_ns |
|
1578 | self.Completer.global_namespace = self.user_global_ns | |
1572 |
|
1579 | |||
1573 | #------------------------------------------------------------------------- |
|
1580 | #------------------------------------------------------------------------- | |
1574 | # Things related to readline |
|
1581 | # Things related to readline | |
1575 | #------------------------------------------------------------------------- |
|
1582 | #------------------------------------------------------------------------- | |
1576 |
|
1583 | |||
1577 | def init_readline(self): |
|
1584 | def init_readline(self): | |
1578 | """Command history completion/saving/reloading.""" |
|
1585 | """Command history completion/saving/reloading.""" | |
1579 |
|
1586 | |||
1580 | if self.readline_use: |
|
1587 | if self.readline_use: | |
1581 | import IPython.utils.rlineimpl as readline |
|
1588 | import IPython.utils.rlineimpl as readline | |
1582 |
|
1589 | |||
1583 | self.rl_next_input = None |
|
1590 | self.rl_next_input = None | |
1584 | self.rl_do_indent = False |
|
1591 | self.rl_do_indent = False | |
1585 |
|
1592 | |||
1586 | if not self.readline_use or not readline.have_readline: |
|
1593 | if not self.readline_use or not readline.have_readline: | |
1587 | self.has_readline = False |
|
1594 | self.has_readline = False | |
1588 | self.readline = None |
|
1595 | self.readline = None | |
1589 | # Set a number of methods that depend on readline to be no-op |
|
1596 | # Set a number of methods that depend on readline to be no-op | |
1590 | self.savehist = no_op |
|
1597 | self.savehist = no_op | |
1591 | self.reloadhist = no_op |
|
1598 | self.reloadhist = no_op | |
1592 | self.set_completer = no_op |
|
1599 | self.set_completer = no_op | |
1593 | self.set_custom_completer = no_op |
|
1600 | self.set_custom_completer = no_op | |
1594 | self.set_completer_frame = no_op |
|
1601 | self.set_completer_frame = no_op | |
1595 | warn('Readline services not available or not loaded.') |
|
1602 | warn('Readline services not available or not loaded.') | |
1596 | else: |
|
1603 | else: | |
1597 | self.has_readline = True |
|
1604 | self.has_readline = True | |
1598 | self.readline = readline |
|
1605 | self.readline = readline | |
1599 | sys.modules['readline'] = readline |
|
1606 | sys.modules['readline'] = readline | |
1600 | import atexit |
|
1607 | import atexit | |
1601 | from IPython.core.completer import IPCompleter |
|
1608 | from IPython.core.completer import IPCompleter | |
1602 | self.Completer = IPCompleter(self, |
|
1609 | self.Completer = IPCompleter(self, | |
1603 | self.user_ns, |
|
1610 | self.user_ns, | |
1604 | self.user_global_ns, |
|
1611 | self.user_global_ns, | |
1605 | self.readline_omit__names, |
|
1612 | self.readline_omit__names, | |
1606 | self.alias_manager.alias_table) |
|
1613 | self.alias_manager.alias_table) | |
1607 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1614 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1608 | self.strdispatchers['complete_command'] = sdisp |
|
1615 | self.strdispatchers['complete_command'] = sdisp | |
1609 | self.Completer.custom_completers = sdisp |
|
1616 | self.Completer.custom_completers = sdisp | |
1610 | # Platform-specific configuration |
|
1617 | # Platform-specific configuration | |
1611 | if os.name == 'nt': |
|
1618 | if os.name == 'nt': | |
1612 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1619 | self.readline_startup_hook = readline.set_pre_input_hook | |
1613 | else: |
|
1620 | else: | |
1614 | self.readline_startup_hook = readline.set_startup_hook |
|
1621 | self.readline_startup_hook = readline.set_startup_hook | |
1615 |
|
1622 | |||
1616 | # Load user's initrc file (readline config) |
|
1623 | # Load user's initrc file (readline config) | |
1617 | # Or if libedit is used, load editrc. |
|
1624 | # Or if libedit is used, load editrc. | |
1618 | inputrc_name = os.environ.get('INPUTRC') |
|
1625 | inputrc_name = os.environ.get('INPUTRC') | |
1619 | if inputrc_name is None: |
|
1626 | if inputrc_name is None: | |
1620 | home_dir = get_home_dir() |
|
1627 | home_dir = get_home_dir() | |
1621 | if home_dir is not None: |
|
1628 | if home_dir is not None: | |
1622 | inputrc_name = '.inputrc' |
|
1629 | inputrc_name = '.inputrc' | |
1623 | if readline.uses_libedit: |
|
1630 | if readline.uses_libedit: | |
1624 | inputrc_name = '.editrc' |
|
1631 | inputrc_name = '.editrc' | |
1625 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1632 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1626 | if os.path.isfile(inputrc_name): |
|
1633 | if os.path.isfile(inputrc_name): | |
1627 | try: |
|
1634 | try: | |
1628 | readline.read_init_file(inputrc_name) |
|
1635 | readline.read_init_file(inputrc_name) | |
1629 | except: |
|
1636 | except: | |
1630 | warn('Problems reading readline initialization file <%s>' |
|
1637 | warn('Problems reading readline initialization file <%s>' | |
1631 | % inputrc_name) |
|
1638 | % inputrc_name) | |
1632 |
|
1639 | |||
1633 | # save this in sys so embedded copies can restore it properly |
|
1640 | # save this in sys so embedded copies can restore it properly | |
1634 | sys.ipcompleter = self.Completer.rlcomplete |
|
1641 | sys.ipcompleter = self.Completer.rlcomplete | |
1635 | self.set_completer() |
|
1642 | self.set_completer() | |
1636 |
|
1643 | |||
1637 | # Configure readline according to user's prefs |
|
1644 | # Configure readline according to user's prefs | |
1638 | # This is only done if GNU readline is being used. If libedit |
|
1645 | # This is only done if GNU readline is being used. If libedit | |
1639 | # is being used (as on Leopard) the readline config is |
|
1646 | # is being used (as on Leopard) the readline config is | |
1640 | # not run as the syntax for libedit is different. |
|
1647 | # not run as the syntax for libedit is different. | |
1641 | if not readline.uses_libedit: |
|
1648 | if not readline.uses_libedit: | |
1642 | for rlcommand in self.readline_parse_and_bind: |
|
1649 | for rlcommand in self.readline_parse_and_bind: | |
1643 | #print "loading rl:",rlcommand # dbg |
|
1650 | #print "loading rl:",rlcommand # dbg | |
1644 | readline.parse_and_bind(rlcommand) |
|
1651 | readline.parse_and_bind(rlcommand) | |
1645 |
|
1652 | |||
1646 | # Remove some chars from the delimiters list. If we encounter |
|
1653 | # Remove some chars from the delimiters list. If we encounter | |
1647 | # unicode chars, discard them. |
|
1654 | # unicode chars, discard them. | |
1648 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1655 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1649 | delims = delims.translate(string._idmap, |
|
1656 | delims = delims.translate(string._idmap, | |
1650 | self.readline_remove_delims) |
|
1657 | self.readline_remove_delims) | |
1651 | readline.set_completer_delims(delims) |
|
1658 | readline.set_completer_delims(delims) | |
1652 | # otherwise we end up with a monster history after a while: |
|
1659 | # otherwise we end up with a monster history after a while: | |
1653 | readline.set_history_length(1000) |
|
1660 | readline.set_history_length(1000) | |
1654 | try: |
|
1661 | try: | |
1655 | #print '*** Reading readline history' # dbg |
|
1662 | #print '*** Reading readline history' # dbg | |
1656 | readline.read_history_file(self.histfile) |
|
1663 | readline.read_history_file(self.histfile) | |
1657 | except IOError: |
|
1664 | except IOError: | |
1658 | pass # It doesn't exist yet. |
|
1665 | pass # It doesn't exist yet. | |
1659 |
|
1666 | |||
1660 | atexit.register(self.atexit_operations) |
|
1667 | atexit.register(self.atexit_operations) | |
1661 | del atexit |
|
1668 | del atexit | |
1662 |
|
1669 | |||
1663 | # Configure auto-indent for all platforms |
|
1670 | # Configure auto-indent for all platforms | |
1664 | self.set_autoindent(self.autoindent) |
|
1671 | self.set_autoindent(self.autoindent) | |
1665 |
|
1672 | |||
1666 | def set_next_input(self, s): |
|
1673 | def set_next_input(self, s): | |
1667 | """ Sets the 'default' input string for the next command line. |
|
1674 | """ Sets the 'default' input string for the next command line. | |
1668 |
|
1675 | |||
1669 | Requires readline. |
|
1676 | Requires readline. | |
1670 |
|
1677 | |||
1671 | Example: |
|
1678 | Example: | |
1672 |
|
1679 | |||
1673 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1680 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1674 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1681 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1675 | """ |
|
1682 | """ | |
1676 |
|
1683 | |||
1677 | self.rl_next_input = s |
|
1684 | self.rl_next_input = s | |
1678 |
|
1685 | |||
1679 | # Maybe move this to the terminal subclass? |
|
1686 | # Maybe move this to the terminal subclass? | |
1680 | def pre_readline(self): |
|
1687 | def pre_readline(self): | |
1681 | """readline hook to be used at the start of each line. |
|
1688 | """readline hook to be used at the start of each line. | |
1682 |
|
1689 | |||
1683 | Currently it handles auto-indent only.""" |
|
1690 | Currently it handles auto-indent only.""" | |
1684 |
|
1691 | |||
1685 | if self.rl_do_indent: |
|
1692 | if self.rl_do_indent: | |
1686 | self.readline.insert_text(self._indent_current_str()) |
|
1693 | self.readline.insert_text(self._indent_current_str()) | |
1687 | if self.rl_next_input is not None: |
|
1694 | if self.rl_next_input is not None: | |
1688 | self.readline.insert_text(self.rl_next_input) |
|
1695 | self.readline.insert_text(self.rl_next_input) | |
1689 | self.rl_next_input = None |
|
1696 | self.rl_next_input = None | |
1690 |
|
1697 | |||
1691 | def _indent_current_str(self): |
|
1698 | def _indent_current_str(self): | |
1692 | """return the current level of indentation as a string""" |
|
1699 | """return the current level of indentation as a string""" | |
1693 | return self.indent_current_nsp * ' ' |
|
1700 | return self.indent_current_nsp * ' ' | |
1694 |
|
1701 | |||
1695 | #------------------------------------------------------------------------- |
|
1702 | #------------------------------------------------------------------------- | |
1696 | # Things related to magics |
|
1703 | # Things related to magics | |
1697 | #------------------------------------------------------------------------- |
|
1704 | #------------------------------------------------------------------------- | |
1698 |
|
1705 | |||
1699 | def init_magics(self): |
|
1706 | def init_magics(self): | |
1700 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1707 | # FIXME: Move the color initialization to the DisplayHook, which | |
1701 | # should be split into a prompt manager and displayhook. We probably |
|
1708 | # should be split into a prompt manager and displayhook. We probably | |
1702 | # even need a centralize colors management object. |
|
1709 | # even need a centralize colors management object. | |
1703 | self.magic_colors(self.colors) |
|
1710 | self.magic_colors(self.colors) | |
1704 | # History was moved to a separate module |
|
1711 | # History was moved to a separate module | |
1705 | from . import history |
|
1712 | from . import history | |
1706 | history.init_ipython(self) |
|
1713 | history.init_ipython(self) | |
1707 |
|
1714 | |||
1708 | def magic(self,arg_s): |
|
1715 | def magic(self,arg_s): | |
1709 | """Call a magic function by name. |
|
1716 | """Call a magic function by name. | |
1710 |
|
1717 | |||
1711 | Input: a string containing the name of the magic function to call and any |
|
1718 | Input: a string containing the name of the magic function to call and any | |
1712 | additional arguments to be passed to the magic. |
|
1719 | additional arguments to be passed to the magic. | |
1713 |
|
1720 | |||
1714 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1721 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1715 | prompt: |
|
1722 | prompt: | |
1716 |
|
1723 | |||
1717 | In[1]: %name -opt foo bar |
|
1724 | In[1]: %name -opt foo bar | |
1718 |
|
1725 | |||
1719 | To call a magic without arguments, simply use magic('name'). |
|
1726 | To call a magic without arguments, simply use magic('name'). | |
1720 |
|
1727 | |||
1721 | This provides a proper Python function to call IPython's magics in any |
|
1728 | This provides a proper Python function to call IPython's magics in any | |
1722 | valid Python code you can type at the interpreter, including loops and |
|
1729 | valid Python code you can type at the interpreter, including loops and | |
1723 | compound statements. |
|
1730 | compound statements. | |
1724 | """ |
|
1731 | """ | |
1725 | args = arg_s.split(' ',1) |
|
1732 | args = arg_s.split(' ',1) | |
1726 | magic_name = args[0] |
|
1733 | magic_name = args[0] | |
1727 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1734 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1728 |
|
1735 | |||
1729 | try: |
|
1736 | try: | |
1730 | magic_args = args[1] |
|
1737 | magic_args = args[1] | |
1731 | except IndexError: |
|
1738 | except IndexError: | |
1732 | magic_args = '' |
|
1739 | magic_args = '' | |
1733 | fn = getattr(self,'magic_'+magic_name,None) |
|
1740 | fn = getattr(self,'magic_'+magic_name,None) | |
1734 | if fn is None: |
|
1741 | if fn is None: | |
1735 | error("Magic function `%s` not found." % magic_name) |
|
1742 | error("Magic function `%s` not found." % magic_name) | |
1736 | else: |
|
1743 | else: | |
1737 | magic_args = self.var_expand(magic_args,1) |
|
1744 | magic_args = self.var_expand(magic_args,1) | |
1738 | with nested(self.builtin_trap,): |
|
1745 | with nested(self.builtin_trap,): | |
1739 | result = fn(magic_args) |
|
1746 | result = fn(magic_args) | |
1740 | return result |
|
1747 | return result | |
1741 |
|
1748 | |||
1742 | def define_magic(self, magicname, func): |
|
1749 | def define_magic(self, magicname, func): | |
1743 | """Expose own function as magic function for ipython |
|
1750 | """Expose own function as magic function for ipython | |
1744 |
|
1751 | |||
1745 | def foo_impl(self,parameter_s=''): |
|
1752 | def foo_impl(self,parameter_s=''): | |
1746 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1753 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1747 | print 'Magic function. Passed parameter is between < >:' |
|
1754 | print 'Magic function. Passed parameter is between < >:' | |
1748 | print '<%s>' % parameter_s |
|
1755 | print '<%s>' % parameter_s | |
1749 | print 'The self object is:',self |
|
1756 | print 'The self object is:',self | |
1750 |
|
1757 | |||
1751 | self.define_magic('foo',foo_impl) |
|
1758 | self.define_magic('foo',foo_impl) | |
1752 | """ |
|
1759 | """ | |
1753 |
|
1760 | |||
1754 | import new |
|
1761 | import new | |
1755 | im = new.instancemethod(func,self, self.__class__) |
|
1762 | im = new.instancemethod(func,self, self.__class__) | |
1756 | old = getattr(self, "magic_" + magicname, None) |
|
1763 | old = getattr(self, "magic_" + magicname, None) | |
1757 | setattr(self, "magic_" + magicname, im) |
|
1764 | setattr(self, "magic_" + magicname, im) | |
1758 | return old |
|
1765 | return old | |
1759 |
|
1766 | |||
1760 | #------------------------------------------------------------------------- |
|
1767 | #------------------------------------------------------------------------- | |
1761 | # Things related to macros |
|
1768 | # Things related to macros | |
1762 | #------------------------------------------------------------------------- |
|
1769 | #------------------------------------------------------------------------- | |
1763 |
|
1770 | |||
1764 | def define_macro(self, name, themacro): |
|
1771 | def define_macro(self, name, themacro): | |
1765 | """Define a new macro |
|
1772 | """Define a new macro | |
1766 |
|
1773 | |||
1767 | Parameters |
|
1774 | Parameters | |
1768 | ---------- |
|
1775 | ---------- | |
1769 | name : str |
|
1776 | name : str | |
1770 | The name of the macro. |
|
1777 | The name of the macro. | |
1771 | themacro : str or Macro |
|
1778 | themacro : str or Macro | |
1772 | The action to do upon invoking the macro. If a string, a new |
|
1779 | The action to do upon invoking the macro. If a string, a new | |
1773 | Macro object is created by passing the string to it. |
|
1780 | Macro object is created by passing the string to it. | |
1774 | """ |
|
1781 | """ | |
1775 |
|
1782 | |||
1776 | from IPython.core import macro |
|
1783 | from IPython.core import macro | |
1777 |
|
1784 | |||
1778 | if isinstance(themacro, basestring): |
|
1785 | if isinstance(themacro, basestring): | |
1779 | themacro = macro.Macro(themacro) |
|
1786 | themacro = macro.Macro(themacro) | |
1780 | if not isinstance(themacro, macro.Macro): |
|
1787 | if not isinstance(themacro, macro.Macro): | |
1781 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1788 | raise ValueError('A macro must be a string or a Macro instance.') | |
1782 | self.user_ns[name] = themacro |
|
1789 | self.user_ns[name] = themacro | |
1783 |
|
1790 | |||
1784 | #------------------------------------------------------------------------- |
|
1791 | #------------------------------------------------------------------------- | |
1785 | # Things related to the running of system commands |
|
1792 | # Things related to the running of system commands | |
1786 | #------------------------------------------------------------------------- |
|
1793 | #------------------------------------------------------------------------- | |
1787 |
|
1794 | |||
1788 | def system(self, cmd): |
|
1795 | def system(self, cmd): | |
1789 | """Call the given cmd in a subprocess.""" |
|
1796 | """Call the given cmd in a subprocess.""" | |
1790 | # We do not support backgrounding processes because we either use |
|
1797 | # We do not support backgrounding processes because we either use | |
1791 | # pexpect or pipes to read from. Users can always just call |
|
1798 | # pexpect or pipes to read from. Users can always just call | |
1792 | # os.system() if they really want a background process. |
|
1799 | # os.system() if they really want a background process. | |
1793 | if cmd.endswith('&'): |
|
1800 | if cmd.endswith('&'): | |
1794 | raise OSError("Background processes not supported.") |
|
1801 | raise OSError("Background processes not supported.") | |
1795 |
|
1802 | |||
1796 | return system(self.var_expand(cmd, depth=2)) |
|
1803 | return system(self.var_expand(cmd, depth=2)) | |
1797 |
|
1804 | |||
1798 | def getoutput(self, cmd): |
|
1805 | def getoutput(self, cmd): | |
1799 | """Get output (possibly including stderr) from a subprocess.""" |
|
1806 | """Get output (possibly including stderr) from a subprocess.""" | |
1800 | if cmd.endswith('&'): |
|
1807 | if cmd.endswith('&'): | |
1801 | raise OSError("Background processes not supported.") |
|
1808 | raise OSError("Background processes not supported.") | |
1802 | return getoutput(self.var_expand(cmd, depth=2)) |
|
1809 | return getoutput(self.var_expand(cmd, depth=2)) | |
1803 |
|
1810 | |||
1804 | #------------------------------------------------------------------------- |
|
1811 | #------------------------------------------------------------------------- | |
1805 | # Things related to aliases |
|
1812 | # Things related to aliases | |
1806 | #------------------------------------------------------------------------- |
|
1813 | #------------------------------------------------------------------------- | |
1807 |
|
1814 | |||
1808 | def init_alias(self): |
|
1815 | def init_alias(self): | |
1809 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1816 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1810 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1817 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1811 |
|
1818 | |||
1812 | #------------------------------------------------------------------------- |
|
1819 | #------------------------------------------------------------------------- | |
1813 | # Things related to extensions and plugins |
|
1820 | # Things related to extensions and plugins | |
1814 | #------------------------------------------------------------------------- |
|
1821 | #------------------------------------------------------------------------- | |
1815 |
|
1822 | |||
1816 | def init_extension_manager(self): |
|
1823 | def init_extension_manager(self): | |
1817 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1824 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1818 |
|
1825 | |||
1819 | def init_plugin_manager(self): |
|
1826 | def init_plugin_manager(self): | |
1820 | self.plugin_manager = PluginManager(config=self.config) |
|
1827 | self.plugin_manager = PluginManager(config=self.config) | |
1821 |
|
1828 | |||
1822 | #------------------------------------------------------------------------- |
|
1829 | #------------------------------------------------------------------------- | |
1823 | # Things related to payloads |
|
1830 | # Things related to payloads | |
1824 | #------------------------------------------------------------------------- |
|
1831 | #------------------------------------------------------------------------- | |
1825 |
|
1832 | |||
1826 | def init_payload(self): |
|
1833 | def init_payload(self): | |
1827 | self.payload_manager = PayloadManager(config=self.config) |
|
1834 | self.payload_manager = PayloadManager(config=self.config) | |
1828 |
|
1835 | |||
1829 | #------------------------------------------------------------------------- |
|
1836 | #------------------------------------------------------------------------- | |
1830 | # Things related to the prefilter |
|
1837 | # Things related to the prefilter | |
1831 | #------------------------------------------------------------------------- |
|
1838 | #------------------------------------------------------------------------- | |
1832 |
|
1839 | |||
1833 | def init_prefilter(self): |
|
1840 | def init_prefilter(self): | |
1834 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1841 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1835 | # Ultimately this will be refactored in the new interpreter code, but |
|
1842 | # Ultimately this will be refactored in the new interpreter code, but | |
1836 | # for now, we should expose the main prefilter method (there's legacy |
|
1843 | # for now, we should expose the main prefilter method (there's legacy | |
1837 | # code out there that may rely on this). |
|
1844 | # code out there that may rely on this). | |
1838 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1845 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1839 |
|
1846 | |||
1840 | #------------------------------------------------------------------------- |
|
1847 | #------------------------------------------------------------------------- | |
1841 | # Things related to extracting values/expressions from kernel and user_ns |
|
1848 | # Things related to extracting values/expressions from kernel and user_ns | |
1842 | #------------------------------------------------------------------------- |
|
1849 | #------------------------------------------------------------------------- | |
1843 |
|
1850 | |||
1844 | def _simple_error(self): |
|
1851 | def _simple_error(self): | |
1845 | etype, value = sys.exc_info()[:2] |
|
1852 | etype, value = sys.exc_info()[:2] | |
1846 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1853 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1847 |
|
1854 | |||
1848 | def get_user_variables(self, names): |
|
1855 | def get_user_variables(self, names): | |
1849 | """Get a list of variable names from the user's namespace. |
|
1856 | """Get a list of variable names from the user's namespace. | |
1850 |
|
1857 | |||
1851 | The return value is a dict with the repr() of each value. |
|
1858 | The return value is a dict with the repr() of each value. | |
1852 | """ |
|
1859 | """ | |
1853 | out = {} |
|
1860 | out = {} | |
1854 | user_ns = self.user_ns |
|
1861 | user_ns = self.user_ns | |
1855 | for varname in names: |
|
1862 | for varname in names: | |
1856 | try: |
|
1863 | try: | |
1857 | value = repr(user_ns[varname]) |
|
1864 | value = repr(user_ns[varname]) | |
1858 | except: |
|
1865 | except: | |
1859 | value = self._simple_error() |
|
1866 | value = self._simple_error() | |
1860 | out[varname] = value |
|
1867 | out[varname] = value | |
1861 | return out |
|
1868 | return out | |
1862 |
|
1869 | |||
1863 | def eval_expressions(self, expressions): |
|
1870 | def eval_expressions(self, expressions): | |
1864 | """Evaluate a dict of expressions in the user's namespace. |
|
1871 | """Evaluate a dict of expressions in the user's namespace. | |
1865 |
|
1872 | |||
1866 | The return value is a dict with the repr() of each value. |
|
1873 | The return value is a dict with the repr() of each value. | |
1867 | """ |
|
1874 | """ | |
1868 | out = {} |
|
1875 | out = {} | |
1869 | user_ns = self.user_ns |
|
1876 | user_ns = self.user_ns | |
1870 | global_ns = self.user_global_ns |
|
1877 | global_ns = self.user_global_ns | |
1871 | for key, expr in expressions.iteritems(): |
|
1878 | for key, expr in expressions.iteritems(): | |
1872 | try: |
|
1879 | try: | |
1873 | value = repr(eval(expr, global_ns, user_ns)) |
|
1880 | value = repr(eval(expr, global_ns, user_ns)) | |
1874 | except: |
|
1881 | except: | |
1875 | value = self._simple_error() |
|
1882 | value = self._simple_error() | |
1876 | out[key] = value |
|
1883 | out[key] = value | |
1877 | return out |
|
1884 | return out | |
1878 |
|
1885 | |||
1879 | #------------------------------------------------------------------------- |
|
1886 | #------------------------------------------------------------------------- | |
1880 | # Things related to the running of code |
|
1887 | # Things related to the running of code | |
1881 | #------------------------------------------------------------------------- |
|
1888 | #------------------------------------------------------------------------- | |
1882 |
|
1889 | |||
1883 | def ex(self, cmd): |
|
1890 | def ex(self, cmd): | |
1884 | """Execute a normal python statement in user namespace.""" |
|
1891 | """Execute a normal python statement in user namespace.""" | |
1885 | with nested(self.builtin_trap,): |
|
1892 | with nested(self.builtin_trap,): | |
1886 | exec cmd in self.user_global_ns, self.user_ns |
|
1893 | exec cmd in self.user_global_ns, self.user_ns | |
1887 |
|
1894 | |||
1888 | def ev(self, expr): |
|
1895 | def ev(self, expr): | |
1889 | """Evaluate python expression expr in user namespace. |
|
1896 | """Evaluate python expression expr in user namespace. | |
1890 |
|
1897 | |||
1891 | Returns the result of evaluation |
|
1898 | Returns the result of evaluation | |
1892 | """ |
|
1899 | """ | |
1893 | with nested(self.builtin_trap,): |
|
1900 | with nested(self.builtin_trap,): | |
1894 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1901 | return eval(expr, self.user_global_ns, self.user_ns) | |
1895 |
|
1902 | |||
1896 | def safe_execfile(self, fname, *where, **kw): |
|
1903 | def safe_execfile(self, fname, *where, **kw): | |
1897 | """A safe version of the builtin execfile(). |
|
1904 | """A safe version of the builtin execfile(). | |
1898 |
|
1905 | |||
1899 | This version will never throw an exception, but instead print |
|
1906 | This version will never throw an exception, but instead print | |
1900 | helpful error messages to the screen. This only works on pure |
|
1907 | helpful error messages to the screen. This only works on pure | |
1901 | Python files with the .py extension. |
|
1908 | Python files with the .py extension. | |
1902 |
|
1909 | |||
1903 | Parameters |
|
1910 | Parameters | |
1904 | ---------- |
|
1911 | ---------- | |
1905 | fname : string |
|
1912 | fname : string | |
1906 | The name of the file to be executed. |
|
1913 | The name of the file to be executed. | |
1907 | where : tuple |
|
1914 | where : tuple | |
1908 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1915 | One or two namespaces, passed to execfile() as (globals,locals). | |
1909 | If only one is given, it is passed as both. |
|
1916 | If only one is given, it is passed as both. | |
1910 | exit_ignore : bool (False) |
|
1917 | exit_ignore : bool (False) | |
1911 | If True, then silence SystemExit for non-zero status (it is always |
|
1918 | If True, then silence SystemExit for non-zero status (it is always | |
1912 | silenced for zero status, as it is so common). |
|
1919 | silenced for zero status, as it is so common). | |
1913 | """ |
|
1920 | """ | |
1914 | kw.setdefault('exit_ignore', False) |
|
1921 | kw.setdefault('exit_ignore', False) | |
1915 |
|
1922 | |||
1916 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1923 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1917 |
|
1924 | |||
1918 | # Make sure we have a .py file |
|
1925 | # Make sure we have a .py file | |
1919 | if not fname.endswith('.py'): |
|
1926 | if not fname.endswith('.py'): | |
1920 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1927 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1921 |
|
1928 | |||
1922 | # Make sure we can open the file |
|
1929 | # Make sure we can open the file | |
1923 | try: |
|
1930 | try: | |
1924 | with open(fname) as thefile: |
|
1931 | with open(fname) as thefile: | |
1925 | pass |
|
1932 | pass | |
1926 | except: |
|
1933 | except: | |
1927 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1934 | warn('Could not open file <%s> for safe execution.' % fname) | |
1928 | return |
|
1935 | return | |
1929 |
|
1936 | |||
1930 | # Find things also in current directory. This is needed to mimic the |
|
1937 | # Find things also in current directory. This is needed to mimic the | |
1931 | # behavior of running a script from the system command line, where |
|
1938 | # behavior of running a script from the system command line, where | |
1932 | # Python inserts the script's directory into sys.path |
|
1939 | # Python inserts the script's directory into sys.path | |
1933 | dname = os.path.dirname(fname) |
|
1940 | dname = os.path.dirname(fname) | |
1934 |
|
1941 | |||
1935 | with prepended_to_syspath(dname): |
|
1942 | with prepended_to_syspath(dname): | |
1936 | try: |
|
1943 | try: | |
1937 | execfile(fname,*where) |
|
1944 | execfile(fname,*where) | |
1938 | except SystemExit, status: |
|
1945 | except SystemExit, status: | |
1939 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
1946 | # If the call was made with 0 or None exit status (sys.exit(0) | |
1940 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
1947 | # or sys.exit() ), don't bother showing a traceback, as both of | |
1941 | # these are considered normal by the OS: |
|
1948 | # these are considered normal by the OS: | |
1942 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
1949 | # > python -c'import sys;sys.exit(0)'; echo $? | |
1943 | # 0 |
|
1950 | # 0 | |
1944 | # > python -c'import sys;sys.exit()'; echo $? |
|
1951 | # > python -c'import sys;sys.exit()'; echo $? | |
1945 | # 0 |
|
1952 | # 0 | |
1946 | # For other exit status, we show the exception unless |
|
1953 | # For other exit status, we show the exception unless | |
1947 | # explicitly silenced, but only in short form. |
|
1954 | # explicitly silenced, but only in short form. | |
1948 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
1955 | if status.code not in (0, None) and not kw['exit_ignore']: | |
1949 | self.showtraceback(exception_only=True) |
|
1956 | self.showtraceback(exception_only=True) | |
1950 | except: |
|
1957 | except: | |
1951 | self.showtraceback() |
|
1958 | self.showtraceback() | |
1952 |
|
1959 | |||
1953 | def safe_execfile_ipy(self, fname): |
|
1960 | def safe_execfile_ipy(self, fname): | |
1954 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1961 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
1955 |
|
1962 | |||
1956 | Parameters |
|
1963 | Parameters | |
1957 | ---------- |
|
1964 | ---------- | |
1958 | fname : str |
|
1965 | fname : str | |
1959 | The name of the file to execute. The filename must have a |
|
1966 | The name of the file to execute. The filename must have a | |
1960 | .ipy extension. |
|
1967 | .ipy extension. | |
1961 | """ |
|
1968 | """ | |
1962 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1969 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1963 |
|
1970 | |||
1964 | # Make sure we have a .py file |
|
1971 | # Make sure we have a .py file | |
1965 | if not fname.endswith('.ipy'): |
|
1972 | if not fname.endswith('.ipy'): | |
1966 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1973 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1967 |
|
1974 | |||
1968 | # Make sure we can open the file |
|
1975 | # Make sure we can open the file | |
1969 | try: |
|
1976 | try: | |
1970 | with open(fname) as thefile: |
|
1977 | with open(fname) as thefile: | |
1971 | pass |
|
1978 | pass | |
1972 | except: |
|
1979 | except: | |
1973 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1980 | warn('Could not open file <%s> for safe execution.' % fname) | |
1974 | return |
|
1981 | return | |
1975 |
|
1982 | |||
1976 | # Find things also in current directory. This is needed to mimic the |
|
1983 | # Find things also in current directory. This is needed to mimic the | |
1977 | # behavior of running a script from the system command line, where |
|
1984 | # behavior of running a script from the system command line, where | |
1978 | # Python inserts the script's directory into sys.path |
|
1985 | # Python inserts the script's directory into sys.path | |
1979 | dname = os.path.dirname(fname) |
|
1986 | dname = os.path.dirname(fname) | |
1980 |
|
1987 | |||
1981 | with prepended_to_syspath(dname): |
|
1988 | with prepended_to_syspath(dname): | |
1982 | try: |
|
1989 | try: | |
1983 | with open(fname) as thefile: |
|
1990 | with open(fname) as thefile: | |
1984 | script = thefile.read() |
|
1991 | script = thefile.read() | |
1985 | # self.runlines currently captures all exceptions |
|
1992 | # self.runlines currently captures all exceptions | |
1986 | # raise in user code. It would be nice if there were |
|
1993 | # raise in user code. It would be nice if there were | |
1987 | # versions of runlines, execfile that did raise, so |
|
1994 | # versions of runlines, execfile that did raise, so | |
1988 | # we could catch the errors. |
|
1995 | # we could catch the errors. | |
1989 | self.runlines(script, clean=True) |
|
1996 | self.runlines(script, clean=True) | |
1990 | except: |
|
1997 | except: | |
1991 | self.showtraceback() |
|
1998 | self.showtraceback() | |
1992 | warn('Unknown failure executing file: <%s>' % fname) |
|
1999 | warn('Unknown failure executing file: <%s>' % fname) | |
1993 |
|
2000 | |||
1994 | def runlines(self, lines, clean=False): |
|
2001 | def runlines(self, lines, clean=False): | |
1995 | """Run a string of one or more lines of source. |
|
2002 | """Run a string of one or more lines of source. | |
1996 |
|
2003 | |||
1997 | This method is capable of running a string containing multiple source |
|
2004 | This method is capable of running a string containing multiple source | |
1998 | lines, as if they had been entered at the IPython prompt. Since it |
|
2005 | lines, as if they had been entered at the IPython prompt. Since it | |
1999 | exposes IPython's processing machinery, the given strings can contain |
|
2006 | exposes IPython's processing machinery, the given strings can contain | |
2000 | magic calls (%magic), special shell access (!cmd), etc. |
|
2007 | magic calls (%magic), special shell access (!cmd), etc. | |
2001 | """ |
|
2008 | """ | |
2002 |
|
2009 | |||
2003 | if isinstance(lines, (list, tuple)): |
|
2010 | if isinstance(lines, (list, tuple)): | |
2004 | lines = '\n'.join(lines) |
|
2011 | lines = '\n'.join(lines) | |
2005 |
|
2012 | |||
2006 | if clean: |
|
2013 | if clean: | |
2007 | lines = self._cleanup_ipy_script(lines) |
|
2014 | lines = self._cleanup_ipy_script(lines) | |
2008 |
|
2015 | |||
2009 | # We must start with a clean buffer, in case this is run from an |
|
2016 | # We must start with a clean buffer, in case this is run from an | |
2010 | # interactive IPython session (via a magic, for example). |
|
2017 | # interactive IPython session (via a magic, for example). | |
2011 | self.resetbuffer() |
|
2018 | self.resetbuffer() | |
2012 | lines = lines.splitlines() |
|
2019 | lines = lines.splitlines() | |
2013 | more = 0 |
|
2020 | more = 0 | |
2014 | with nested(self.builtin_trap, self.display_trap): |
|
2021 | with nested(self.builtin_trap, self.display_trap): | |
2015 | for line in lines: |
|
2022 | for line in lines: | |
2016 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2023 | # skip blank lines so we don't mess up the prompt counter, but do | |
2017 | # NOT skip even a blank line if we are in a code block (more is |
|
2024 | # NOT skip even a blank line if we are in a code block (more is | |
2018 | # true) |
|
2025 | # true) | |
2019 |
|
2026 | |||
2020 | if line or more: |
|
2027 | if line or more: | |
2021 | # push to raw history, so hist line numbers stay in sync |
|
2028 | # push to raw history, so hist line numbers stay in sync | |
2022 | self.input_hist_raw.append(line + '\n') |
|
2029 | self.input_hist_raw.append(line + '\n') | |
2023 | prefiltered = self.prefilter_manager.prefilter_lines(line, |
|
2030 | prefiltered = self.prefilter_manager.prefilter_lines(line, | |
2024 | more) |
|
2031 | more) | |
2025 | more = self.push_line(prefiltered) |
|
2032 | more = self.push_line(prefiltered) | |
2026 | # IPython's runsource returns None if there was an error |
|
2033 | # IPython's runsource returns None if there was an error | |
2027 | # compiling the code. This allows us to stop processing right |
|
2034 | # compiling the code. This allows us to stop processing right | |
2028 | # away, so the user gets the error message at the right place. |
|
2035 | # away, so the user gets the error message at the right place. | |
2029 | if more is None: |
|
2036 | if more is None: | |
2030 | break |
|
2037 | break | |
2031 | else: |
|
2038 | else: | |
2032 | self.input_hist_raw.append("\n") |
|
2039 | self.input_hist_raw.append("\n") | |
2033 | # final newline in case the input didn't have it, so that the code |
|
2040 | # final newline in case the input didn't have it, so that the code | |
2034 | # actually does get executed |
|
2041 | # actually does get executed | |
2035 | if more: |
|
2042 | if more: | |
2036 | self.push_line('\n') |
|
2043 | self.push_line('\n') | |
2037 |
|
2044 | |||
2038 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2045 | def runsource(self, source, filename='<input>', symbol='single'): | |
2039 | """Compile and run some source in the interpreter. |
|
2046 | """Compile and run some source in the interpreter. | |
2040 |
|
2047 | |||
2041 | Arguments are as for compile_command(). |
|
2048 | Arguments are as for compile_command(). | |
2042 |
|
2049 | |||
2043 | One several things can happen: |
|
2050 | One several things can happen: | |
2044 |
|
2051 | |||
2045 | 1) The input is incorrect; compile_command() raised an |
|
2052 | 1) The input is incorrect; compile_command() raised an | |
2046 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2053 | exception (SyntaxError or OverflowError). A syntax traceback | |
2047 | will be printed by calling the showsyntaxerror() method. |
|
2054 | will be printed by calling the showsyntaxerror() method. | |
2048 |
|
2055 | |||
2049 | 2) The input is incomplete, and more input is required; |
|
2056 | 2) The input is incomplete, and more input is required; | |
2050 | compile_command() returned None. Nothing happens. |
|
2057 | compile_command() returned None. Nothing happens. | |
2051 |
|
2058 | |||
2052 | 3) The input is complete; compile_command() returned a code |
|
2059 | 3) The input is complete; compile_command() returned a code | |
2053 | object. The code is executed by calling self.runcode() (which |
|
2060 | object. The code is executed by calling self.runcode() (which | |
2054 | also handles run-time exceptions, except for SystemExit). |
|
2061 | also handles run-time exceptions, except for SystemExit). | |
2055 |
|
2062 | |||
2056 | The return value is: |
|
2063 | The return value is: | |
2057 |
|
2064 | |||
2058 | - True in case 2 |
|
2065 | - True in case 2 | |
2059 |
|
2066 | |||
2060 | - False in the other cases, unless an exception is raised, where |
|
2067 | - False in the other cases, unless an exception is raised, where | |
2061 | None is returned instead. This can be used by external callers to |
|
2068 | None is returned instead. This can be used by external callers to | |
2062 | know whether to continue feeding input or not. |
|
2069 | know whether to continue feeding input or not. | |
2063 |
|
2070 | |||
2064 | The return value can be used to decide whether to use sys.ps1 or |
|
2071 | The return value can be used to decide whether to use sys.ps1 or | |
2065 | sys.ps2 to prompt the next line.""" |
|
2072 | sys.ps2 to prompt the next line.""" | |
2066 |
|
2073 | |||
2067 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2074 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2068 | # this allows execution of indented pasted code. It is tempting |
|
2075 | # this allows execution of indented pasted code. It is tempting | |
2069 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2076 | # to add '\n' at the end of source to run commands like ' a=1' | |
2070 | # directly, but this fails for more complicated scenarios |
|
2077 | # directly, but this fails for more complicated scenarios | |
2071 | source=source.encode(self.stdin_encoding) |
|
2078 | source=source.encode(self.stdin_encoding) | |
2072 | if source[:1] in [' ', '\t']: |
|
2079 | if source[:1] in [' ', '\t']: | |
2073 | source = 'if 1:\n%s' % source |
|
2080 | source = 'if 1:\n%s' % source | |
2074 |
|
2081 | |||
2075 | try: |
|
2082 | try: | |
2076 | code = self.compile(source,filename,symbol) |
|
2083 | code = self.compile(source,filename,symbol) | |
2077 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2084 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2078 | # Case 1 |
|
2085 | # Case 1 | |
2079 | self.showsyntaxerror(filename) |
|
2086 | self.showsyntaxerror(filename) | |
2080 | return None |
|
2087 | return None | |
2081 |
|
2088 | |||
2082 | if code is None: |
|
2089 | if code is None: | |
2083 | # Case 2 |
|
2090 | # Case 2 | |
2084 | return True |
|
2091 | return True | |
2085 |
|
2092 | |||
2086 | # Case 3 |
|
2093 | # Case 3 | |
2087 | # We store the code object so that threaded shells and |
|
2094 | # We store the code object so that threaded shells and | |
2088 | # custom exception handlers can access all this info if needed. |
|
2095 | # custom exception handlers can access all this info if needed. | |
2089 | # The source corresponding to this can be obtained from the |
|
2096 | # The source corresponding to this can be obtained from the | |
2090 | # buffer attribute as '\n'.join(self.buffer). |
|
2097 | # buffer attribute as '\n'.join(self.buffer). | |
2091 | self.code_to_run = code |
|
2098 | self.code_to_run = code | |
2092 | # now actually execute the code object |
|
2099 | # now actually execute the code object | |
2093 | if self.runcode(code) == 0: |
|
2100 | if self.runcode(code) == 0: | |
2094 | return False |
|
2101 | return False | |
2095 | else: |
|
2102 | else: | |
2096 | return None |
|
2103 | return None | |
2097 |
|
2104 | |||
2098 | def runcode(self,code_obj): |
|
2105 | def runcode(self,code_obj): | |
2099 | """Execute a code object. |
|
2106 | """Execute a code object. | |
2100 |
|
2107 | |||
2101 | When an exception occurs, self.showtraceback() is called to display a |
|
2108 | When an exception occurs, self.showtraceback() is called to display a | |
2102 | traceback. |
|
2109 | traceback. | |
2103 |
|
2110 | |||
2104 | Return value: a flag indicating whether the code to be run completed |
|
2111 | Return value: a flag indicating whether the code to be run completed | |
2105 | successfully: |
|
2112 | successfully: | |
2106 |
|
2113 | |||
2107 | - 0: successful execution. |
|
2114 | - 0: successful execution. | |
2108 | - 1: an error occurred. |
|
2115 | - 1: an error occurred. | |
2109 | """ |
|
2116 | """ | |
2110 |
|
2117 | |||
2111 | # Set our own excepthook in case the user code tries to call it |
|
2118 | # Set our own excepthook in case the user code tries to call it | |
2112 | # directly, so that the IPython crash handler doesn't get triggered |
|
2119 | # directly, so that the IPython crash handler doesn't get triggered | |
2113 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2120 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2114 |
|
2121 | |||
2115 | # we save the original sys.excepthook in the instance, in case config |
|
2122 | # we save the original sys.excepthook in the instance, in case config | |
2116 | # code (such as magics) needs access to it. |
|
2123 | # code (such as magics) needs access to it. | |
2117 | self.sys_excepthook = old_excepthook |
|
2124 | self.sys_excepthook = old_excepthook | |
2118 | outflag = 1 # happens in more places, so it's easier as default |
|
2125 | outflag = 1 # happens in more places, so it's easier as default | |
2119 | try: |
|
2126 | try: | |
2120 | try: |
|
2127 | try: | |
2121 | self.hooks.pre_runcode_hook() |
|
2128 | self.hooks.pre_runcode_hook() | |
2122 | #rprint('Running code') # dbg |
|
2129 | #rprint('Running code') # dbg | |
2123 | exec code_obj in self.user_global_ns, self.user_ns |
|
2130 | exec code_obj in self.user_global_ns, self.user_ns | |
2124 | finally: |
|
2131 | finally: | |
2125 | # Reset our crash handler in place |
|
2132 | # Reset our crash handler in place | |
2126 | sys.excepthook = old_excepthook |
|
2133 | sys.excepthook = old_excepthook | |
2127 | except SystemExit: |
|
2134 | except SystemExit: | |
2128 | self.resetbuffer() |
|
2135 | self.resetbuffer() | |
2129 | self.showtraceback(exception_only=True) |
|
2136 | self.showtraceback(exception_only=True) | |
2130 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2137 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2131 | except self.custom_exceptions: |
|
2138 | except self.custom_exceptions: | |
2132 | etype,value,tb = sys.exc_info() |
|
2139 | etype,value,tb = sys.exc_info() | |
2133 | self.CustomTB(etype,value,tb) |
|
2140 | self.CustomTB(etype,value,tb) | |
2134 | except: |
|
2141 | except: | |
2135 | self.showtraceback() |
|
2142 | self.showtraceback() | |
2136 | else: |
|
2143 | else: | |
2137 | outflag = 0 |
|
2144 | outflag = 0 | |
2138 | if softspace(sys.stdout, 0): |
|
2145 | if softspace(sys.stdout, 0): | |
2139 |
|
2146 | |||
2140 | # Flush out code object which has been run (and source) |
|
2147 | # Flush out code object which has been run (and source) | |
2141 | self.code_to_run = None |
|
2148 | self.code_to_run = None | |
2142 | return outflag |
|
2149 | return outflag | |
2143 |
|
2150 | |||
2144 | def push_line(self, line): |
|
2151 | def push_line(self, line): | |
2145 | """Push a line to the interpreter. |
|
2152 | """Push a line to the interpreter. | |
2146 |
|
2153 | |||
2147 | The line should not have a trailing newline; it may have |
|
2154 | The line should not have a trailing newline; it may have | |
2148 | internal newlines. The line is appended to a buffer and the |
|
2155 | internal newlines. The line is appended to a buffer and the | |
2149 | interpreter's runsource() method is called with the |
|
2156 | interpreter's runsource() method is called with the | |
2150 | concatenated contents of the buffer as source. If this |
|
2157 | concatenated contents of the buffer as source. If this | |
2151 | indicates that the command was executed or invalid, the buffer |
|
2158 | indicates that the command was executed or invalid, the buffer | |
2152 | is reset; otherwise, the command is incomplete, and the buffer |
|
2159 | is reset; otherwise, the command is incomplete, and the buffer | |
2153 | is left as it was after the line was appended. The return |
|
2160 | is left as it was after the line was appended. The return | |
2154 | value is 1 if more input is required, 0 if the line was dealt |
|
2161 | value is 1 if more input is required, 0 if the line was dealt | |
2155 | with in some way (this is the same as runsource()). |
|
2162 | with in some way (this is the same as runsource()). | |
2156 | """ |
|
2163 | """ | |
2157 |
|
2164 | |||
2158 | # autoindent management should be done here, and not in the |
|
2165 | # autoindent management should be done here, and not in the | |
2159 | # interactive loop, since that one is only seen by keyboard input. We |
|
2166 | # interactive loop, since that one is only seen by keyboard input. We | |
2160 | # need this done correctly even for code run via runlines (which uses |
|
2167 | # need this done correctly even for code run via runlines (which uses | |
2161 | # push). |
|
2168 | # push). | |
2162 |
|
2169 | |||
2163 | #print 'push line: <%s>' % line # dbg |
|
2170 | #print 'push line: <%s>' % line # dbg | |
2164 | for subline in line.splitlines(): |
|
2171 | for subline in line.splitlines(): | |
2165 | self._autoindent_update(subline) |
|
2172 | self._autoindent_update(subline) | |
2166 | self.buffer.append(line) |
|
2173 | self.buffer.append(line) | |
2167 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2174 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2168 | if not more: |
|
2175 | if not more: | |
2169 | self.resetbuffer() |
|
2176 | self.resetbuffer() | |
2170 | return more |
|
2177 | return more | |
2171 |
|
2178 | |||
2172 | def resetbuffer(self): |
|
2179 | def resetbuffer(self): | |
2173 | """Reset the input buffer.""" |
|
2180 | """Reset the input buffer.""" | |
2174 | self.buffer[:] = [] |
|
2181 | self.buffer[:] = [] | |
2175 |
|
2182 | |||
2176 | def _is_secondary_block_start(self, s): |
|
2183 | def _is_secondary_block_start(self, s): | |
2177 | if not s.endswith(':'): |
|
2184 | if not s.endswith(':'): | |
2178 | return False |
|
2185 | return False | |
2179 | if (s.startswith('elif') or |
|
2186 | if (s.startswith('elif') or | |
2180 | s.startswith('else') or |
|
2187 | s.startswith('else') or | |
2181 | s.startswith('except') or |
|
2188 | s.startswith('except') or | |
2182 | s.startswith('finally')): |
|
2189 | s.startswith('finally')): | |
2183 | return True |
|
2190 | return True | |
2184 |
|
2191 | |||
2185 | def _cleanup_ipy_script(self, script): |
|
2192 | def _cleanup_ipy_script(self, script): | |
2186 | """Make a script safe for self.runlines() |
|
2193 | """Make a script safe for self.runlines() | |
2187 |
|
2194 | |||
2188 | Currently, IPython is lines based, with blocks being detected by |
|
2195 | Currently, IPython is lines based, with blocks being detected by | |
2189 | empty lines. This is a problem for block based scripts that may |
|
2196 | empty lines. This is a problem for block based scripts that may | |
2190 | not have empty lines after blocks. This script adds those empty |
|
2197 | not have empty lines after blocks. This script adds those empty | |
2191 | lines to make scripts safe for running in the current line based |
|
2198 | lines to make scripts safe for running in the current line based | |
2192 | IPython. |
|
2199 | IPython. | |
2193 | """ |
|
2200 | """ | |
2194 | res = [] |
|
2201 | res = [] | |
2195 | lines = script.splitlines() |
|
2202 | lines = script.splitlines() | |
2196 | level = 0 |
|
2203 | level = 0 | |
2197 |
|
2204 | |||
2198 | for l in lines: |
|
2205 | for l in lines: | |
2199 | lstripped = l.lstrip() |
|
2206 | lstripped = l.lstrip() | |
2200 | stripped = l.strip() |
|
2207 | stripped = l.strip() | |
2201 | if not stripped: |
|
2208 | if not stripped: | |
2202 | continue |
|
2209 | continue | |
2203 | newlevel = len(l) - len(lstripped) |
|
2210 | newlevel = len(l) - len(lstripped) | |
2204 | if level > 0 and newlevel == 0 and \ |
|
2211 | if level > 0 and newlevel == 0 and \ | |
2205 | not self._is_secondary_block_start(stripped): |
|
2212 | not self._is_secondary_block_start(stripped): | |
2206 | # add empty line |
|
2213 | # add empty line | |
2207 | res.append('') |
|
2214 | res.append('') | |
2208 | res.append(l) |
|
2215 | res.append(l) | |
2209 | level = newlevel |
|
2216 | level = newlevel | |
2210 |
|
2217 | |||
2211 | return '\n'.join(res) + '\n' |
|
2218 | return '\n'.join(res) + '\n' | |
2212 |
|
2219 | |||
2213 | def _autoindent_update(self,line): |
|
2220 | def _autoindent_update(self,line): | |
2214 | """Keep track of the indent level.""" |
|
2221 | """Keep track of the indent level.""" | |
2215 |
|
2222 | |||
2216 | #debugx('line') |
|
2223 | #debugx('line') | |
2217 | #debugx('self.indent_current_nsp') |
|
2224 | #debugx('self.indent_current_nsp') | |
2218 | if self.autoindent: |
|
2225 | if self.autoindent: | |
2219 | if line: |
|
2226 | if line: | |
2220 | inisp = num_ini_spaces(line) |
|
2227 | inisp = num_ini_spaces(line) | |
2221 | if inisp < self.indent_current_nsp: |
|
2228 | if inisp < self.indent_current_nsp: | |
2222 | self.indent_current_nsp = inisp |
|
2229 | self.indent_current_nsp = inisp | |
2223 |
|
2230 | |||
2224 | if line[-1] == ':': |
|
2231 | if line[-1] == ':': | |
2225 | self.indent_current_nsp += 4 |
|
2232 | self.indent_current_nsp += 4 | |
2226 | elif dedent_re.match(line): |
|
2233 | elif dedent_re.match(line): | |
2227 | self.indent_current_nsp -= 4 |
|
2234 | self.indent_current_nsp -= 4 | |
2228 | else: |
|
2235 | else: | |
2229 | self.indent_current_nsp = 0 |
|
2236 | self.indent_current_nsp = 0 | |
2230 |
|
2237 | |||
2231 | #------------------------------------------------------------------------- |
|
2238 | #------------------------------------------------------------------------- | |
2232 | # Things related to GUI support and pylab |
|
2239 | # Things related to GUI support and pylab | |
2233 | #------------------------------------------------------------------------- |
|
2240 | #------------------------------------------------------------------------- | |
2234 |
|
2241 | |||
2235 | def enable_pylab(self, gui=None): |
|
2242 | def enable_pylab(self, gui=None): | |
2236 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2243 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2237 |
|
2244 | |||
2238 | #------------------------------------------------------------------------- |
|
2245 | #------------------------------------------------------------------------- | |
2239 | # Utilities |
|
2246 | # Utilities | |
2240 | #------------------------------------------------------------------------- |
|
2247 | #------------------------------------------------------------------------- | |
2241 |
|
2248 | |||
2242 | def var_expand(self,cmd,depth=0): |
|
2249 | def var_expand(self,cmd,depth=0): | |
2243 | """Expand python variables in a string. |
|
2250 | """Expand python variables in a string. | |
2244 |
|
2251 | |||
2245 | The depth argument indicates how many frames above the caller should |
|
2252 | The depth argument indicates how many frames above the caller should | |
2246 | be walked to look for the local namespace where to expand variables. |
|
2253 | be walked to look for the local namespace where to expand variables. | |
2247 |
|
2254 | |||
2248 | The global namespace for expansion is always the user's interactive |
|
2255 | The global namespace for expansion is always the user's interactive | |
2249 | namespace. |
|
2256 | namespace. | |
2250 | """ |
|
2257 | """ | |
2251 |
|
2258 | |||
2252 | return str(ItplNS(cmd, |
|
2259 | return str(ItplNS(cmd, | |
2253 | self.user_ns, # globals |
|
2260 | self.user_ns, # globals | |
2254 | # Skip our own frame in searching for locals: |
|
2261 | # Skip our own frame in searching for locals: | |
2255 | sys._getframe(depth+1).f_locals # locals |
|
2262 | sys._getframe(depth+1).f_locals # locals | |
2256 | )) |
|
2263 | )) | |
2257 |
|
2264 | |||
2258 | def mktempfile(self,data=None): |
|
2265 | def mktempfile(self,data=None): | |
2259 | """Make a new tempfile and return its filename. |
|
2266 | """Make a new tempfile and return its filename. | |
2260 |
|
2267 | |||
2261 | This makes a call to tempfile.mktemp, but it registers the created |
|
2268 | This makes a call to tempfile.mktemp, but it registers the created | |
2262 | filename internally so ipython cleans it up at exit time. |
|
2269 | filename internally so ipython cleans it up at exit time. | |
2263 |
|
2270 | |||
2264 | Optional inputs: |
|
2271 | Optional inputs: | |
2265 |
|
2272 | |||
2266 | - data(None): if data is given, it gets written out to the temp file |
|
2273 | - data(None): if data is given, it gets written out to the temp file | |
2267 | immediately, and the file is closed again.""" |
|
2274 | immediately, and the file is closed again.""" | |
2268 |
|
2275 | |||
2269 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2276 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2270 | self.tempfiles.append(filename) |
|
2277 | self.tempfiles.append(filename) | |
2271 |
|
2278 | |||
2272 | if data: |
|
2279 | if data: | |
2273 | tmp_file = open(filename,'w') |
|
2280 | tmp_file = open(filename,'w') | |
2274 | tmp_file.write(data) |
|
2281 | tmp_file.write(data) | |
2275 | tmp_file.close() |
|
2282 | tmp_file.close() | |
2276 | return filename |
|
2283 | return filename | |
2277 |
|
2284 | |||
2278 | # TODO: This should be removed when Term is refactored. |
|
2285 | # TODO: This should be removed when Term is refactored. | |
2279 | def write(self,data): |
|
2286 | def write(self,data): | |
2280 | """Write a string to the default output""" |
|
2287 | """Write a string to the default output""" | |
2281 | io.Term.cout.write(data) |
|
2288 | io.Term.cout.write(data) | |
2282 |
|
2289 | |||
2283 | # TODO: This should be removed when Term is refactored. |
|
2290 | # TODO: This should be removed when Term is refactored. | |
2284 | def write_err(self,data): |
|
2291 | def write_err(self,data): | |
2285 | """Write a string to the default error output""" |
|
2292 | """Write a string to the default error output""" | |
2286 | io.Term.cerr.write(data) |
|
2293 | io.Term.cerr.write(data) | |
2287 |
|
2294 | |||
2288 | def ask_yes_no(self,prompt,default=True): |
|
2295 | def ask_yes_no(self,prompt,default=True): | |
2289 | if self.quiet: |
|
2296 | if self.quiet: | |
2290 | return True |
|
2297 | return True | |
2291 | return ask_yes_no(prompt,default) |
|
2298 | return ask_yes_no(prompt,default) | |
2292 |
|
2299 | |||
2293 | def show_usage(self): |
|
2300 | def show_usage(self): | |
2294 | """Show a usage message""" |
|
2301 | """Show a usage message""" | |
2295 | page.page(IPython.core.usage.interactive_usage) |
|
2302 | page.page(IPython.core.usage.interactive_usage) | |
2296 |
|
2303 | |||
2297 | #------------------------------------------------------------------------- |
|
2304 | #------------------------------------------------------------------------- | |
2298 | # Things related to IPython exiting |
|
2305 | # Things related to IPython exiting | |
2299 | #------------------------------------------------------------------------- |
|
2306 | #------------------------------------------------------------------------- | |
2300 |
|
2307 | |||
2301 | def atexit_operations(self): |
|
2308 | def atexit_operations(self): | |
2302 | """This will be executed at the time of exit. |
|
2309 | """This will be executed at the time of exit. | |
2303 |
|
2310 | |||
2304 | Saving of persistent data should be performed here. |
|
2311 | Saving of persistent data should be performed here. | |
2305 | """ |
|
2312 | """ | |
2306 | self.savehist() |
|
2313 | self.savehist() | |
2307 |
|
2314 | |||
2308 | # Cleanup all tempfiles left around |
|
2315 | # Cleanup all tempfiles left around | |
2309 | for tfile in self.tempfiles: |
|
2316 | for tfile in self.tempfiles: | |
2310 | try: |
|
2317 | try: | |
2311 | os.unlink(tfile) |
|
2318 | os.unlink(tfile) | |
2312 | except OSError: |
|
2319 | except OSError: | |
2313 | pass |
|
2320 | pass | |
2314 |
|
2321 | |||
2315 | # Clear all user namespaces to release all references cleanly. |
|
2322 | # Clear all user namespaces to release all references cleanly. | |
2316 | self.reset() |
|
2323 | self.reset() | |
2317 |
|
2324 | |||
2318 | # Run user hooks |
|
2325 | # Run user hooks | |
2319 | self.hooks.shutdown_hook() |
|
2326 | self.hooks.shutdown_hook() | |
2320 |
|
2327 | |||
2321 | def cleanup(self): |
|
2328 | def cleanup(self): | |
2322 | self.restore_sys_module_state() |
|
2329 | self.restore_sys_module_state() | |
2323 |
|
2330 | |||
2324 |
|
2331 | |||
2325 | class InteractiveShellABC(object): |
|
2332 | class InteractiveShellABC(object): | |
2326 | """An abstract base class for InteractiveShell.""" |
|
2333 | """An abstract base class for InteractiveShell.""" | |
2327 | __metaclass__ = abc.ABCMeta |
|
2334 | __metaclass__ = abc.ABCMeta | |
2328 |
|
2335 | |||
2329 | InteractiveShellABC.register(InteractiveShell) |
|
2336 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,3491 +1,3482 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-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 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__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
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 | # print_function was added to __future__ in Python2.6, remove this when we drop |
|
44 | # print_function was added to __future__ in Python2.6, remove this when we drop | |
45 | # 2.5 compatibility |
|
45 | # 2.5 compatibility | |
46 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): |
|
46 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): | |
47 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 |
|
47 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 | |
48 |
|
48 | |||
49 | import IPython |
|
49 | import IPython | |
50 | from IPython.core import debugger, oinspect |
|
50 | from IPython.core import debugger, oinspect | |
51 | from IPython.core.error import TryNext |
|
51 | from IPython.core.error import TryNext | |
52 | from IPython.core.error import UsageError |
|
52 | from IPython.core.error import UsageError | |
53 | from IPython.core.fakemodule import FakeModule |
|
53 | from IPython.core.fakemodule import FakeModule | |
54 | from IPython.core.macro import Macro |
|
54 | from IPython.core.macro import Macro | |
55 | from IPython.core import page |
|
55 | from IPython.core import page | |
56 | from IPython.core.prefilter import ESC_MAGIC |
|
56 | from IPython.core.prefilter import ESC_MAGIC | |
57 | from IPython.lib.pylabtools import mpl_runner |
|
57 | from IPython.lib.pylabtools import mpl_runner | |
58 | from IPython.external.Itpl import itpl, printpl |
|
58 | from IPython.external.Itpl import itpl, printpl | |
59 | from IPython.testing import decorators as testdec |
|
59 | from IPython.testing import decorators as testdec | |
60 | from IPython.utils.io import file_read, nlprint |
|
60 | from IPython.utils.io import file_read, nlprint | |
61 | import IPython.utils.io |
|
61 | import IPython.utils.io | |
62 | from IPython.utils.path import get_py_filename |
|
62 | from IPython.utils.path import get_py_filename | |
63 | from IPython.utils.process import arg_split, abbrev_cwd |
|
63 | from IPython.utils.process import arg_split, abbrev_cwd | |
64 | from IPython.utils.terminal import set_term_title |
|
64 | from IPython.utils.terminal import set_term_title | |
65 | from IPython.utils.text import LSString, SList, StringTypes |
|
65 | from IPython.utils.text import LSString, SList, StringTypes, format_screen | |
66 | from IPython.utils.timing import clock, clock2 |
|
66 | from IPython.utils.timing import clock, clock2 | |
67 | from IPython.utils.warn import warn, error |
|
67 | from IPython.utils.warn import warn, error | |
68 | from IPython.utils.ipstruct import Struct |
|
68 | from IPython.utils.ipstruct import Struct | |
69 | import IPython.utils.generics |
|
69 | import IPython.utils.generics | |
70 |
|
70 | |||
71 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
72 | # Utility functions |
|
72 | # Utility functions | |
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 |
|
74 | |||
75 | def on_off(tag): |
|
75 | def on_off(tag): | |
76 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
76 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
77 | return ['OFF','ON'][tag] |
|
77 | return ['OFF','ON'][tag] | |
78 |
|
78 | |||
79 | class Bunch: pass |
|
79 | class Bunch: pass | |
80 |
|
80 | |||
81 | def compress_dhist(dh): |
|
81 | def compress_dhist(dh): | |
82 | head, tail = dh[:-10], dh[-10:] |
|
82 | head, tail = dh[:-10], dh[-10:] | |
83 |
|
83 | |||
84 | newhead = [] |
|
84 | newhead = [] | |
85 | done = set() |
|
85 | done = set() | |
86 | for h in head: |
|
86 | for h in head: | |
87 | if h in done: |
|
87 | if h in done: | |
88 | continue |
|
88 | continue | |
89 | newhead.append(h) |
|
89 | newhead.append(h) | |
90 | done.add(h) |
|
90 | done.add(h) | |
91 |
|
91 | |||
92 | return newhead + tail |
|
92 | return newhead + tail | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | #*************************************************************************** |
|
95 | #*************************************************************************** | |
96 | # Main class implementing Magic functionality |
|
96 | # Main class implementing Magic functionality | |
97 |
|
97 | |||
98 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
98 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
99 | # on construction of the main InteractiveShell object. Something odd is going |
|
99 | # on construction of the main InteractiveShell object. Something odd is going | |
100 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
100 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
101 | # eventually this needs to be clarified. |
|
101 | # eventually this needs to be clarified. | |
102 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
102 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
103 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
103 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
104 | # make Magic a configurable that InteractiveShell does not subclass. |
|
104 | # make Magic a configurable that InteractiveShell does not subclass. | |
105 |
|
105 | |||
106 | class Magic: |
|
106 | class Magic: | |
107 | """Magic functions for InteractiveShell. |
|
107 | """Magic functions for InteractiveShell. | |
108 |
|
108 | |||
109 | Shell functions which can be reached as %function_name. All magic |
|
109 | Shell functions which can be reached as %function_name. All magic | |
110 | functions should accept a string, which they can parse for their own |
|
110 | functions should accept a string, which they can parse for their own | |
111 | needs. This can make some functions easier to type, eg `%cd ../` |
|
111 | needs. This can make some functions easier to type, eg `%cd ../` | |
112 | vs. `%cd("../")` |
|
112 | vs. `%cd("../")` | |
113 |
|
113 | |||
114 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
114 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
115 | at the command line, but it is is needed in the definition. """ |
|
115 | at the command line, but it is is needed in the definition. """ | |
116 |
|
116 | |||
117 | # class globals |
|
117 | # class globals | |
118 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
118 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
119 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
119 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
120 |
|
120 | |||
121 | #...................................................................... |
|
121 | #...................................................................... | |
122 | # some utility functions |
|
122 | # some utility functions | |
123 |
|
123 | |||
124 | def __init__(self,shell): |
|
124 | def __init__(self,shell): | |
125 |
|
125 | |||
126 | self.options_table = {} |
|
126 | self.options_table = {} | |
127 | if profile is None: |
|
127 | if profile is None: | |
128 | self.magic_prun = self.profile_missing_notice |
|
128 | self.magic_prun = self.profile_missing_notice | |
129 | self.shell = shell |
|
129 | self.shell = shell | |
130 |
|
130 | |||
131 | # namespace for holding state we may need |
|
131 | # namespace for holding state we may need | |
132 | self._magic_state = Bunch() |
|
132 | self._magic_state = Bunch() | |
133 |
|
133 | |||
134 | def profile_missing_notice(self, *args, **kwargs): |
|
134 | def profile_missing_notice(self, *args, **kwargs): | |
135 | error("""\ |
|
135 | error("""\ | |
136 | The profile module could not be found. It has been removed from the standard |
|
136 | The profile module could not be found. It has been removed from the standard | |
137 | python packages because of its non-free license. To use profiling, install the |
|
137 | python packages because of its non-free license. To use profiling, install the | |
138 | python-profiler package from non-free.""") |
|
138 | python-profiler package from non-free.""") | |
139 |
|
139 | |||
140 | def default_option(self,fn,optstr): |
|
140 | def default_option(self,fn,optstr): | |
141 | """Make an entry in the options_table for fn, with value optstr""" |
|
141 | """Make an entry in the options_table for fn, with value optstr""" | |
142 |
|
142 | |||
143 | if fn not in self.lsmagic(): |
|
143 | if fn not in self.lsmagic(): | |
144 | error("%s is not a magic function" % fn) |
|
144 | error("%s is not a magic function" % fn) | |
145 | self.options_table[fn] = optstr |
|
145 | self.options_table[fn] = optstr | |
146 |
|
146 | |||
147 | def lsmagic(self): |
|
147 | def lsmagic(self): | |
148 | """Return a list of currently available magic functions. |
|
148 | """Return a list of currently available magic functions. | |
149 |
|
149 | |||
150 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
150 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
151 | ['magic_ls','magic_cd',...]""" |
|
151 | ['magic_ls','magic_cd',...]""" | |
152 |
|
152 | |||
153 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
153 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
154 |
|
154 | |||
155 | # magics in class definition |
|
155 | # magics in class definition | |
156 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
156 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
157 | callable(Magic.__dict__[fn]) |
|
157 | callable(Magic.__dict__[fn]) | |
158 | # in instance namespace (run-time user additions) |
|
158 | # in instance namespace (run-time user additions) | |
159 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
159 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
160 | callable(self.__dict__[fn]) |
|
160 | callable(self.__dict__[fn]) | |
161 | # and bound magics by user (so they can access self): |
|
161 | # and bound magics by user (so they can access self): | |
162 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
162 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
163 | callable(self.__class__.__dict__[fn]) |
|
163 | callable(self.__class__.__dict__[fn]) | |
164 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
164 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
165 | filter(inst_magic,self.__dict__.keys()) + \ |
|
165 | filter(inst_magic,self.__dict__.keys()) + \ | |
166 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
166 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
167 | out = [] |
|
167 | out = [] | |
168 | for fn in set(magics): |
|
168 | for fn in set(magics): | |
169 | out.append(fn.replace('magic_','',1)) |
|
169 | out.append(fn.replace('magic_','',1)) | |
170 | out.sort() |
|
170 | out.sort() | |
171 | return out |
|
171 | return out | |
172 |
|
172 | |||
173 | def extract_input_slices(self,slices,raw=False): |
|
173 | def extract_input_slices(self,slices,raw=False): | |
174 | """Return as a string a set of input history slices. |
|
174 | """Return as a string a set of input history slices. | |
175 |
|
175 | |||
176 | Inputs: |
|
176 | Inputs: | |
177 |
|
177 | |||
178 | - slices: the set of slices is given as a list of strings (like |
|
178 | - slices: the set of slices is given as a list of strings (like | |
179 | ['1','4:8','9'], since this function is for use by magic functions |
|
179 | ['1','4:8','9'], since this function is for use by magic functions | |
180 | which get their arguments as strings. |
|
180 | which get their arguments as strings. | |
181 |
|
181 | |||
182 | Optional inputs: |
|
182 | Optional inputs: | |
183 |
|
183 | |||
184 | - raw(False): by default, the processed input is used. If this is |
|
184 | - raw(False): by default, the processed input is used. If this is | |
185 | true, the raw input history is used instead. |
|
185 | true, the raw input history is used instead. | |
186 |
|
186 | |||
187 | Note that slices can be called with two notations: |
|
187 | Note that slices can be called with two notations: | |
188 |
|
188 | |||
189 | N:M -> standard python form, means including items N...(M-1). |
|
189 | N:M -> standard python form, means including items N...(M-1). | |
190 |
|
190 | |||
191 | N-M -> include items N..M (closed endpoint).""" |
|
191 | N-M -> include items N..M (closed endpoint).""" | |
192 |
|
192 | |||
193 | if raw: |
|
193 | if raw: | |
194 | hist = self.shell.input_hist_raw |
|
194 | hist = self.shell.input_hist_raw | |
195 | else: |
|
195 | else: | |
196 | hist = self.shell.input_hist |
|
196 | hist = self.shell.input_hist | |
197 |
|
197 | |||
198 | cmds = [] |
|
198 | cmds = [] | |
199 | for chunk in slices: |
|
199 | for chunk in slices: | |
200 | if ':' in chunk: |
|
200 | if ':' in chunk: | |
201 | ini,fin = map(int,chunk.split(':')) |
|
201 | ini,fin = map(int,chunk.split(':')) | |
202 | elif '-' in chunk: |
|
202 | elif '-' in chunk: | |
203 | ini,fin = map(int,chunk.split('-')) |
|
203 | ini,fin = map(int,chunk.split('-')) | |
204 | fin += 1 |
|
204 | fin += 1 | |
205 | else: |
|
205 | else: | |
206 | ini = int(chunk) |
|
206 | ini = int(chunk) | |
207 | fin = ini+1 |
|
207 | fin = ini+1 | |
208 | cmds.append(hist[ini:fin]) |
|
208 | cmds.append(hist[ini:fin]) | |
209 | return cmds |
|
209 | return cmds | |
210 |
|
210 | |||
211 | def arg_err(self,func): |
|
211 | def arg_err(self,func): | |
212 | """Print docstring if incorrect arguments were passed""" |
|
212 | """Print docstring if incorrect arguments were passed""" | |
213 | print 'Error in arguments:' |
|
213 | print 'Error in arguments:' | |
214 | print oinspect.getdoc(func) |
|
214 | print oinspect.getdoc(func) | |
215 |
|
215 | |||
216 | def format_latex(self,strng): |
|
216 | def format_latex(self,strng): | |
217 | """Format a string for latex inclusion.""" |
|
217 | """Format a string for latex inclusion.""" | |
218 |
|
218 | |||
219 | # Characters that need to be escaped for latex: |
|
219 | # Characters that need to be escaped for latex: | |
220 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
220 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
221 | # Magic command names as headers: |
|
221 | # Magic command names as headers: | |
222 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
222 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
223 | re.MULTILINE) |
|
223 | re.MULTILINE) | |
224 | # Magic commands |
|
224 | # Magic commands | |
225 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
225 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
226 | re.MULTILINE) |
|
226 | re.MULTILINE) | |
227 | # Paragraph continue |
|
227 | # Paragraph continue | |
228 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
228 | par_re = re.compile(r'\\$',re.MULTILINE) | |
229 |
|
229 | |||
230 | # The "\n" symbol |
|
230 | # The "\n" symbol | |
231 | newline_re = re.compile(r'\\n') |
|
231 | newline_re = re.compile(r'\\n') | |
232 |
|
232 | |||
233 | # Now build the string for output: |
|
233 | # Now build the string for output: | |
234 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
234 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
235 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
235 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
236 | strng) |
|
236 | strng) | |
237 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
237 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
238 | strng = par_re.sub(r'\\\\',strng) |
|
238 | strng = par_re.sub(r'\\\\',strng) | |
239 | strng = escape_re.sub(r'\\\1',strng) |
|
239 | strng = escape_re.sub(r'\\\1',strng) | |
240 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
240 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
241 | return strng |
|
241 | return strng | |
242 |
|
242 | |||
243 | def format_screen(self,strng): |
|
|||
244 | """Format a string for screen printing. |
|
|||
245 |
|
||||
246 | This removes some latex-type format codes.""" |
|
|||
247 | # Paragraph continue |
|
|||
248 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
|||
249 | strng = par_re.sub('',strng) |
|
|||
250 | return strng |
|
|||
251 |
|
||||
252 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
243 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
253 | """Parse options passed to an argument string. |
|
244 | """Parse options passed to an argument string. | |
254 |
|
245 | |||
255 | The interface is similar to that of getopt(), but it returns back a |
|
246 | The interface is similar to that of getopt(), but it returns back a | |
256 | Struct with the options as keys and the stripped argument string still |
|
247 | Struct with the options as keys and the stripped argument string still | |
257 | as a string. |
|
248 | as a string. | |
258 |
|
249 | |||
259 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
250 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
260 | This allows us to easily expand variables, glob files, quote |
|
251 | This allows us to easily expand variables, glob files, quote | |
261 | arguments, etc. |
|
252 | arguments, etc. | |
262 |
|
253 | |||
263 | Options: |
|
254 | Options: | |
264 | -mode: default 'string'. If given as 'list', the argument string is |
|
255 | -mode: default 'string'. If given as 'list', the argument string is | |
265 | returned as a list (split on whitespace) instead of a string. |
|
256 | returned as a list (split on whitespace) instead of a string. | |
266 |
|
257 | |||
267 | -list_all: put all option values in lists. Normally only options |
|
258 | -list_all: put all option values in lists. Normally only options | |
268 | appearing more than once are put in a list. |
|
259 | appearing more than once are put in a list. | |
269 |
|
260 | |||
270 | -posix (True): whether to split the input line in POSIX mode or not, |
|
261 | -posix (True): whether to split the input line in POSIX mode or not, | |
271 | as per the conventions outlined in the shlex module from the |
|
262 | as per the conventions outlined in the shlex module from the | |
272 | standard library.""" |
|
263 | standard library.""" | |
273 |
|
264 | |||
274 | # inject default options at the beginning of the input line |
|
265 | # inject default options at the beginning of the input line | |
275 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
266 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
276 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
267 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
277 |
|
268 | |||
278 | mode = kw.get('mode','string') |
|
269 | mode = kw.get('mode','string') | |
279 | if mode not in ['string','list']: |
|
270 | if mode not in ['string','list']: | |
280 | raise ValueError,'incorrect mode given: %s' % mode |
|
271 | raise ValueError,'incorrect mode given: %s' % mode | |
281 | # Get options |
|
272 | # Get options | |
282 | list_all = kw.get('list_all',0) |
|
273 | list_all = kw.get('list_all',0) | |
283 | posix = kw.get('posix', os.name == 'posix') |
|
274 | posix = kw.get('posix', os.name == 'posix') | |
284 |
|
275 | |||
285 | # Check if we have more than one argument to warrant extra processing: |
|
276 | # Check if we have more than one argument to warrant extra processing: | |
286 | odict = {} # Dictionary with options |
|
277 | odict = {} # Dictionary with options | |
287 | args = arg_str.split() |
|
278 | args = arg_str.split() | |
288 | if len(args) >= 1: |
|
279 | if len(args) >= 1: | |
289 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
280 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
290 | # need to look for options |
|
281 | # need to look for options | |
291 | argv = arg_split(arg_str,posix) |
|
282 | argv = arg_split(arg_str,posix) | |
292 | # Do regular option processing |
|
283 | # Do regular option processing | |
293 | try: |
|
284 | try: | |
294 | opts,args = getopt(argv,opt_str,*long_opts) |
|
285 | opts,args = getopt(argv,opt_str,*long_opts) | |
295 | except GetoptError,e: |
|
286 | except GetoptError,e: | |
296 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
297 | " ".join(long_opts))) |
|
288 | " ".join(long_opts))) | |
298 | for o,a in opts: |
|
289 | for o,a in opts: | |
299 | if o.startswith('--'): |
|
290 | if o.startswith('--'): | |
300 | o = o[2:] |
|
291 | o = o[2:] | |
301 | else: |
|
292 | else: | |
302 | o = o[1:] |
|
293 | o = o[1:] | |
303 | try: |
|
294 | try: | |
304 | odict[o].append(a) |
|
295 | odict[o].append(a) | |
305 | except AttributeError: |
|
296 | except AttributeError: | |
306 | odict[o] = [odict[o],a] |
|
297 | odict[o] = [odict[o],a] | |
307 | except KeyError: |
|
298 | except KeyError: | |
308 | if list_all: |
|
299 | if list_all: | |
309 | odict[o] = [a] |
|
300 | odict[o] = [a] | |
310 | else: |
|
301 | else: | |
311 | odict[o] = a |
|
302 | odict[o] = a | |
312 |
|
303 | |||
313 | # Prepare opts,args for return |
|
304 | # Prepare opts,args for return | |
314 | opts = Struct(odict) |
|
305 | opts = Struct(odict) | |
315 | if mode == 'string': |
|
306 | if mode == 'string': | |
316 | args = ' '.join(args) |
|
307 | args = ' '.join(args) | |
317 |
|
308 | |||
318 | return opts,args |
|
309 | return opts,args | |
319 |
|
310 | |||
320 | #...................................................................... |
|
311 | #...................................................................... | |
321 | # And now the actual magic functions |
|
312 | # And now the actual magic functions | |
322 |
|
313 | |||
323 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
314 | # Functions for IPython shell work (vars,funcs, config, etc) | |
324 | def magic_lsmagic(self, parameter_s = ''): |
|
315 | def magic_lsmagic(self, parameter_s = ''): | |
325 | """List currently available magic functions.""" |
|
316 | """List currently available magic functions.""" | |
326 | mesc = ESC_MAGIC |
|
317 | mesc = ESC_MAGIC | |
327 | print 'Available magic functions:\n'+mesc+\ |
|
318 | print 'Available magic functions:\n'+mesc+\ | |
328 | (' '+mesc).join(self.lsmagic()) |
|
319 | (' '+mesc).join(self.lsmagic()) | |
329 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
320 | print '\n' + Magic.auto_status[self.shell.automagic] | |
330 | return None |
|
321 | return None | |
331 |
|
322 | |||
332 | def magic_magic(self, parameter_s = ''): |
|
323 | def magic_magic(self, parameter_s = ''): | |
333 | """Print information about the magic function system. |
|
324 | """Print information about the magic function system. | |
334 |
|
325 | |||
335 | Supported formats: -latex, -brief, -rest |
|
326 | Supported formats: -latex, -brief, -rest | |
336 | """ |
|
327 | """ | |
337 |
|
328 | |||
338 | mode = '' |
|
329 | mode = '' | |
339 | try: |
|
330 | try: | |
340 | if parameter_s.split()[0] == '-latex': |
|
331 | if parameter_s.split()[0] == '-latex': | |
341 | mode = 'latex' |
|
332 | mode = 'latex' | |
342 | if parameter_s.split()[0] == '-brief': |
|
333 | if parameter_s.split()[0] == '-brief': | |
343 | mode = 'brief' |
|
334 | mode = 'brief' | |
344 | if parameter_s.split()[0] == '-rest': |
|
335 | if parameter_s.split()[0] == '-rest': | |
345 | mode = 'rest' |
|
336 | mode = 'rest' | |
346 | rest_docs = [] |
|
337 | rest_docs = [] | |
347 | except: |
|
338 | except: | |
348 | pass |
|
339 | pass | |
349 |
|
340 | |||
350 | magic_docs = [] |
|
341 | magic_docs = [] | |
351 | for fname in self.lsmagic(): |
|
342 | for fname in self.lsmagic(): | |
352 | mname = 'magic_' + fname |
|
343 | mname = 'magic_' + fname | |
353 | for space in (Magic,self,self.__class__): |
|
344 | for space in (Magic,self,self.__class__): | |
354 | try: |
|
345 | try: | |
355 | fn = space.__dict__[mname] |
|
346 | fn = space.__dict__[mname] | |
356 | except KeyError: |
|
347 | except KeyError: | |
357 | pass |
|
348 | pass | |
358 | else: |
|
349 | else: | |
359 | break |
|
350 | break | |
360 | if mode == 'brief': |
|
351 | if mode == 'brief': | |
361 | # only first line |
|
352 | # only first line | |
362 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
363 | fndoc = fn.__doc__.split('\n',1)[0] |
|
354 | fndoc = fn.__doc__.split('\n',1)[0] | |
364 | else: |
|
355 | else: | |
365 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
366 | else: |
|
357 | else: | |
367 | if fn.__doc__: |
|
358 | if fn.__doc__: | |
368 | fndoc = fn.__doc__.rstrip() |
|
359 | fndoc = fn.__doc__.rstrip() | |
369 | else: |
|
360 | else: | |
370 | fndoc = 'No documentation' |
|
361 | fndoc = 'No documentation' | |
371 |
|
362 | |||
372 |
|
363 | |||
373 | if mode == 'rest': |
|
364 | if mode == 'rest': | |
374 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
375 | fname,fndoc)) |
|
366 | fname,fndoc)) | |
376 |
|
367 | |||
377 | else: |
|
368 | else: | |
378 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
379 | fname,fndoc)) |
|
370 | fname,fndoc)) | |
380 |
|
371 | |||
381 | magic_docs = ''.join(magic_docs) |
|
372 | magic_docs = ''.join(magic_docs) | |
382 |
|
373 | |||
383 | if mode == 'rest': |
|
374 | if mode == 'rest': | |
384 | return "".join(rest_docs) |
|
375 | return "".join(rest_docs) | |
385 |
|
376 | |||
386 | if mode == 'latex': |
|
377 | if mode == 'latex': | |
387 | print self.format_latex(magic_docs) |
|
378 | print self.format_latex(magic_docs) | |
388 | return |
|
379 | return | |
389 | else: |
|
380 | else: | |
390 |
magic_docs = |
|
381 | magic_docs = format_screen(magic_docs) | |
391 | if mode == 'brief': |
|
382 | if mode == 'brief': | |
392 | return magic_docs |
|
383 | return magic_docs | |
393 |
|
384 | |||
394 | outmsg = """ |
|
385 | outmsg = """ | |
395 | IPython's 'magic' functions |
|
386 | IPython's 'magic' functions | |
396 | =========================== |
|
387 | =========================== | |
397 |
|
388 | |||
398 | The magic function system provides a series of functions which allow you to |
|
389 | The magic function system provides a series of functions which allow you to | |
399 | control the behavior of IPython itself, plus a lot of system-type |
|
390 | control the behavior of IPython itself, plus a lot of system-type | |
400 | features. All these functions are prefixed with a % character, but parameters |
|
391 | features. All these functions are prefixed with a % character, but parameters | |
401 | are given without parentheses or quotes. |
|
392 | are given without parentheses or quotes. | |
402 |
|
393 | |||
403 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
404 | %automagic function), you don't need to type in the % explicitly. By default, |
|
395 | %automagic function), you don't need to type in the % explicitly. By default, | |
405 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
396 | IPython ships with automagic on, so you should only rarely need the % escape. | |
406 |
|
397 | |||
407 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
408 | to 'mydir', if it exists. |
|
399 | to 'mydir', if it exists. | |
409 |
|
400 | |||
410 | You can define your own magic functions to extend the system. See the supplied |
|
401 | You can define your own magic functions to extend the system. See the supplied | |
411 | ipythonrc and example-magic.py files for details (in your ipython |
|
402 | ipythonrc and example-magic.py files for details (in your ipython | |
412 | configuration directory, typically $HOME/.ipython/). |
|
403 | configuration directory, typically $HOME/.ipython/). | |
413 |
|
404 | |||
414 | You can also define your own aliased names for magic functions. In your |
|
405 | You can also define your own aliased names for magic functions. In your | |
415 | ipythonrc file, placing a line like: |
|
406 | ipythonrc file, placing a line like: | |
416 |
|
407 | |||
417 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
408 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
418 |
|
409 | |||
419 | will define %pf as a new name for %profile. |
|
410 | will define %pf as a new name for %profile. | |
420 |
|
411 | |||
421 | You can also call magics in code using the magic() function, which IPython |
|
412 | You can also call magics in code using the magic() function, which IPython | |
422 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
413 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
423 |
|
414 | |||
424 | For a list of the available magic functions, use %lsmagic. For a description |
|
415 | For a list of the available magic functions, use %lsmagic. For a description | |
425 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
416 | of any of them, type %magic_name?, e.g. '%cd?'. | |
426 |
|
417 | |||
427 | Currently the magic system has the following functions:\n""" |
|
418 | Currently the magic system has the following functions:\n""" | |
428 |
|
419 | |||
429 | mesc = ESC_MAGIC |
|
420 | mesc = ESC_MAGIC | |
430 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
421 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
431 | "\n\n%s%s\n\n%s" % (outmsg, |
|
422 | "\n\n%s%s\n\n%s" % (outmsg, | |
432 | magic_docs,mesc,mesc, |
|
423 | magic_docs,mesc,mesc, | |
433 | (' '+mesc).join(self.lsmagic()), |
|
424 | (' '+mesc).join(self.lsmagic()), | |
434 | Magic.auto_status[self.shell.automagic] ) ) |
|
425 | Magic.auto_status[self.shell.automagic] ) ) | |
435 | page.page(outmsg) |
|
426 | page.page(outmsg) | |
436 |
|
427 | |||
437 | def magic_autoindent(self, parameter_s = ''): |
|
428 | def magic_autoindent(self, parameter_s = ''): | |
438 | """Toggle autoindent on/off (if available).""" |
|
429 | """Toggle autoindent on/off (if available).""" | |
439 |
|
430 | |||
440 | self.shell.set_autoindent() |
|
431 | self.shell.set_autoindent() | |
441 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
432 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
442 |
|
433 | |||
443 | def magic_automagic(self, parameter_s = ''): |
|
434 | def magic_automagic(self, parameter_s = ''): | |
444 | """Make magic functions callable without having to type the initial %. |
|
435 | """Make magic functions callable without having to type the initial %. | |
445 |
|
436 | |||
446 | Without argumentsl toggles on/off (when off, you must call it as |
|
437 | Without argumentsl toggles on/off (when off, you must call it as | |
447 | %automagic, of course). With arguments it sets the value, and you can |
|
438 | %automagic, of course). With arguments it sets the value, and you can | |
448 | use any of (case insensitive): |
|
439 | use any of (case insensitive): | |
449 |
|
440 | |||
450 | - on,1,True: to activate |
|
441 | - on,1,True: to activate | |
451 |
|
442 | |||
452 | - off,0,False: to deactivate. |
|
443 | - off,0,False: to deactivate. | |
453 |
|
444 | |||
454 | Note that magic functions have lowest priority, so if there's a |
|
445 | Note that magic functions have lowest priority, so if there's a | |
455 | variable whose name collides with that of a magic fn, automagic won't |
|
446 | variable whose name collides with that of a magic fn, automagic won't | |
456 | work for that function (you get the variable instead). However, if you |
|
447 | work for that function (you get the variable instead). However, if you | |
457 | delete the variable (del var), the previously shadowed magic function |
|
448 | delete the variable (del var), the previously shadowed magic function | |
458 | becomes visible to automagic again.""" |
|
449 | becomes visible to automagic again.""" | |
459 |
|
450 | |||
460 | arg = parameter_s.lower() |
|
451 | arg = parameter_s.lower() | |
461 | if parameter_s in ('on','1','true'): |
|
452 | if parameter_s in ('on','1','true'): | |
462 | self.shell.automagic = True |
|
453 | self.shell.automagic = True | |
463 | elif parameter_s in ('off','0','false'): |
|
454 | elif parameter_s in ('off','0','false'): | |
464 | self.shell.automagic = False |
|
455 | self.shell.automagic = False | |
465 | else: |
|
456 | else: | |
466 | self.shell.automagic = not self.shell.automagic |
|
457 | self.shell.automagic = not self.shell.automagic | |
467 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
458 | print '\n' + Magic.auto_status[self.shell.automagic] | |
468 |
|
459 | |||
469 | @testdec.skip_doctest |
|
460 | @testdec.skip_doctest | |
470 | def magic_autocall(self, parameter_s = ''): |
|
461 | def magic_autocall(self, parameter_s = ''): | |
471 | """Make functions callable without having to type parentheses. |
|
462 | """Make functions callable without having to type parentheses. | |
472 |
|
463 | |||
473 | Usage: |
|
464 | Usage: | |
474 |
|
465 | |||
475 | %autocall [mode] |
|
466 | %autocall [mode] | |
476 |
|
467 | |||
477 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
468 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
478 | value is toggled on and off (remembering the previous state). |
|
469 | value is toggled on and off (remembering the previous state). | |
479 |
|
470 | |||
480 | In more detail, these values mean: |
|
471 | In more detail, these values mean: | |
481 |
|
472 | |||
482 | 0 -> fully disabled |
|
473 | 0 -> fully disabled | |
483 |
|
474 | |||
484 | 1 -> active, but do not apply if there are no arguments on the line. |
|
475 | 1 -> active, but do not apply if there are no arguments on the line. | |
485 |
|
476 | |||
486 | In this mode, you get: |
|
477 | In this mode, you get: | |
487 |
|
478 | |||
488 | In [1]: callable |
|
479 | In [1]: callable | |
489 | Out[1]: <built-in function callable> |
|
480 | Out[1]: <built-in function callable> | |
490 |
|
481 | |||
491 | In [2]: callable 'hello' |
|
482 | In [2]: callable 'hello' | |
492 | ------> callable('hello') |
|
483 | ------> callable('hello') | |
493 | Out[2]: False |
|
484 | Out[2]: False | |
494 |
|
485 | |||
495 | 2 -> Active always. Even if no arguments are present, the callable |
|
486 | 2 -> Active always. Even if no arguments are present, the callable | |
496 | object is called: |
|
487 | object is called: | |
497 |
|
488 | |||
498 | In [2]: float |
|
489 | In [2]: float | |
499 | ------> float() |
|
490 | ------> float() | |
500 | Out[2]: 0.0 |
|
491 | Out[2]: 0.0 | |
501 |
|
492 | |||
502 | Note that even with autocall off, you can still use '/' at the start of |
|
493 | Note that even with autocall off, you can still use '/' at the start of | |
503 | a line to treat the first argument on the command line as a function |
|
494 | a line to treat the first argument on the command line as a function | |
504 | and add parentheses to it: |
|
495 | and add parentheses to it: | |
505 |
|
496 | |||
506 | In [8]: /str 43 |
|
497 | In [8]: /str 43 | |
507 | ------> str(43) |
|
498 | ------> str(43) | |
508 | Out[8]: '43' |
|
499 | Out[8]: '43' | |
509 |
|
500 | |||
510 | # all-random (note for auto-testing) |
|
501 | # all-random (note for auto-testing) | |
511 | """ |
|
502 | """ | |
512 |
|
503 | |||
513 | if parameter_s: |
|
504 | if parameter_s: | |
514 | arg = int(parameter_s) |
|
505 | arg = int(parameter_s) | |
515 | else: |
|
506 | else: | |
516 | arg = 'toggle' |
|
507 | arg = 'toggle' | |
517 |
|
508 | |||
518 | if not arg in (0,1,2,'toggle'): |
|
509 | if not arg in (0,1,2,'toggle'): | |
519 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
510 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
520 | return |
|
511 | return | |
521 |
|
512 | |||
522 | if arg in (0,1,2): |
|
513 | if arg in (0,1,2): | |
523 | self.shell.autocall = arg |
|
514 | self.shell.autocall = arg | |
524 | else: # toggle |
|
515 | else: # toggle | |
525 | if self.shell.autocall: |
|
516 | if self.shell.autocall: | |
526 | self._magic_state.autocall_save = self.shell.autocall |
|
517 | self._magic_state.autocall_save = self.shell.autocall | |
527 | self.shell.autocall = 0 |
|
518 | self.shell.autocall = 0 | |
528 | else: |
|
519 | else: | |
529 | try: |
|
520 | try: | |
530 | self.shell.autocall = self._magic_state.autocall_save |
|
521 | self.shell.autocall = self._magic_state.autocall_save | |
531 | except AttributeError: |
|
522 | except AttributeError: | |
532 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
523 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
533 |
|
524 | |||
534 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
525 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
535 |
|
526 | |||
536 |
|
527 | |||
537 | def magic_page(self, parameter_s=''): |
|
528 | def magic_page(self, parameter_s=''): | |
538 | """Pretty print the object and display it through a pager. |
|
529 | """Pretty print the object and display it through a pager. | |
539 |
|
530 | |||
540 | %page [options] OBJECT |
|
531 | %page [options] OBJECT | |
541 |
|
532 | |||
542 | If no object is given, use _ (last output). |
|
533 | If no object is given, use _ (last output). | |
543 |
|
534 | |||
544 | Options: |
|
535 | Options: | |
545 |
|
536 | |||
546 | -r: page str(object), don't pretty-print it.""" |
|
537 | -r: page str(object), don't pretty-print it.""" | |
547 |
|
538 | |||
548 | # After a function contributed by Olivier Aubert, slightly modified. |
|
539 | # After a function contributed by Olivier Aubert, slightly modified. | |
549 |
|
540 | |||
550 | # Process options/args |
|
541 | # Process options/args | |
551 | opts,args = self.parse_options(parameter_s,'r') |
|
542 | opts,args = self.parse_options(parameter_s,'r') | |
552 | raw = 'r' in opts |
|
543 | raw = 'r' in opts | |
553 |
|
544 | |||
554 | oname = args and args or '_' |
|
545 | oname = args and args or '_' | |
555 | info = self._ofind(oname) |
|
546 | info = self._ofind(oname) | |
556 | if info['found']: |
|
547 | if info['found']: | |
557 | txt = (raw and str or pformat)( info['obj'] ) |
|
548 | txt = (raw and str or pformat)( info['obj'] ) | |
558 | page.page(txt) |
|
549 | page.page(txt) | |
559 | else: |
|
550 | else: | |
560 | print 'Object `%s` not found' % oname |
|
551 | print 'Object `%s` not found' % oname | |
561 |
|
552 | |||
562 | def magic_profile(self, parameter_s=''): |
|
553 | def magic_profile(self, parameter_s=''): | |
563 | """Print your currently active IPython profile.""" |
|
554 | """Print your currently active IPython profile.""" | |
564 | if self.shell.profile: |
|
555 | if self.shell.profile: | |
565 | printpl('Current IPython profile: $self.shell.profile.') |
|
556 | printpl('Current IPython profile: $self.shell.profile.') | |
566 | else: |
|
557 | else: | |
567 | print 'No profile active.' |
|
558 | print 'No profile active.' | |
568 |
|
559 | |||
569 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
560 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
570 | """Provide detailed information about an object. |
|
561 | """Provide detailed information about an object. | |
571 |
|
562 | |||
572 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
563 | '%pinfo object' is just a synonym for object? or ?object.""" | |
573 |
|
564 | |||
574 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
565 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
575 |
|
566 | |||
576 |
|
567 | |||
577 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
568 | # detail_level: 0 -> obj? , 1 -> obj?? | |
578 | detail_level = 0 |
|
569 | detail_level = 0 | |
579 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
570 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
580 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
571 | # happen if the user types 'pinfo foo?' at the cmd line. | |
581 | pinfo,qmark1,oname,qmark2 = \ |
|
572 | pinfo,qmark1,oname,qmark2 = \ | |
582 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
573 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
583 | if pinfo or qmark1 or qmark2: |
|
574 | if pinfo or qmark1 or qmark2: | |
584 | detail_level = 1 |
|
575 | detail_level = 1 | |
585 | if "*" in oname: |
|
576 | if "*" in oname: | |
586 | self.magic_psearch(oname) |
|
577 | self.magic_psearch(oname) | |
587 | else: |
|
578 | else: | |
588 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
579 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
589 | namespaces=namespaces) |
|
580 | namespaces=namespaces) | |
590 |
|
581 | |||
591 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
582 | def magic_pdef(self, parameter_s='', namespaces=None): | |
592 | """Print the definition header for any callable object. |
|
583 | """Print the definition header for any callable object. | |
593 |
|
584 | |||
594 | If the object is a class, print the constructor information.""" |
|
585 | If the object is a class, print the constructor information.""" | |
595 | self._inspect('pdef',parameter_s, namespaces) |
|
586 | self._inspect('pdef',parameter_s, namespaces) | |
596 |
|
587 | |||
597 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
588 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
598 | """Print the docstring for an object. |
|
589 | """Print the docstring for an object. | |
599 |
|
590 | |||
600 | If the given object is a class, it will print both the class and the |
|
591 | If the given object is a class, it will print both the class and the | |
601 | constructor docstrings.""" |
|
592 | constructor docstrings.""" | |
602 | self._inspect('pdoc',parameter_s, namespaces) |
|
593 | self._inspect('pdoc',parameter_s, namespaces) | |
603 |
|
594 | |||
604 | def magic_psource(self, parameter_s='', namespaces=None): |
|
595 | def magic_psource(self, parameter_s='', namespaces=None): | |
605 | """Print (or run through pager) the source code for an object.""" |
|
596 | """Print (or run through pager) the source code for an object.""" | |
606 | self._inspect('psource',parameter_s, namespaces) |
|
597 | self._inspect('psource',parameter_s, namespaces) | |
607 |
|
598 | |||
608 | def magic_pfile(self, parameter_s=''): |
|
599 | def magic_pfile(self, parameter_s=''): | |
609 | """Print (or run through pager) the file where an object is defined. |
|
600 | """Print (or run through pager) the file where an object is defined. | |
610 |
|
601 | |||
611 | The file opens at the line where the object definition begins. IPython |
|
602 | The file opens at the line where the object definition begins. IPython | |
612 | will honor the environment variable PAGER if set, and otherwise will |
|
603 | will honor the environment variable PAGER if set, and otherwise will | |
613 | do its best to print the file in a convenient form. |
|
604 | do its best to print the file in a convenient form. | |
614 |
|
605 | |||
615 | If the given argument is not an object currently defined, IPython will |
|
606 | If the given argument is not an object currently defined, IPython will | |
616 | try to interpret it as a filename (automatically adding a .py extension |
|
607 | try to interpret it as a filename (automatically adding a .py extension | |
617 | if needed). You can thus use %pfile as a syntax highlighting code |
|
608 | if needed). You can thus use %pfile as a syntax highlighting code | |
618 | viewer.""" |
|
609 | viewer.""" | |
619 |
|
610 | |||
620 | # first interpret argument as an object name |
|
611 | # first interpret argument as an object name | |
621 | out = self._inspect('pfile',parameter_s) |
|
612 | out = self._inspect('pfile',parameter_s) | |
622 | # if not, try the input as a filename |
|
613 | # if not, try the input as a filename | |
623 | if out == 'not found': |
|
614 | if out == 'not found': | |
624 | try: |
|
615 | try: | |
625 | filename = get_py_filename(parameter_s) |
|
616 | filename = get_py_filename(parameter_s) | |
626 | except IOError,msg: |
|
617 | except IOError,msg: | |
627 | print msg |
|
618 | print msg | |
628 | return |
|
619 | return | |
629 | page.page(self.shell.inspector.format(file(filename).read())) |
|
620 | page.page(self.shell.inspector.format(file(filename).read())) | |
630 |
|
621 | |||
631 | def magic_psearch(self, parameter_s=''): |
|
622 | def magic_psearch(self, parameter_s=''): | |
632 | """Search for object in namespaces by wildcard. |
|
623 | """Search for object in namespaces by wildcard. | |
633 |
|
624 | |||
634 | %psearch [options] PATTERN [OBJECT TYPE] |
|
625 | %psearch [options] PATTERN [OBJECT TYPE] | |
635 |
|
626 | |||
636 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
627 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
637 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
628 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
638 | rest of the command line must be unchanged (options come first), so |
|
629 | rest of the command line must be unchanged (options come first), so | |
639 | for example the following forms are equivalent |
|
630 | for example the following forms are equivalent | |
640 |
|
631 | |||
641 | %psearch -i a* function |
|
632 | %psearch -i a* function | |
642 | -i a* function? |
|
633 | -i a* function? | |
643 | ?-i a* function |
|
634 | ?-i a* function | |
644 |
|
635 | |||
645 | Arguments: |
|
636 | Arguments: | |
646 |
|
637 | |||
647 | PATTERN |
|
638 | PATTERN | |
648 |
|
639 | |||
649 | where PATTERN is a string containing * as a wildcard similar to its |
|
640 | where PATTERN is a string containing * as a wildcard similar to its | |
650 | use in a shell. The pattern is matched in all namespaces on the |
|
641 | use in a shell. The pattern is matched in all namespaces on the | |
651 | search path. By default objects starting with a single _ are not |
|
642 | search path. By default objects starting with a single _ are not | |
652 | matched, many IPython generated objects have a single |
|
643 | matched, many IPython generated objects have a single | |
653 | underscore. The default is case insensitive matching. Matching is |
|
644 | underscore. The default is case insensitive matching. Matching is | |
654 | also done on the attributes of objects and not only on the objects |
|
645 | also done on the attributes of objects and not only on the objects | |
655 | in a module. |
|
646 | in a module. | |
656 |
|
647 | |||
657 | [OBJECT TYPE] |
|
648 | [OBJECT TYPE] | |
658 |
|
649 | |||
659 | Is the name of a python type from the types module. The name is |
|
650 | Is the name of a python type from the types module. The name is | |
660 | given in lowercase without the ending type, ex. StringType is |
|
651 | given in lowercase without the ending type, ex. StringType is | |
661 | written string. By adding a type here only objects matching the |
|
652 | written string. By adding a type here only objects matching the | |
662 | given type are matched. Using all here makes the pattern match all |
|
653 | given type are matched. Using all here makes the pattern match all | |
663 | types (this is the default). |
|
654 | types (this is the default). | |
664 |
|
655 | |||
665 | Options: |
|
656 | Options: | |
666 |
|
657 | |||
667 | -a: makes the pattern match even objects whose names start with a |
|
658 | -a: makes the pattern match even objects whose names start with a | |
668 | single underscore. These names are normally ommitted from the |
|
659 | single underscore. These names are normally ommitted from the | |
669 | search. |
|
660 | search. | |
670 |
|
661 | |||
671 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
662 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
672 | these options is given, the default is read from your ipythonrc |
|
663 | these options is given, the default is read from your ipythonrc | |
673 | file. The option name which sets this value is |
|
664 | file. The option name which sets this value is | |
674 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
665 | 'wildcards_case_sensitive'. If this option is not specified in your | |
675 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
666 | ipythonrc file, IPython's internal default is to do a case sensitive | |
676 | search. |
|
667 | search. | |
677 |
|
668 | |||
678 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
669 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
679 | specifiy can be searched in any of the following namespaces: |
|
670 | specifiy can be searched in any of the following namespaces: | |
680 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
671 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
681 | 'builtin' and 'user' are the search defaults. Note that you should |
|
672 | 'builtin' and 'user' are the search defaults. Note that you should | |
682 | not use quotes when specifying namespaces. |
|
673 | not use quotes when specifying namespaces. | |
683 |
|
674 | |||
684 | 'Builtin' contains the python module builtin, 'user' contains all |
|
675 | 'Builtin' contains the python module builtin, 'user' contains all | |
685 | user data, 'alias' only contain the shell aliases and no python |
|
676 | user data, 'alias' only contain the shell aliases and no python | |
686 | objects, 'internal' contains objects used by IPython. The |
|
677 | objects, 'internal' contains objects used by IPython. The | |
687 | 'user_global' namespace is only used by embedded IPython instances, |
|
678 | 'user_global' namespace is only used by embedded IPython instances, | |
688 | and it contains module-level globals. You can add namespaces to the |
|
679 | and it contains module-level globals. You can add namespaces to the | |
689 | search with -s or exclude them with -e (these options can be given |
|
680 | search with -s or exclude them with -e (these options can be given | |
690 | more than once). |
|
681 | more than once). | |
691 |
|
682 | |||
692 | Examples: |
|
683 | Examples: | |
693 |
|
684 | |||
694 | %psearch a* -> objects beginning with an a |
|
685 | %psearch a* -> objects beginning with an a | |
695 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
686 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
696 | %psearch a* function -> all functions beginning with an a |
|
687 | %psearch a* function -> all functions beginning with an a | |
697 | %psearch re.e* -> objects beginning with an e in module re |
|
688 | %psearch re.e* -> objects beginning with an e in module re | |
698 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
689 | %psearch r*.e* -> objects that start with e in modules starting in r | |
699 | %psearch r*.* string -> all strings in modules beginning with r |
|
690 | %psearch r*.* string -> all strings in modules beginning with r | |
700 |
|
691 | |||
701 | Case sensitve search: |
|
692 | Case sensitve search: | |
702 |
|
693 | |||
703 | %psearch -c a* list all object beginning with lower case a |
|
694 | %psearch -c a* list all object beginning with lower case a | |
704 |
|
695 | |||
705 | Show objects beginning with a single _: |
|
696 | Show objects beginning with a single _: | |
706 |
|
697 | |||
707 | %psearch -a _* list objects beginning with a single underscore""" |
|
698 | %psearch -a _* list objects beginning with a single underscore""" | |
708 | try: |
|
699 | try: | |
709 | parameter_s = parameter_s.encode('ascii') |
|
700 | parameter_s = parameter_s.encode('ascii') | |
710 | except UnicodeEncodeError: |
|
701 | except UnicodeEncodeError: | |
711 | print 'Python identifiers can only contain ascii characters.' |
|
702 | print 'Python identifiers can only contain ascii characters.' | |
712 | return |
|
703 | return | |
713 |
|
704 | |||
714 | # default namespaces to be searched |
|
705 | # default namespaces to be searched | |
715 | def_search = ['user','builtin'] |
|
706 | def_search = ['user','builtin'] | |
716 |
|
707 | |||
717 | # Process options/args |
|
708 | # Process options/args | |
718 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
709 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
719 | opt = opts.get |
|
710 | opt = opts.get | |
720 | shell = self.shell |
|
711 | shell = self.shell | |
721 | psearch = shell.inspector.psearch |
|
712 | psearch = shell.inspector.psearch | |
722 |
|
713 | |||
723 | # select case options |
|
714 | # select case options | |
724 | if opts.has_key('i'): |
|
715 | if opts.has_key('i'): | |
725 | ignore_case = True |
|
716 | ignore_case = True | |
726 | elif opts.has_key('c'): |
|
717 | elif opts.has_key('c'): | |
727 | ignore_case = False |
|
718 | ignore_case = False | |
728 | else: |
|
719 | else: | |
729 | ignore_case = not shell.wildcards_case_sensitive |
|
720 | ignore_case = not shell.wildcards_case_sensitive | |
730 |
|
721 | |||
731 | # Build list of namespaces to search from user options |
|
722 | # Build list of namespaces to search from user options | |
732 | def_search.extend(opt('s',[])) |
|
723 | def_search.extend(opt('s',[])) | |
733 | ns_exclude = ns_exclude=opt('e',[]) |
|
724 | ns_exclude = ns_exclude=opt('e',[]) | |
734 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
725 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
735 |
|
726 | |||
736 | # Call the actual search |
|
727 | # Call the actual search | |
737 | try: |
|
728 | try: | |
738 | psearch(args,shell.ns_table,ns_search, |
|
729 | psearch(args,shell.ns_table,ns_search, | |
739 | show_all=opt('a'),ignore_case=ignore_case) |
|
730 | show_all=opt('a'),ignore_case=ignore_case) | |
740 | except: |
|
731 | except: | |
741 | shell.showtraceback() |
|
732 | shell.showtraceback() | |
742 |
|
733 | |||
743 | def magic_who_ls(self, parameter_s=''): |
|
734 | def magic_who_ls(self, parameter_s=''): | |
744 | """Return a sorted list of all interactive variables. |
|
735 | """Return a sorted list of all interactive variables. | |
745 |
|
736 | |||
746 | If arguments are given, only variables of types matching these |
|
737 | If arguments are given, only variables of types matching these | |
747 | arguments are returned.""" |
|
738 | arguments are returned.""" | |
748 |
|
739 | |||
749 | user_ns = self.shell.user_ns |
|
740 | user_ns = self.shell.user_ns | |
750 | internal_ns = self.shell.internal_ns |
|
741 | internal_ns = self.shell.internal_ns | |
751 | user_ns_hidden = self.shell.user_ns_hidden |
|
742 | user_ns_hidden = self.shell.user_ns_hidden | |
752 | out = [ i for i in user_ns |
|
743 | out = [ i for i in user_ns | |
753 | if not i.startswith('_') \ |
|
744 | if not i.startswith('_') \ | |
754 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
745 | and not (i in internal_ns or i in user_ns_hidden) ] | |
755 |
|
746 | |||
756 | typelist = parameter_s.split() |
|
747 | typelist = parameter_s.split() | |
757 | if typelist: |
|
748 | if typelist: | |
758 | typeset = set(typelist) |
|
749 | typeset = set(typelist) | |
759 | out = [i for i in out if type(i).__name__ in typeset] |
|
750 | out = [i for i in out if type(i).__name__ in typeset] | |
760 |
|
751 | |||
761 | out.sort() |
|
752 | out.sort() | |
762 | return out |
|
753 | return out | |
763 |
|
754 | |||
764 | def magic_who(self, parameter_s=''): |
|
755 | def magic_who(self, parameter_s=''): | |
765 | """Print all interactive variables, with some minimal formatting. |
|
756 | """Print all interactive variables, with some minimal formatting. | |
766 |
|
757 | |||
767 | If any arguments are given, only variables whose type matches one of |
|
758 | If any arguments are given, only variables whose type matches one of | |
768 | these are printed. For example: |
|
759 | these are printed. For example: | |
769 |
|
760 | |||
770 | %who function str |
|
761 | %who function str | |
771 |
|
762 | |||
772 | will only list functions and strings, excluding all other types of |
|
763 | will only list functions and strings, excluding all other types of | |
773 | variables. To find the proper type names, simply use type(var) at a |
|
764 | variables. To find the proper type names, simply use type(var) at a | |
774 | command line to see how python prints type names. For example: |
|
765 | command line to see how python prints type names. For example: | |
775 |
|
766 | |||
776 | In [1]: type('hello')\\ |
|
767 | In [1]: type('hello')\\ | |
777 | Out[1]: <type 'str'> |
|
768 | Out[1]: <type 'str'> | |
778 |
|
769 | |||
779 | indicates that the type name for strings is 'str'. |
|
770 | indicates that the type name for strings is 'str'. | |
780 |
|
771 | |||
781 | %who always excludes executed names loaded through your configuration |
|
772 | %who always excludes executed names loaded through your configuration | |
782 | file and things which are internal to IPython. |
|
773 | file and things which are internal to IPython. | |
783 |
|
774 | |||
784 | This is deliberate, as typically you may load many modules and the |
|
775 | This is deliberate, as typically you may load many modules and the | |
785 | purpose of %who is to show you only what you've manually defined.""" |
|
776 | purpose of %who is to show you only what you've manually defined.""" | |
786 |
|
777 | |||
787 | varlist = self.magic_who_ls(parameter_s) |
|
778 | varlist = self.magic_who_ls(parameter_s) | |
788 | if not varlist: |
|
779 | if not varlist: | |
789 | if parameter_s: |
|
780 | if parameter_s: | |
790 | print 'No variables match your requested type.' |
|
781 | print 'No variables match your requested type.' | |
791 | else: |
|
782 | else: | |
792 | print 'Interactive namespace is empty.' |
|
783 | print 'Interactive namespace is empty.' | |
793 | return |
|
784 | return | |
794 |
|
785 | |||
795 | # if we have variables, move on... |
|
786 | # if we have variables, move on... | |
796 | count = 0 |
|
787 | count = 0 | |
797 | for i in varlist: |
|
788 | for i in varlist: | |
798 | print i+'\t', |
|
789 | print i+'\t', | |
799 | count += 1 |
|
790 | count += 1 | |
800 | if count > 8: |
|
791 | if count > 8: | |
801 | count = 0 |
|
792 | count = 0 | |
802 |
|
793 | |||
803 |
|
794 | |||
804 |
|
795 | |||
805 | def magic_whos(self, parameter_s=''): |
|
796 | def magic_whos(self, parameter_s=''): | |
806 | """Like %who, but gives some extra information about each variable. |
|
797 | """Like %who, but gives some extra information about each variable. | |
807 |
|
798 | |||
808 | The same type filtering of %who can be applied here. |
|
799 | The same type filtering of %who can be applied here. | |
809 |
|
800 | |||
810 | For all variables, the type is printed. Additionally it prints: |
|
801 | For all variables, the type is printed. Additionally it prints: | |
811 |
|
802 | |||
812 | - For {},[],(): their length. |
|
803 | - For {},[],(): their length. | |
813 |
|
804 | |||
814 | - For numpy and Numeric arrays, a summary with shape, number of |
|
805 | - For numpy and Numeric arrays, a summary with shape, number of | |
815 | elements, typecode and size in memory. |
|
806 | elements, typecode and size in memory. | |
816 |
|
807 | |||
817 | - Everything else: a string representation, snipping their middle if |
|
808 | - Everything else: a string representation, snipping their middle if | |
818 | too long.""" |
|
809 | too long.""" | |
819 |
|
810 | |||
820 | varnames = self.magic_who_ls(parameter_s) |
|
811 | varnames = self.magic_who_ls(parameter_s) | |
821 | if not varnames: |
|
812 | if not varnames: | |
822 | if parameter_s: |
|
813 | if parameter_s: | |
823 | print 'No variables match your requested type.' |
|
814 | print 'No variables match your requested type.' | |
824 | else: |
|
815 | else: | |
825 | print 'Interactive namespace is empty.' |
|
816 | print 'Interactive namespace is empty.' | |
826 | return |
|
817 | return | |
827 |
|
818 | |||
828 | # if we have variables, move on... |
|
819 | # if we have variables, move on... | |
829 |
|
820 | |||
830 | # for these types, show len() instead of data: |
|
821 | # for these types, show len() instead of data: | |
831 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
822 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
832 |
|
823 | |||
833 | # for numpy/Numeric arrays, display summary info |
|
824 | # for numpy/Numeric arrays, display summary info | |
834 | try: |
|
825 | try: | |
835 | import numpy |
|
826 | import numpy | |
836 | except ImportError: |
|
827 | except ImportError: | |
837 | ndarray_type = None |
|
828 | ndarray_type = None | |
838 | else: |
|
829 | else: | |
839 | ndarray_type = numpy.ndarray.__name__ |
|
830 | ndarray_type = numpy.ndarray.__name__ | |
840 | try: |
|
831 | try: | |
841 | import Numeric |
|
832 | import Numeric | |
842 | except ImportError: |
|
833 | except ImportError: | |
843 | array_type = None |
|
834 | array_type = None | |
844 | else: |
|
835 | else: | |
845 | array_type = Numeric.ArrayType.__name__ |
|
836 | array_type = Numeric.ArrayType.__name__ | |
846 |
|
837 | |||
847 | # Find all variable names and types so we can figure out column sizes |
|
838 | # Find all variable names and types so we can figure out column sizes | |
848 | def get_vars(i): |
|
839 | def get_vars(i): | |
849 | return self.shell.user_ns[i] |
|
840 | return self.shell.user_ns[i] | |
850 |
|
841 | |||
851 | # some types are well known and can be shorter |
|
842 | # some types are well known and can be shorter | |
852 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
843 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
853 | def type_name(v): |
|
844 | def type_name(v): | |
854 | tn = type(v).__name__ |
|
845 | tn = type(v).__name__ | |
855 | return abbrevs.get(tn,tn) |
|
846 | return abbrevs.get(tn,tn) | |
856 |
|
847 | |||
857 | varlist = map(get_vars,varnames) |
|
848 | varlist = map(get_vars,varnames) | |
858 |
|
849 | |||
859 | typelist = [] |
|
850 | typelist = [] | |
860 | for vv in varlist: |
|
851 | for vv in varlist: | |
861 | tt = type_name(vv) |
|
852 | tt = type_name(vv) | |
862 |
|
853 | |||
863 | if tt=='instance': |
|
854 | if tt=='instance': | |
864 | typelist.append( abbrevs.get(str(vv.__class__), |
|
855 | typelist.append( abbrevs.get(str(vv.__class__), | |
865 | str(vv.__class__))) |
|
856 | str(vv.__class__))) | |
866 | else: |
|
857 | else: | |
867 | typelist.append(tt) |
|
858 | typelist.append(tt) | |
868 |
|
859 | |||
869 | # column labels and # of spaces as separator |
|
860 | # column labels and # of spaces as separator | |
870 | varlabel = 'Variable' |
|
861 | varlabel = 'Variable' | |
871 | typelabel = 'Type' |
|
862 | typelabel = 'Type' | |
872 | datalabel = 'Data/Info' |
|
863 | datalabel = 'Data/Info' | |
873 | colsep = 3 |
|
864 | colsep = 3 | |
874 | # variable format strings |
|
865 | # variable format strings | |
875 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
866 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
876 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
867 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
877 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
868 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
878 | # find the size of the columns to format the output nicely |
|
869 | # find the size of the columns to format the output nicely | |
879 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
870 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
880 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
871 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
881 | # table header |
|
872 | # table header | |
882 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
873 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
883 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
874 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
884 | # and the table itself |
|
875 | # and the table itself | |
885 | kb = 1024 |
|
876 | kb = 1024 | |
886 | Mb = 1048576 # kb**2 |
|
877 | Mb = 1048576 # kb**2 | |
887 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
878 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
888 | print itpl(vformat), |
|
879 | print itpl(vformat), | |
889 | if vtype in seq_types: |
|
880 | if vtype in seq_types: | |
890 | print len(var) |
|
881 | print len(var) | |
891 | elif vtype in [array_type,ndarray_type]: |
|
882 | elif vtype in [array_type,ndarray_type]: | |
892 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
883 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
893 | if vtype==ndarray_type: |
|
884 | if vtype==ndarray_type: | |
894 | # numpy |
|
885 | # numpy | |
895 | vsize = var.size |
|
886 | vsize = var.size | |
896 | vbytes = vsize*var.itemsize |
|
887 | vbytes = vsize*var.itemsize | |
897 | vdtype = var.dtype |
|
888 | vdtype = var.dtype | |
898 | else: |
|
889 | else: | |
899 | # Numeric |
|
890 | # Numeric | |
900 | vsize = Numeric.size(var) |
|
891 | vsize = Numeric.size(var) | |
901 | vbytes = vsize*var.itemsize() |
|
892 | vbytes = vsize*var.itemsize() | |
902 | vdtype = var.typecode() |
|
893 | vdtype = var.typecode() | |
903 |
|
894 | |||
904 | if vbytes < 100000: |
|
895 | if vbytes < 100000: | |
905 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
896 | print aformat % (vshape,vsize,vdtype,vbytes) | |
906 | else: |
|
897 | else: | |
907 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
898 | print aformat % (vshape,vsize,vdtype,vbytes), | |
908 | if vbytes < Mb: |
|
899 | if vbytes < Mb: | |
909 | print '(%s kb)' % (vbytes/kb,) |
|
900 | print '(%s kb)' % (vbytes/kb,) | |
910 | else: |
|
901 | else: | |
911 | print '(%s Mb)' % (vbytes/Mb,) |
|
902 | print '(%s Mb)' % (vbytes/Mb,) | |
912 | else: |
|
903 | else: | |
913 | try: |
|
904 | try: | |
914 | vstr = str(var) |
|
905 | vstr = str(var) | |
915 | except UnicodeEncodeError: |
|
906 | except UnicodeEncodeError: | |
916 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
907 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
917 | 'backslashreplace') |
|
908 | 'backslashreplace') | |
918 | vstr = vstr.replace('\n','\\n') |
|
909 | vstr = vstr.replace('\n','\\n') | |
919 | if len(vstr) < 50: |
|
910 | if len(vstr) < 50: | |
920 | print vstr |
|
911 | print vstr | |
921 | else: |
|
912 | else: | |
922 | printpl(vfmt_short) |
|
913 | printpl(vfmt_short) | |
923 |
|
914 | |||
924 | def magic_reset(self, parameter_s=''): |
|
915 | def magic_reset(self, parameter_s=''): | |
925 | """Resets the namespace by removing all names defined by the user. |
|
916 | """Resets the namespace by removing all names defined by the user. | |
926 |
|
917 | |||
927 | Input/Output history are left around in case you need them. |
|
918 | Input/Output history are left around in case you need them. | |
928 |
|
919 | |||
929 | Parameters |
|
920 | Parameters | |
930 | ---------- |
|
921 | ---------- | |
931 | -y : force reset without asking for confirmation. |
|
922 | -y : force reset without asking for confirmation. | |
932 |
|
923 | |||
933 | Examples |
|
924 | Examples | |
934 | -------- |
|
925 | -------- | |
935 | In [6]: a = 1 |
|
926 | In [6]: a = 1 | |
936 |
|
927 | |||
937 | In [7]: a |
|
928 | In [7]: a | |
938 | Out[7]: 1 |
|
929 | Out[7]: 1 | |
939 |
|
930 | |||
940 | In [8]: 'a' in _ip.user_ns |
|
931 | In [8]: 'a' in _ip.user_ns | |
941 | Out[8]: True |
|
932 | Out[8]: True | |
942 |
|
933 | |||
943 | In [9]: %reset -f |
|
934 | In [9]: %reset -f | |
944 |
|
935 | |||
945 | In [10]: 'a' in _ip.user_ns |
|
936 | In [10]: 'a' in _ip.user_ns | |
946 | Out[10]: False |
|
937 | Out[10]: False | |
947 | """ |
|
938 | """ | |
948 |
|
939 | |||
949 | if parameter_s == '-f': |
|
940 | if parameter_s == '-f': | |
950 | ans = True |
|
941 | ans = True | |
951 | else: |
|
942 | else: | |
952 | ans = self.shell.ask_yes_no( |
|
943 | ans = self.shell.ask_yes_no( | |
953 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
944 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
954 | if not ans: |
|
945 | if not ans: | |
955 | print 'Nothing done.' |
|
946 | print 'Nothing done.' | |
956 | return |
|
947 | return | |
957 | user_ns = self.shell.user_ns |
|
948 | user_ns = self.shell.user_ns | |
958 | for i in self.magic_who_ls(): |
|
949 | for i in self.magic_who_ls(): | |
959 | del(user_ns[i]) |
|
950 | del(user_ns[i]) | |
960 |
|
951 | |||
961 | # Also flush the private list of module references kept for script |
|
952 | # Also flush the private list of module references kept for script | |
962 | # execution protection |
|
953 | # execution protection | |
963 | self.shell.clear_main_mod_cache() |
|
954 | self.shell.clear_main_mod_cache() | |
964 |
|
955 | |||
965 | def magic_reset_selective(self, parameter_s=''): |
|
956 | def magic_reset_selective(self, parameter_s=''): | |
966 | """Resets the namespace by removing names defined by the user. |
|
957 | """Resets the namespace by removing names defined by the user. | |
967 |
|
958 | |||
968 | Input/Output history are left around in case you need them. |
|
959 | Input/Output history are left around in case you need them. | |
969 |
|
960 | |||
970 | %reset_selective [-f] regex |
|
961 | %reset_selective [-f] regex | |
971 |
|
962 | |||
972 | No action is taken if regex is not included |
|
963 | No action is taken if regex is not included | |
973 |
|
964 | |||
974 | Options |
|
965 | Options | |
975 | -f : force reset without asking for confirmation. |
|
966 | -f : force reset without asking for confirmation. | |
976 |
|
967 | |||
977 | Examples |
|
968 | Examples | |
978 | -------- |
|
969 | -------- | |
979 |
|
970 | |||
980 | We first fully reset the namespace so your output looks identical to |
|
971 | We first fully reset the namespace so your output looks identical to | |
981 | this example for pedagogical reasons; in practice you do not need a |
|
972 | this example for pedagogical reasons; in practice you do not need a | |
982 | full reset. |
|
973 | full reset. | |
983 |
|
974 | |||
984 | In [1]: %reset -f |
|
975 | In [1]: %reset -f | |
985 |
|
976 | |||
986 | Now, with a clean namespace we can make a few variables and use |
|
977 | Now, with a clean namespace we can make a few variables and use | |
987 | %reset_selective to only delete names that match our regexp: |
|
978 | %reset_selective to only delete names that match our regexp: | |
988 |
|
979 | |||
989 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
980 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
990 |
|
981 | |||
991 | In [3]: who_ls |
|
982 | In [3]: who_ls | |
992 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
983 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
993 |
|
984 | |||
994 | In [4]: %reset_selective -f b[2-3]m |
|
985 | In [4]: %reset_selective -f b[2-3]m | |
995 |
|
986 | |||
996 | In [5]: who_ls |
|
987 | In [5]: who_ls | |
997 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
988 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
998 |
|
989 | |||
999 | In [6]: %reset_selective -f d |
|
990 | In [6]: %reset_selective -f d | |
1000 |
|
991 | |||
1001 | In [7]: who_ls |
|
992 | In [7]: who_ls | |
1002 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
993 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1003 |
|
994 | |||
1004 | In [8]: %reset_selective -f c |
|
995 | In [8]: %reset_selective -f c | |
1005 |
|
996 | |||
1006 | In [9]: who_ls |
|
997 | In [9]: who_ls | |
1007 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
998 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1008 |
|
999 | |||
1009 | In [10]: %reset_selective -f b |
|
1000 | In [10]: %reset_selective -f b | |
1010 |
|
1001 | |||
1011 | In [11]: who_ls |
|
1002 | In [11]: who_ls | |
1012 | Out[11]: ['a'] |
|
1003 | Out[11]: ['a'] | |
1013 | """ |
|
1004 | """ | |
1014 |
|
1005 | |||
1015 | opts, regex = self.parse_options(parameter_s,'f') |
|
1006 | opts, regex = self.parse_options(parameter_s,'f') | |
1016 |
|
1007 | |||
1017 | if opts.has_key('f'): |
|
1008 | if opts.has_key('f'): | |
1018 | ans = True |
|
1009 | ans = True | |
1019 | else: |
|
1010 | else: | |
1020 | ans = self.shell.ask_yes_no( |
|
1011 | ans = self.shell.ask_yes_no( | |
1021 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1012 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1022 | if not ans: |
|
1013 | if not ans: | |
1023 | print 'Nothing done.' |
|
1014 | print 'Nothing done.' | |
1024 | return |
|
1015 | return | |
1025 | user_ns = self.shell.user_ns |
|
1016 | user_ns = self.shell.user_ns | |
1026 | if not regex: |
|
1017 | if not regex: | |
1027 | print 'No regex pattern specified. Nothing done.' |
|
1018 | print 'No regex pattern specified. Nothing done.' | |
1028 | return |
|
1019 | return | |
1029 | else: |
|
1020 | else: | |
1030 | try: |
|
1021 | try: | |
1031 | m = re.compile(regex) |
|
1022 | m = re.compile(regex) | |
1032 | except TypeError: |
|
1023 | except TypeError: | |
1033 | raise TypeError('regex must be a string or compiled pattern') |
|
1024 | raise TypeError('regex must be a string or compiled pattern') | |
1034 | for i in self.magic_who_ls(): |
|
1025 | for i in self.magic_who_ls(): | |
1035 | if m.search(i): |
|
1026 | if m.search(i): | |
1036 | del(user_ns[i]) |
|
1027 | del(user_ns[i]) | |
1037 |
|
1028 | |||
1038 | def magic_logstart(self,parameter_s=''): |
|
1029 | def magic_logstart(self,parameter_s=''): | |
1039 | """Start logging anywhere in a session. |
|
1030 | """Start logging anywhere in a session. | |
1040 |
|
1031 | |||
1041 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1032 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1042 |
|
1033 | |||
1043 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1034 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1044 | current directory, in 'rotate' mode (see below). |
|
1035 | current directory, in 'rotate' mode (see below). | |
1045 |
|
1036 | |||
1046 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1037 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1047 | history up to that point and then continues logging. |
|
1038 | history up to that point and then continues logging. | |
1048 |
|
1039 | |||
1049 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1040 | %logstart takes a second optional parameter: logging mode. This can be one | |
1050 | of (note that the modes are given unquoted):\\ |
|
1041 | of (note that the modes are given unquoted):\\ | |
1051 | append: well, that says it.\\ |
|
1042 | append: well, that says it.\\ | |
1052 | backup: rename (if exists) to name~ and start name.\\ |
|
1043 | backup: rename (if exists) to name~ and start name.\\ | |
1053 | global: single logfile in your home dir, appended to.\\ |
|
1044 | global: single logfile in your home dir, appended to.\\ | |
1054 | over : overwrite existing log.\\ |
|
1045 | over : overwrite existing log.\\ | |
1055 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1046 | rotate: create rotating logs name.1~, name.2~, etc. | |
1056 |
|
1047 | |||
1057 | Options: |
|
1048 | Options: | |
1058 |
|
1049 | |||
1059 | -o: log also IPython's output. In this mode, all commands which |
|
1050 | -o: log also IPython's output. In this mode, all commands which | |
1060 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1051 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1061 | their corresponding input line. The output lines are always |
|
1052 | their corresponding input line. The output lines are always | |
1062 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1053 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1063 | Python code. |
|
1054 | Python code. | |
1064 |
|
1055 | |||
1065 | Since this marker is always the same, filtering only the output from |
|
1056 | Since this marker is always the same, filtering only the output from | |
1066 | a log is very easy, using for example a simple awk call: |
|
1057 | a log is very easy, using for example a simple awk call: | |
1067 |
|
1058 | |||
1068 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1059 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1069 |
|
1060 | |||
1070 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1061 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1071 | input, so that user lines are logged in their final form, converted |
|
1062 | input, so that user lines are logged in their final form, converted | |
1072 | into valid Python. For example, %Exit is logged as |
|
1063 | into valid Python. For example, %Exit is logged as | |
1073 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1064 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1074 | exactly as typed, with no transformations applied. |
|
1065 | exactly as typed, with no transformations applied. | |
1075 |
|
1066 | |||
1076 | -t: put timestamps before each input line logged (these are put in |
|
1067 | -t: put timestamps before each input line logged (these are put in | |
1077 | comments).""" |
|
1068 | comments).""" | |
1078 |
|
1069 | |||
1079 | opts,par = self.parse_options(parameter_s,'ort') |
|
1070 | opts,par = self.parse_options(parameter_s,'ort') | |
1080 | log_output = 'o' in opts |
|
1071 | log_output = 'o' in opts | |
1081 | log_raw_input = 'r' in opts |
|
1072 | log_raw_input = 'r' in opts | |
1082 | timestamp = 't' in opts |
|
1073 | timestamp = 't' in opts | |
1083 |
|
1074 | |||
1084 | logger = self.shell.logger |
|
1075 | logger = self.shell.logger | |
1085 |
|
1076 | |||
1086 | # if no args are given, the defaults set in the logger constructor by |
|
1077 | # if no args are given, the defaults set in the logger constructor by | |
1087 | # ipytohn remain valid |
|
1078 | # ipytohn remain valid | |
1088 | if par: |
|
1079 | if par: | |
1089 | try: |
|
1080 | try: | |
1090 | logfname,logmode = par.split() |
|
1081 | logfname,logmode = par.split() | |
1091 | except: |
|
1082 | except: | |
1092 | logfname = par |
|
1083 | logfname = par | |
1093 | logmode = 'backup' |
|
1084 | logmode = 'backup' | |
1094 | else: |
|
1085 | else: | |
1095 | logfname = logger.logfname |
|
1086 | logfname = logger.logfname | |
1096 | logmode = logger.logmode |
|
1087 | logmode = logger.logmode | |
1097 | # put logfname into rc struct as if it had been called on the command |
|
1088 | # put logfname into rc struct as if it had been called on the command | |
1098 | # line, so it ends up saved in the log header Save it in case we need |
|
1089 | # line, so it ends up saved in the log header Save it in case we need | |
1099 | # to restore it... |
|
1090 | # to restore it... | |
1100 | old_logfile = self.shell.logfile |
|
1091 | old_logfile = self.shell.logfile | |
1101 | if logfname: |
|
1092 | if logfname: | |
1102 | logfname = os.path.expanduser(logfname) |
|
1093 | logfname = os.path.expanduser(logfname) | |
1103 | self.shell.logfile = logfname |
|
1094 | self.shell.logfile = logfname | |
1104 |
|
1095 | |||
1105 | loghead = '# IPython log file\n\n' |
|
1096 | loghead = '# IPython log file\n\n' | |
1106 | try: |
|
1097 | try: | |
1107 | started = logger.logstart(logfname,loghead,logmode, |
|
1098 | started = logger.logstart(logfname,loghead,logmode, | |
1108 | log_output,timestamp,log_raw_input) |
|
1099 | log_output,timestamp,log_raw_input) | |
1109 | except: |
|
1100 | except: | |
1110 | self.shell.logfile = old_logfile |
|
1101 | self.shell.logfile = old_logfile | |
1111 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1102 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1112 | else: |
|
1103 | else: | |
1113 | # log input history up to this point, optionally interleaving |
|
1104 | # log input history up to this point, optionally interleaving | |
1114 | # output if requested |
|
1105 | # output if requested | |
1115 |
|
1106 | |||
1116 | if timestamp: |
|
1107 | if timestamp: | |
1117 | # disable timestamping for the previous history, since we've |
|
1108 | # disable timestamping for the previous history, since we've | |
1118 | # lost those already (no time machine here). |
|
1109 | # lost those already (no time machine here). | |
1119 | logger.timestamp = False |
|
1110 | logger.timestamp = False | |
1120 |
|
1111 | |||
1121 | if log_raw_input: |
|
1112 | if log_raw_input: | |
1122 | input_hist = self.shell.input_hist_raw |
|
1113 | input_hist = self.shell.input_hist_raw | |
1123 | else: |
|
1114 | else: | |
1124 | input_hist = self.shell.input_hist |
|
1115 | input_hist = self.shell.input_hist | |
1125 |
|
1116 | |||
1126 | if log_output: |
|
1117 | if log_output: | |
1127 | log_write = logger.log_write |
|
1118 | log_write = logger.log_write | |
1128 | output_hist = self.shell.output_hist |
|
1119 | output_hist = self.shell.output_hist | |
1129 | for n in range(1,len(input_hist)-1): |
|
1120 | for n in range(1,len(input_hist)-1): | |
1130 | log_write(input_hist[n].rstrip()) |
|
1121 | log_write(input_hist[n].rstrip()) | |
1131 | if n in output_hist: |
|
1122 | if n in output_hist: | |
1132 | log_write(repr(output_hist[n]),'output') |
|
1123 | log_write(repr(output_hist[n]),'output') | |
1133 | else: |
|
1124 | else: | |
1134 | logger.log_write(input_hist[1:]) |
|
1125 | logger.log_write(input_hist[1:]) | |
1135 | if timestamp: |
|
1126 | if timestamp: | |
1136 | # re-enable timestamping |
|
1127 | # re-enable timestamping | |
1137 | logger.timestamp = True |
|
1128 | logger.timestamp = True | |
1138 |
|
1129 | |||
1139 | print ('Activating auto-logging. ' |
|
1130 | print ('Activating auto-logging. ' | |
1140 | 'Current session state plus future input saved.') |
|
1131 | 'Current session state plus future input saved.') | |
1141 | logger.logstate() |
|
1132 | logger.logstate() | |
1142 |
|
1133 | |||
1143 | def magic_logstop(self,parameter_s=''): |
|
1134 | def magic_logstop(self,parameter_s=''): | |
1144 | """Fully stop logging and close log file. |
|
1135 | """Fully stop logging and close log file. | |
1145 |
|
1136 | |||
1146 | In order to start logging again, a new %logstart call needs to be made, |
|
1137 | In order to start logging again, a new %logstart call needs to be made, | |
1147 | possibly (though not necessarily) with a new filename, mode and other |
|
1138 | possibly (though not necessarily) with a new filename, mode and other | |
1148 | options.""" |
|
1139 | options.""" | |
1149 | self.logger.logstop() |
|
1140 | self.logger.logstop() | |
1150 |
|
1141 | |||
1151 | def magic_logoff(self,parameter_s=''): |
|
1142 | def magic_logoff(self,parameter_s=''): | |
1152 | """Temporarily stop logging. |
|
1143 | """Temporarily stop logging. | |
1153 |
|
1144 | |||
1154 | You must have previously started logging.""" |
|
1145 | You must have previously started logging.""" | |
1155 | self.shell.logger.switch_log(0) |
|
1146 | self.shell.logger.switch_log(0) | |
1156 |
|
1147 | |||
1157 | def magic_logon(self,parameter_s=''): |
|
1148 | def magic_logon(self,parameter_s=''): | |
1158 | """Restart logging. |
|
1149 | """Restart logging. | |
1159 |
|
1150 | |||
1160 | This function is for restarting logging which you've temporarily |
|
1151 | This function is for restarting logging which you've temporarily | |
1161 | stopped with %logoff. For starting logging for the first time, you |
|
1152 | stopped with %logoff. For starting logging for the first time, you | |
1162 | must use the %logstart function, which allows you to specify an |
|
1153 | must use the %logstart function, which allows you to specify an | |
1163 | optional log filename.""" |
|
1154 | optional log filename.""" | |
1164 |
|
1155 | |||
1165 | self.shell.logger.switch_log(1) |
|
1156 | self.shell.logger.switch_log(1) | |
1166 |
|
1157 | |||
1167 | def magic_logstate(self,parameter_s=''): |
|
1158 | def magic_logstate(self,parameter_s=''): | |
1168 | """Print the status of the logging system.""" |
|
1159 | """Print the status of the logging system.""" | |
1169 |
|
1160 | |||
1170 | self.shell.logger.logstate() |
|
1161 | self.shell.logger.logstate() | |
1171 |
|
1162 | |||
1172 | def magic_pdb(self, parameter_s=''): |
|
1163 | def magic_pdb(self, parameter_s=''): | |
1173 | """Control the automatic calling of the pdb interactive debugger. |
|
1164 | """Control the automatic calling of the pdb interactive debugger. | |
1174 |
|
1165 | |||
1175 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1166 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1176 | argument it works as a toggle. |
|
1167 | argument it works as a toggle. | |
1177 |
|
1168 | |||
1178 | When an exception is triggered, IPython can optionally call the |
|
1169 | When an exception is triggered, IPython can optionally call the | |
1179 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1170 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1180 | this feature on and off. |
|
1171 | this feature on and off. | |
1181 |
|
1172 | |||
1182 | The initial state of this feature is set in your ipythonrc |
|
1173 | The initial state of this feature is set in your ipythonrc | |
1183 | configuration file (the variable is called 'pdb'). |
|
1174 | configuration file (the variable is called 'pdb'). | |
1184 |
|
1175 | |||
1185 | If you want to just activate the debugger AFTER an exception has fired, |
|
1176 | If you want to just activate the debugger AFTER an exception has fired, | |
1186 | without having to type '%pdb on' and rerunning your code, you can use |
|
1177 | without having to type '%pdb on' and rerunning your code, you can use | |
1187 | the %debug magic.""" |
|
1178 | the %debug magic.""" | |
1188 |
|
1179 | |||
1189 | par = parameter_s.strip().lower() |
|
1180 | par = parameter_s.strip().lower() | |
1190 |
|
1181 | |||
1191 | if par: |
|
1182 | if par: | |
1192 | try: |
|
1183 | try: | |
1193 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1184 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1194 | except KeyError: |
|
1185 | except KeyError: | |
1195 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1186 | print ('Incorrect argument. Use on/1, off/0, ' | |
1196 | 'or nothing for a toggle.') |
|
1187 | 'or nothing for a toggle.') | |
1197 | return |
|
1188 | return | |
1198 | else: |
|
1189 | else: | |
1199 | # toggle |
|
1190 | # toggle | |
1200 | new_pdb = not self.shell.call_pdb |
|
1191 | new_pdb = not self.shell.call_pdb | |
1201 |
|
1192 | |||
1202 | # set on the shell |
|
1193 | # set on the shell | |
1203 | self.shell.call_pdb = new_pdb |
|
1194 | self.shell.call_pdb = new_pdb | |
1204 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1195 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1205 |
|
1196 | |||
1206 | def magic_debug(self, parameter_s=''): |
|
1197 | def magic_debug(self, parameter_s=''): | |
1207 | """Activate the interactive debugger in post-mortem mode. |
|
1198 | """Activate the interactive debugger in post-mortem mode. | |
1208 |
|
1199 | |||
1209 | If an exception has just occurred, this lets you inspect its stack |
|
1200 | If an exception has just occurred, this lets you inspect its stack | |
1210 | frames interactively. Note that this will always work only on the last |
|
1201 | frames interactively. Note that this will always work only on the last | |
1211 | traceback that occurred, so you must call this quickly after an |
|
1202 | traceback that occurred, so you must call this quickly after an | |
1212 | exception that you wish to inspect has fired, because if another one |
|
1203 | exception that you wish to inspect has fired, because if another one | |
1213 | occurs, it clobbers the previous one. |
|
1204 | occurs, it clobbers the previous one. | |
1214 |
|
1205 | |||
1215 | If you want IPython to automatically do this on every exception, see |
|
1206 | If you want IPython to automatically do this on every exception, see | |
1216 | the %pdb magic for more details. |
|
1207 | the %pdb magic for more details. | |
1217 | """ |
|
1208 | """ | |
1218 | self.shell.debugger(force=True) |
|
1209 | self.shell.debugger(force=True) | |
1219 |
|
1210 | |||
1220 | @testdec.skip_doctest |
|
1211 | @testdec.skip_doctest | |
1221 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1212 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1222 | opts=None,arg_lst=None,prog_ns=None): |
|
1213 | opts=None,arg_lst=None,prog_ns=None): | |
1223 |
|
1214 | |||
1224 | """Run a statement through the python code profiler. |
|
1215 | """Run a statement through the python code profiler. | |
1225 |
|
1216 | |||
1226 | Usage: |
|
1217 | Usage: | |
1227 | %prun [options] statement |
|
1218 | %prun [options] statement | |
1228 |
|
1219 | |||
1229 | The given statement (which doesn't require quote marks) is run via the |
|
1220 | The given statement (which doesn't require quote marks) is run via the | |
1230 | python profiler in a manner similar to the profile.run() function. |
|
1221 | python profiler in a manner similar to the profile.run() function. | |
1231 | Namespaces are internally managed to work correctly; profile.run |
|
1222 | Namespaces are internally managed to work correctly; profile.run | |
1232 | cannot be used in IPython because it makes certain assumptions about |
|
1223 | cannot be used in IPython because it makes certain assumptions about | |
1233 | namespaces which do not hold under IPython. |
|
1224 | namespaces which do not hold under IPython. | |
1234 |
|
1225 | |||
1235 | Options: |
|
1226 | Options: | |
1236 |
|
1227 | |||
1237 | -l <limit>: you can place restrictions on what or how much of the |
|
1228 | -l <limit>: you can place restrictions on what or how much of the | |
1238 | profile gets printed. The limit value can be: |
|
1229 | profile gets printed. The limit value can be: | |
1239 |
|
1230 | |||
1240 | * A string: only information for function names containing this string |
|
1231 | * A string: only information for function names containing this string | |
1241 | is printed. |
|
1232 | is printed. | |
1242 |
|
1233 | |||
1243 | * An integer: only these many lines are printed. |
|
1234 | * An integer: only these many lines are printed. | |
1244 |
|
1235 | |||
1245 | * A float (between 0 and 1): this fraction of the report is printed |
|
1236 | * A float (between 0 and 1): this fraction of the report is printed | |
1246 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1237 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1247 |
|
1238 | |||
1248 | You can combine several limits with repeated use of the option. For |
|
1239 | You can combine several limits with repeated use of the option. For | |
1249 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1240 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1250 | information about class constructors. |
|
1241 | information about class constructors. | |
1251 |
|
1242 | |||
1252 | -r: return the pstats.Stats object generated by the profiling. This |
|
1243 | -r: return the pstats.Stats object generated by the profiling. This | |
1253 | object has all the information about the profile in it, and you can |
|
1244 | object has all the information about the profile in it, and you can | |
1254 | later use it for further analysis or in other functions. |
|
1245 | later use it for further analysis or in other functions. | |
1255 |
|
1246 | |||
1256 | -s <key>: sort profile by given key. You can provide more than one key |
|
1247 | -s <key>: sort profile by given key. You can provide more than one key | |
1257 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1248 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1258 | default sorting key is 'time'. |
|
1249 | default sorting key is 'time'. | |
1259 |
|
1250 | |||
1260 | The following is copied verbatim from the profile documentation |
|
1251 | The following is copied verbatim from the profile documentation | |
1261 | referenced below: |
|
1252 | referenced below: | |
1262 |
|
1253 | |||
1263 | When more than one key is provided, additional keys are used as |
|
1254 | When more than one key is provided, additional keys are used as | |
1264 | secondary criteria when the there is equality in all keys selected |
|
1255 | secondary criteria when the there is equality in all keys selected | |
1265 | before them. |
|
1256 | before them. | |
1266 |
|
1257 | |||
1267 | Abbreviations can be used for any key names, as long as the |
|
1258 | Abbreviations can be used for any key names, as long as the | |
1268 | abbreviation is unambiguous. The following are the keys currently |
|
1259 | abbreviation is unambiguous. The following are the keys currently | |
1269 | defined: |
|
1260 | defined: | |
1270 |
|
1261 | |||
1271 | Valid Arg Meaning |
|
1262 | Valid Arg Meaning | |
1272 | "calls" call count |
|
1263 | "calls" call count | |
1273 | "cumulative" cumulative time |
|
1264 | "cumulative" cumulative time | |
1274 | "file" file name |
|
1265 | "file" file name | |
1275 | "module" file name |
|
1266 | "module" file name | |
1276 | "pcalls" primitive call count |
|
1267 | "pcalls" primitive call count | |
1277 | "line" line number |
|
1268 | "line" line number | |
1278 | "name" function name |
|
1269 | "name" function name | |
1279 | "nfl" name/file/line |
|
1270 | "nfl" name/file/line | |
1280 | "stdname" standard name |
|
1271 | "stdname" standard name | |
1281 | "time" internal time |
|
1272 | "time" internal time | |
1282 |
|
1273 | |||
1283 | Note that all sorts on statistics are in descending order (placing |
|
1274 | Note that all sorts on statistics are in descending order (placing | |
1284 | most time consuming items first), where as name, file, and line number |
|
1275 | most time consuming items first), where as name, file, and line number | |
1285 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1276 | searches are in ascending order (i.e., alphabetical). The subtle | |
1286 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1277 | distinction between "nfl" and "stdname" is that the standard name is a | |
1287 | sort of the name as printed, which means that the embedded line |
|
1278 | sort of the name as printed, which means that the embedded line | |
1288 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1279 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1289 | would (if the file names were the same) appear in the string order |
|
1280 | would (if the file names were the same) appear in the string order | |
1290 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1281 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1291 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1282 | line numbers. In fact, sort_stats("nfl") is the same as | |
1292 | sort_stats("name", "file", "line"). |
|
1283 | sort_stats("name", "file", "line"). | |
1293 |
|
1284 | |||
1294 | -T <filename>: save profile results as shown on screen to a text |
|
1285 | -T <filename>: save profile results as shown on screen to a text | |
1295 | file. The profile is still shown on screen. |
|
1286 | file. The profile is still shown on screen. | |
1296 |
|
1287 | |||
1297 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1288 | -D <filename>: save (via dump_stats) profile statistics to given | |
1298 | filename. This data is in a format understod by the pstats module, and |
|
1289 | filename. This data is in a format understod by the pstats module, and | |
1299 | is generated by a call to the dump_stats() method of profile |
|
1290 | is generated by a call to the dump_stats() method of profile | |
1300 | objects. The profile is still shown on screen. |
|
1291 | objects. The profile is still shown on screen. | |
1301 |
|
1292 | |||
1302 | If you want to run complete programs under the profiler's control, use |
|
1293 | If you want to run complete programs under the profiler's control, use | |
1303 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1294 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1304 | contains profiler specific options as described here. |
|
1295 | contains profiler specific options as described here. | |
1305 |
|
1296 | |||
1306 | You can read the complete documentation for the profile module with:: |
|
1297 | You can read the complete documentation for the profile module with:: | |
1307 |
|
1298 | |||
1308 | In [1]: import profile; profile.help() |
|
1299 | In [1]: import profile; profile.help() | |
1309 | """ |
|
1300 | """ | |
1310 |
|
1301 | |||
1311 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1302 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1312 | # protect user quote marks |
|
1303 | # protect user quote marks | |
1313 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1304 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1314 |
|
1305 | |||
1315 | if user_mode: # regular user call |
|
1306 | if user_mode: # regular user call | |
1316 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1307 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1317 | list_all=1) |
|
1308 | list_all=1) | |
1318 | namespace = self.shell.user_ns |
|
1309 | namespace = self.shell.user_ns | |
1319 | else: # called to run a program by %run -p |
|
1310 | else: # called to run a program by %run -p | |
1320 | try: |
|
1311 | try: | |
1321 | filename = get_py_filename(arg_lst[0]) |
|
1312 | filename = get_py_filename(arg_lst[0]) | |
1322 | except IOError,msg: |
|
1313 | except IOError,msg: | |
1323 | error(msg) |
|
1314 | error(msg) | |
1324 | return |
|
1315 | return | |
1325 |
|
1316 | |||
1326 | arg_str = 'execfile(filename,prog_ns)' |
|
1317 | arg_str = 'execfile(filename,prog_ns)' | |
1327 | namespace = locals() |
|
1318 | namespace = locals() | |
1328 |
|
1319 | |||
1329 | opts.merge(opts_def) |
|
1320 | opts.merge(opts_def) | |
1330 |
|
1321 | |||
1331 | prof = profile.Profile() |
|
1322 | prof = profile.Profile() | |
1332 | try: |
|
1323 | try: | |
1333 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1324 | prof = prof.runctx(arg_str,namespace,namespace) | |
1334 | sys_exit = '' |
|
1325 | sys_exit = '' | |
1335 | except SystemExit: |
|
1326 | except SystemExit: | |
1336 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1327 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1337 |
|
1328 | |||
1338 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1329 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1339 |
|
1330 | |||
1340 | lims = opts.l |
|
1331 | lims = opts.l | |
1341 | if lims: |
|
1332 | if lims: | |
1342 | lims = [] # rebuild lims with ints/floats/strings |
|
1333 | lims = [] # rebuild lims with ints/floats/strings | |
1343 | for lim in opts.l: |
|
1334 | for lim in opts.l: | |
1344 | try: |
|
1335 | try: | |
1345 | lims.append(int(lim)) |
|
1336 | lims.append(int(lim)) | |
1346 | except ValueError: |
|
1337 | except ValueError: | |
1347 | try: |
|
1338 | try: | |
1348 | lims.append(float(lim)) |
|
1339 | lims.append(float(lim)) | |
1349 | except ValueError: |
|
1340 | except ValueError: | |
1350 | lims.append(lim) |
|
1341 | lims.append(lim) | |
1351 |
|
1342 | |||
1352 | # Trap output. |
|
1343 | # Trap output. | |
1353 | stdout_trap = StringIO() |
|
1344 | stdout_trap = StringIO() | |
1354 |
|
1345 | |||
1355 | if hasattr(stats,'stream'): |
|
1346 | if hasattr(stats,'stream'): | |
1356 | # In newer versions of python, the stats object has a 'stream' |
|
1347 | # In newer versions of python, the stats object has a 'stream' | |
1357 | # attribute to write into. |
|
1348 | # attribute to write into. | |
1358 | stats.stream = stdout_trap |
|
1349 | stats.stream = stdout_trap | |
1359 | stats.print_stats(*lims) |
|
1350 | stats.print_stats(*lims) | |
1360 | else: |
|
1351 | else: | |
1361 | # For older versions, we manually redirect stdout during printing |
|
1352 | # For older versions, we manually redirect stdout during printing | |
1362 | sys_stdout = sys.stdout |
|
1353 | sys_stdout = sys.stdout | |
1363 | try: |
|
1354 | try: | |
1364 | sys.stdout = stdout_trap |
|
1355 | sys.stdout = stdout_trap | |
1365 | stats.print_stats(*lims) |
|
1356 | stats.print_stats(*lims) | |
1366 | finally: |
|
1357 | finally: | |
1367 | sys.stdout = sys_stdout |
|
1358 | sys.stdout = sys_stdout | |
1368 |
|
1359 | |||
1369 | output = stdout_trap.getvalue() |
|
1360 | output = stdout_trap.getvalue() | |
1370 | output = output.rstrip() |
|
1361 | output = output.rstrip() | |
1371 |
|
1362 | |||
1372 | page.page(output) |
|
1363 | page.page(output) | |
1373 | print sys_exit, |
|
1364 | print sys_exit, | |
1374 |
|
1365 | |||
1375 | dump_file = opts.D[0] |
|
1366 | dump_file = opts.D[0] | |
1376 | text_file = opts.T[0] |
|
1367 | text_file = opts.T[0] | |
1377 | if dump_file: |
|
1368 | if dump_file: | |
1378 | prof.dump_stats(dump_file) |
|
1369 | prof.dump_stats(dump_file) | |
1379 | print '\n*** Profile stats marshalled to file',\ |
|
1370 | print '\n*** Profile stats marshalled to file',\ | |
1380 | `dump_file`+'.',sys_exit |
|
1371 | `dump_file`+'.',sys_exit | |
1381 | if text_file: |
|
1372 | if text_file: | |
1382 | pfile = file(text_file,'w') |
|
1373 | pfile = file(text_file,'w') | |
1383 | pfile.write(output) |
|
1374 | pfile.write(output) | |
1384 | pfile.close() |
|
1375 | pfile.close() | |
1385 | print '\n*** Profile printout saved to text file',\ |
|
1376 | print '\n*** Profile printout saved to text file',\ | |
1386 | `text_file`+'.',sys_exit |
|
1377 | `text_file`+'.',sys_exit | |
1387 |
|
1378 | |||
1388 | if opts.has_key('r'): |
|
1379 | if opts.has_key('r'): | |
1389 | return stats |
|
1380 | return stats | |
1390 | else: |
|
1381 | else: | |
1391 | return None |
|
1382 | return None | |
1392 |
|
1383 | |||
1393 | @testdec.skip_doctest |
|
1384 | @testdec.skip_doctest | |
1394 | def magic_run(self, parameter_s ='',runner=None, |
|
1385 | def magic_run(self, parameter_s ='',runner=None, | |
1395 | file_finder=get_py_filename): |
|
1386 | file_finder=get_py_filename): | |
1396 | """Run the named file inside IPython as a program. |
|
1387 | """Run the named file inside IPython as a program. | |
1397 |
|
1388 | |||
1398 | Usage:\\ |
|
1389 | Usage:\\ | |
1399 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1390 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1400 |
|
1391 | |||
1401 | Parameters after the filename are passed as command-line arguments to |
|
1392 | Parameters after the filename are passed as command-line arguments to | |
1402 | the program (put in sys.argv). Then, control returns to IPython's |
|
1393 | the program (put in sys.argv). Then, control returns to IPython's | |
1403 | prompt. |
|
1394 | prompt. | |
1404 |
|
1395 | |||
1405 | This is similar to running at a system prompt:\\ |
|
1396 | This is similar to running at a system prompt:\\ | |
1406 | $ python file args\\ |
|
1397 | $ python file args\\ | |
1407 | but with the advantage of giving you IPython's tracebacks, and of |
|
1398 | but with the advantage of giving you IPython's tracebacks, and of | |
1408 | loading all variables into your interactive namespace for further use |
|
1399 | loading all variables into your interactive namespace for further use | |
1409 | (unless -p is used, see below). |
|
1400 | (unless -p is used, see below). | |
1410 |
|
1401 | |||
1411 | The file is executed in a namespace initially consisting only of |
|
1402 | The file is executed in a namespace initially consisting only of | |
1412 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1403 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1413 | sees its environment as if it were being run as a stand-alone program |
|
1404 | sees its environment as if it were being run as a stand-alone program | |
1414 | (except for sharing global objects such as previously imported |
|
1405 | (except for sharing global objects such as previously imported | |
1415 | modules). But after execution, the IPython interactive namespace gets |
|
1406 | modules). But after execution, the IPython interactive namespace gets | |
1416 | updated with all variables defined in the program (except for __name__ |
|
1407 | updated with all variables defined in the program (except for __name__ | |
1417 | and sys.argv). This allows for very convenient loading of code for |
|
1408 | and sys.argv). This allows for very convenient loading of code for | |
1418 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1409 | interactive work, while giving each program a 'clean sheet' to run in. | |
1419 |
|
1410 | |||
1420 | Options: |
|
1411 | Options: | |
1421 |
|
1412 | |||
1422 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1413 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1423 | without extension (as python does under import). This allows running |
|
1414 | without extension (as python does under import). This allows running | |
1424 | scripts and reloading the definitions in them without calling code |
|
1415 | scripts and reloading the definitions in them without calling code | |
1425 | protected by an ' if __name__ == "__main__" ' clause. |
|
1416 | protected by an ' if __name__ == "__main__" ' clause. | |
1426 |
|
1417 | |||
1427 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1418 | -i: run the file in IPython's namespace instead of an empty one. This | |
1428 | is useful if you are experimenting with code written in a text editor |
|
1419 | is useful if you are experimenting with code written in a text editor | |
1429 | which depends on variables defined interactively. |
|
1420 | which depends on variables defined interactively. | |
1430 |
|
1421 | |||
1431 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1422 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1432 | being run. This is particularly useful if IPython is being used to |
|
1423 | being run. This is particularly useful if IPython is being used to | |
1433 | run unittests, which always exit with a sys.exit() call. In such |
|
1424 | run unittests, which always exit with a sys.exit() call. In such | |
1434 | cases you are interested in the output of the test results, not in |
|
1425 | cases you are interested in the output of the test results, not in | |
1435 | seeing a traceback of the unittest module. |
|
1426 | seeing a traceback of the unittest module. | |
1436 |
|
1427 | |||
1437 | -t: print timing information at the end of the run. IPython will give |
|
1428 | -t: print timing information at the end of the run. IPython will give | |
1438 | you an estimated CPU time consumption for your script, which under |
|
1429 | you an estimated CPU time consumption for your script, which under | |
1439 | Unix uses the resource module to avoid the wraparound problems of |
|
1430 | Unix uses the resource module to avoid the wraparound problems of | |
1440 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1431 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1441 | is also given (for Windows platforms this is reported as 0.0). |
|
1432 | is also given (for Windows platforms this is reported as 0.0). | |
1442 |
|
1433 | |||
1443 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1434 | If -t is given, an additional -N<N> option can be given, where <N> | |
1444 | must be an integer indicating how many times you want the script to |
|
1435 | must be an integer indicating how many times you want the script to | |
1445 | run. The final timing report will include total and per run results. |
|
1436 | run. The final timing report will include total and per run results. | |
1446 |
|
1437 | |||
1447 | For example (testing the script uniq_stable.py): |
|
1438 | For example (testing the script uniq_stable.py): | |
1448 |
|
1439 | |||
1449 | In [1]: run -t uniq_stable |
|
1440 | In [1]: run -t uniq_stable | |
1450 |
|
1441 | |||
1451 | IPython CPU timings (estimated):\\ |
|
1442 | IPython CPU timings (estimated):\\ | |
1452 | User : 0.19597 s.\\ |
|
1443 | User : 0.19597 s.\\ | |
1453 | System: 0.0 s.\\ |
|
1444 | System: 0.0 s.\\ | |
1454 |
|
1445 | |||
1455 | In [2]: run -t -N5 uniq_stable |
|
1446 | In [2]: run -t -N5 uniq_stable | |
1456 |
|
1447 | |||
1457 | IPython CPU timings (estimated):\\ |
|
1448 | IPython CPU timings (estimated):\\ | |
1458 | Total runs performed: 5\\ |
|
1449 | Total runs performed: 5\\ | |
1459 | Times : Total Per run\\ |
|
1450 | Times : Total Per run\\ | |
1460 | User : 0.910862 s, 0.1821724 s.\\ |
|
1451 | User : 0.910862 s, 0.1821724 s.\\ | |
1461 | System: 0.0 s, 0.0 s. |
|
1452 | System: 0.0 s, 0.0 s. | |
1462 |
|
1453 | |||
1463 | -d: run your program under the control of pdb, the Python debugger. |
|
1454 | -d: run your program under the control of pdb, the Python debugger. | |
1464 | This allows you to execute your program step by step, watch variables, |
|
1455 | This allows you to execute your program step by step, watch variables, | |
1465 | etc. Internally, what IPython does is similar to calling: |
|
1456 | etc. Internally, what IPython does is similar to calling: | |
1466 |
|
1457 | |||
1467 | pdb.run('execfile("YOURFILENAME")') |
|
1458 | pdb.run('execfile("YOURFILENAME")') | |
1468 |
|
1459 | |||
1469 | with a breakpoint set on line 1 of your file. You can change the line |
|
1460 | with a breakpoint set on line 1 of your file. You can change the line | |
1470 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1461 | number for this automatic breakpoint to be <N> by using the -bN option | |
1471 | (where N must be an integer). For example: |
|
1462 | (where N must be an integer). For example: | |
1472 |
|
1463 | |||
1473 | %run -d -b40 myscript |
|
1464 | %run -d -b40 myscript | |
1474 |
|
1465 | |||
1475 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1466 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1476 | the first breakpoint must be set on a line which actually does |
|
1467 | the first breakpoint must be set on a line which actually does | |
1477 | something (not a comment or docstring) for it to stop execution. |
|
1468 | something (not a comment or docstring) for it to stop execution. | |
1478 |
|
1469 | |||
1479 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1470 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1480 | first enter 'c' (without qoutes) to start execution up to the first |
|
1471 | first enter 'c' (without qoutes) to start execution up to the first | |
1481 | breakpoint. |
|
1472 | breakpoint. | |
1482 |
|
1473 | |||
1483 | Entering 'help' gives information about the use of the debugger. You |
|
1474 | Entering 'help' gives information about the use of the debugger. You | |
1484 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1475 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1485 | at a prompt. |
|
1476 | at a prompt. | |
1486 |
|
1477 | |||
1487 | -p: run program under the control of the Python profiler module (which |
|
1478 | -p: run program under the control of the Python profiler module (which | |
1488 | prints a detailed report of execution times, function calls, etc). |
|
1479 | prints a detailed report of execution times, function calls, etc). | |
1489 |
|
1480 | |||
1490 | You can pass other options after -p which affect the behavior of the |
|
1481 | You can pass other options after -p which affect the behavior of the | |
1491 | profiler itself. See the docs for %prun for details. |
|
1482 | profiler itself. See the docs for %prun for details. | |
1492 |
|
1483 | |||
1493 | In this mode, the program's variables do NOT propagate back to the |
|
1484 | In this mode, the program's variables do NOT propagate back to the | |
1494 | IPython interactive namespace (because they remain in the namespace |
|
1485 | IPython interactive namespace (because they remain in the namespace | |
1495 | where the profiler executes them). |
|
1486 | where the profiler executes them). | |
1496 |
|
1487 | |||
1497 | Internally this triggers a call to %prun, see its documentation for |
|
1488 | Internally this triggers a call to %prun, see its documentation for | |
1498 | details on the options available specifically for profiling. |
|
1489 | details on the options available specifically for profiling. | |
1499 |
|
1490 | |||
1500 | There is one special usage for which the text above doesn't apply: |
|
1491 | There is one special usage for which the text above doesn't apply: | |
1501 | if the filename ends with .ipy, the file is run as ipython script, |
|
1492 | if the filename ends with .ipy, the file is run as ipython script, | |
1502 | just as if the commands were written on IPython prompt. |
|
1493 | just as if the commands were written on IPython prompt. | |
1503 | """ |
|
1494 | """ | |
1504 |
|
1495 | |||
1505 | # get arguments and set sys.argv for program to be run. |
|
1496 | # get arguments and set sys.argv for program to be run. | |
1506 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1497 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1507 | mode='list',list_all=1) |
|
1498 | mode='list',list_all=1) | |
1508 |
|
1499 | |||
1509 | try: |
|
1500 | try: | |
1510 | filename = file_finder(arg_lst[0]) |
|
1501 | filename = file_finder(arg_lst[0]) | |
1511 | except IndexError: |
|
1502 | except IndexError: | |
1512 | warn('you must provide at least a filename.') |
|
1503 | warn('you must provide at least a filename.') | |
1513 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1504 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1514 | return |
|
1505 | return | |
1515 | except IOError,msg: |
|
1506 | except IOError,msg: | |
1516 | error(msg) |
|
1507 | error(msg) | |
1517 | return |
|
1508 | return | |
1518 |
|
1509 | |||
1519 | if filename.lower().endswith('.ipy'): |
|
1510 | if filename.lower().endswith('.ipy'): | |
1520 | self.shell.safe_execfile_ipy(filename) |
|
1511 | self.shell.safe_execfile_ipy(filename) | |
1521 | return |
|
1512 | return | |
1522 |
|
1513 | |||
1523 | # Control the response to exit() calls made by the script being run |
|
1514 | # Control the response to exit() calls made by the script being run | |
1524 | exit_ignore = opts.has_key('e') |
|
1515 | exit_ignore = opts.has_key('e') | |
1525 |
|
1516 | |||
1526 | # Make sure that the running script gets a proper sys.argv as if it |
|
1517 | # Make sure that the running script gets a proper sys.argv as if it | |
1527 | # were run from a system shell. |
|
1518 | # were run from a system shell. | |
1528 | save_argv = sys.argv # save it for later restoring |
|
1519 | save_argv = sys.argv # save it for later restoring | |
1529 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1520 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1530 |
|
1521 | |||
1531 | if opts.has_key('i'): |
|
1522 | if opts.has_key('i'): | |
1532 | # Run in user's interactive namespace |
|
1523 | # Run in user's interactive namespace | |
1533 | prog_ns = self.shell.user_ns |
|
1524 | prog_ns = self.shell.user_ns | |
1534 | __name__save = self.shell.user_ns['__name__'] |
|
1525 | __name__save = self.shell.user_ns['__name__'] | |
1535 | prog_ns['__name__'] = '__main__' |
|
1526 | prog_ns['__name__'] = '__main__' | |
1536 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1527 | main_mod = self.shell.new_main_mod(prog_ns) | |
1537 | else: |
|
1528 | else: | |
1538 | # Run in a fresh, empty namespace |
|
1529 | # Run in a fresh, empty namespace | |
1539 | if opts.has_key('n'): |
|
1530 | if opts.has_key('n'): | |
1540 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1531 | name = os.path.splitext(os.path.basename(filename))[0] | |
1541 | else: |
|
1532 | else: | |
1542 | name = '__main__' |
|
1533 | name = '__main__' | |
1543 |
|
1534 | |||
1544 | main_mod = self.shell.new_main_mod() |
|
1535 | main_mod = self.shell.new_main_mod() | |
1545 | prog_ns = main_mod.__dict__ |
|
1536 | prog_ns = main_mod.__dict__ | |
1546 | prog_ns['__name__'] = name |
|
1537 | prog_ns['__name__'] = name | |
1547 |
|
1538 | |||
1548 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1539 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1549 | # set the __file__ global in the script's namespace |
|
1540 | # set the __file__ global in the script's namespace | |
1550 | prog_ns['__file__'] = filename |
|
1541 | prog_ns['__file__'] = filename | |
1551 |
|
1542 | |||
1552 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1543 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1553 | # that, if we overwrite __main__, we replace it at the end |
|
1544 | # that, if we overwrite __main__, we replace it at the end | |
1554 | main_mod_name = prog_ns['__name__'] |
|
1545 | main_mod_name = prog_ns['__name__'] | |
1555 |
|
1546 | |||
1556 | if main_mod_name == '__main__': |
|
1547 | if main_mod_name == '__main__': | |
1557 | restore_main = sys.modules['__main__'] |
|
1548 | restore_main = sys.modules['__main__'] | |
1558 | else: |
|
1549 | else: | |
1559 | restore_main = False |
|
1550 | restore_main = False | |
1560 |
|
1551 | |||
1561 | # This needs to be undone at the end to prevent holding references to |
|
1552 | # This needs to be undone at the end to prevent holding references to | |
1562 | # every single object ever created. |
|
1553 | # every single object ever created. | |
1563 | sys.modules[main_mod_name] = main_mod |
|
1554 | sys.modules[main_mod_name] = main_mod | |
1564 |
|
1555 | |||
1565 | stats = None |
|
1556 | stats = None | |
1566 | try: |
|
1557 | try: | |
1567 | self.shell.savehist() |
|
1558 | self.shell.savehist() | |
1568 |
|
1559 | |||
1569 | if opts.has_key('p'): |
|
1560 | if opts.has_key('p'): | |
1570 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1561 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1571 | else: |
|
1562 | else: | |
1572 | if opts.has_key('d'): |
|
1563 | if opts.has_key('d'): | |
1573 | deb = debugger.Pdb(self.shell.colors) |
|
1564 | deb = debugger.Pdb(self.shell.colors) | |
1574 | # reset Breakpoint state, which is moronically kept |
|
1565 | # reset Breakpoint state, which is moronically kept | |
1575 | # in a class |
|
1566 | # in a class | |
1576 | bdb.Breakpoint.next = 1 |
|
1567 | bdb.Breakpoint.next = 1 | |
1577 | bdb.Breakpoint.bplist = {} |
|
1568 | bdb.Breakpoint.bplist = {} | |
1578 | bdb.Breakpoint.bpbynumber = [None] |
|
1569 | bdb.Breakpoint.bpbynumber = [None] | |
1579 | # Set an initial breakpoint to stop execution |
|
1570 | # Set an initial breakpoint to stop execution | |
1580 | maxtries = 10 |
|
1571 | maxtries = 10 | |
1581 | bp = int(opts.get('b',[1])[0]) |
|
1572 | bp = int(opts.get('b',[1])[0]) | |
1582 | checkline = deb.checkline(filename,bp) |
|
1573 | checkline = deb.checkline(filename,bp) | |
1583 | if not checkline: |
|
1574 | if not checkline: | |
1584 | for bp in range(bp+1,bp+maxtries+1): |
|
1575 | for bp in range(bp+1,bp+maxtries+1): | |
1585 | if deb.checkline(filename,bp): |
|
1576 | if deb.checkline(filename,bp): | |
1586 | break |
|
1577 | break | |
1587 | else: |
|
1578 | else: | |
1588 | msg = ("\nI failed to find a valid line to set " |
|
1579 | msg = ("\nI failed to find a valid line to set " | |
1589 | "a breakpoint\n" |
|
1580 | "a breakpoint\n" | |
1590 | "after trying up to line: %s.\n" |
|
1581 | "after trying up to line: %s.\n" | |
1591 | "Please set a valid breakpoint manually " |
|
1582 | "Please set a valid breakpoint manually " | |
1592 | "with the -b option." % bp) |
|
1583 | "with the -b option." % bp) | |
1593 | error(msg) |
|
1584 | error(msg) | |
1594 | return |
|
1585 | return | |
1595 | # if we find a good linenumber, set the breakpoint |
|
1586 | # if we find a good linenumber, set the breakpoint | |
1596 | deb.do_break('%s:%s' % (filename,bp)) |
|
1587 | deb.do_break('%s:%s' % (filename,bp)) | |
1597 | # Start file run |
|
1588 | # Start file run | |
1598 | print "NOTE: Enter 'c' at the", |
|
1589 | print "NOTE: Enter 'c' at the", | |
1599 | print "%s prompt to start your script." % deb.prompt |
|
1590 | print "%s prompt to start your script." % deb.prompt | |
1600 | try: |
|
1591 | try: | |
1601 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1592 | deb.run('execfile("%s")' % filename,prog_ns) | |
1602 |
|
1593 | |||
1603 | except: |
|
1594 | except: | |
1604 | etype, value, tb = sys.exc_info() |
|
1595 | etype, value, tb = sys.exc_info() | |
1605 | # Skip three frames in the traceback: the %run one, |
|
1596 | # Skip three frames in the traceback: the %run one, | |
1606 | # one inside bdb.py, and the command-line typed by the |
|
1597 | # one inside bdb.py, and the command-line typed by the | |
1607 | # user (run by exec in pdb itself). |
|
1598 | # user (run by exec in pdb itself). | |
1608 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1599 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1609 | else: |
|
1600 | else: | |
1610 | if runner is None: |
|
1601 | if runner is None: | |
1611 | runner = self.shell.safe_execfile |
|
1602 | runner = self.shell.safe_execfile | |
1612 | if opts.has_key('t'): |
|
1603 | if opts.has_key('t'): | |
1613 | # timed execution |
|
1604 | # timed execution | |
1614 | try: |
|
1605 | try: | |
1615 | nruns = int(opts['N'][0]) |
|
1606 | nruns = int(opts['N'][0]) | |
1616 | if nruns < 1: |
|
1607 | if nruns < 1: | |
1617 | error('Number of runs must be >=1') |
|
1608 | error('Number of runs must be >=1') | |
1618 | return |
|
1609 | return | |
1619 | except (KeyError): |
|
1610 | except (KeyError): | |
1620 | nruns = 1 |
|
1611 | nruns = 1 | |
1621 | if nruns == 1: |
|
1612 | if nruns == 1: | |
1622 | t0 = clock2() |
|
1613 | t0 = clock2() | |
1623 | runner(filename,prog_ns,prog_ns, |
|
1614 | runner(filename,prog_ns,prog_ns, | |
1624 | exit_ignore=exit_ignore) |
|
1615 | exit_ignore=exit_ignore) | |
1625 | t1 = clock2() |
|
1616 | t1 = clock2() | |
1626 | t_usr = t1[0]-t0[0] |
|
1617 | t_usr = t1[0]-t0[0] | |
1627 | t_sys = t1[1]-t0[1] |
|
1618 | t_sys = t1[1]-t0[1] | |
1628 | print "\nIPython CPU timings (estimated):" |
|
1619 | print "\nIPython CPU timings (estimated):" | |
1629 | print " User : %10s s." % t_usr |
|
1620 | print " User : %10s s." % t_usr | |
1630 | print " System: %10s s." % t_sys |
|
1621 | print " System: %10s s." % t_sys | |
1631 | else: |
|
1622 | else: | |
1632 | runs = range(nruns) |
|
1623 | runs = range(nruns) | |
1633 | t0 = clock2() |
|
1624 | t0 = clock2() | |
1634 | for nr in runs: |
|
1625 | for nr in runs: | |
1635 | runner(filename,prog_ns,prog_ns, |
|
1626 | runner(filename,prog_ns,prog_ns, | |
1636 | exit_ignore=exit_ignore) |
|
1627 | exit_ignore=exit_ignore) | |
1637 | t1 = clock2() |
|
1628 | t1 = clock2() | |
1638 | t_usr = t1[0]-t0[0] |
|
1629 | t_usr = t1[0]-t0[0] | |
1639 | t_sys = t1[1]-t0[1] |
|
1630 | t_sys = t1[1]-t0[1] | |
1640 | print "\nIPython CPU timings (estimated):" |
|
1631 | print "\nIPython CPU timings (estimated):" | |
1641 | print "Total runs performed:",nruns |
|
1632 | print "Total runs performed:",nruns | |
1642 | print " Times : %10s %10s" % ('Total','Per run') |
|
1633 | print " Times : %10s %10s" % ('Total','Per run') | |
1643 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1634 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1644 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1635 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1645 |
|
1636 | |||
1646 | else: |
|
1637 | else: | |
1647 | # regular execution |
|
1638 | # regular execution | |
1648 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1639 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1649 |
|
1640 | |||
1650 | if opts.has_key('i'): |
|
1641 | if opts.has_key('i'): | |
1651 | self.shell.user_ns['__name__'] = __name__save |
|
1642 | self.shell.user_ns['__name__'] = __name__save | |
1652 | else: |
|
1643 | else: | |
1653 | # The shell MUST hold a reference to prog_ns so after %run |
|
1644 | # The shell MUST hold a reference to prog_ns so after %run | |
1654 | # exits, the python deletion mechanism doesn't zero it out |
|
1645 | # exits, the python deletion mechanism doesn't zero it out | |
1655 | # (leaving dangling references). |
|
1646 | # (leaving dangling references). | |
1656 | self.shell.cache_main_mod(prog_ns,filename) |
|
1647 | self.shell.cache_main_mod(prog_ns,filename) | |
1657 | # update IPython interactive namespace |
|
1648 | # update IPython interactive namespace | |
1658 |
|
1649 | |||
1659 | # Some forms of read errors on the file may mean the |
|
1650 | # Some forms of read errors on the file may mean the | |
1660 | # __name__ key was never set; using pop we don't have to |
|
1651 | # __name__ key was never set; using pop we don't have to | |
1661 | # worry about a possible KeyError. |
|
1652 | # worry about a possible KeyError. | |
1662 | prog_ns.pop('__name__', None) |
|
1653 | prog_ns.pop('__name__', None) | |
1663 |
|
1654 | |||
1664 | self.shell.user_ns.update(prog_ns) |
|
1655 | self.shell.user_ns.update(prog_ns) | |
1665 | finally: |
|
1656 | finally: | |
1666 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1657 | # It's a bit of a mystery why, but __builtins__ can change from | |
1667 | # being a module to becoming a dict missing some key data after |
|
1658 | # being a module to becoming a dict missing some key data after | |
1668 | # %run. As best I can see, this is NOT something IPython is doing |
|
1659 | # %run. As best I can see, this is NOT something IPython is doing | |
1669 | # at all, and similar problems have been reported before: |
|
1660 | # at all, and similar problems have been reported before: | |
1670 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1661 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1671 | # Since this seems to be done by the interpreter itself, the best |
|
1662 | # Since this seems to be done by the interpreter itself, the best | |
1672 | # we can do is to at least restore __builtins__ for the user on |
|
1663 | # we can do is to at least restore __builtins__ for the user on | |
1673 | # exit. |
|
1664 | # exit. | |
1674 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1665 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1675 |
|
1666 | |||
1676 | # Ensure key global structures are restored |
|
1667 | # Ensure key global structures are restored | |
1677 | sys.argv = save_argv |
|
1668 | sys.argv = save_argv | |
1678 | if restore_main: |
|
1669 | if restore_main: | |
1679 | sys.modules['__main__'] = restore_main |
|
1670 | sys.modules['__main__'] = restore_main | |
1680 | else: |
|
1671 | else: | |
1681 | # Remove from sys.modules the reference to main_mod we'd |
|
1672 | # Remove from sys.modules the reference to main_mod we'd | |
1682 | # added. Otherwise it will trap references to objects |
|
1673 | # added. Otherwise it will trap references to objects | |
1683 | # contained therein. |
|
1674 | # contained therein. | |
1684 | del sys.modules[main_mod_name] |
|
1675 | del sys.modules[main_mod_name] | |
1685 |
|
1676 | |||
1686 | self.shell.reloadhist() |
|
1677 | self.shell.reloadhist() | |
1687 |
|
1678 | |||
1688 | return stats |
|
1679 | return stats | |
1689 |
|
1680 | |||
1690 | @testdec.skip_doctest |
|
1681 | @testdec.skip_doctest | |
1691 | def magic_timeit(self, parameter_s =''): |
|
1682 | def magic_timeit(self, parameter_s =''): | |
1692 | """Time execution of a Python statement or expression |
|
1683 | """Time execution of a Python statement or expression | |
1693 |
|
1684 | |||
1694 | Usage:\\ |
|
1685 | Usage:\\ | |
1695 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1686 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1696 |
|
1687 | |||
1697 | Time execution of a Python statement or expression using the timeit |
|
1688 | Time execution of a Python statement or expression using the timeit | |
1698 | module. |
|
1689 | module. | |
1699 |
|
1690 | |||
1700 | Options: |
|
1691 | Options: | |
1701 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1692 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1702 | is not given, a fitting value is chosen. |
|
1693 | is not given, a fitting value is chosen. | |
1703 |
|
1694 | |||
1704 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1695 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1705 | Default: 3 |
|
1696 | Default: 3 | |
1706 |
|
1697 | |||
1707 | -t: use time.time to measure the time, which is the default on Unix. |
|
1698 | -t: use time.time to measure the time, which is the default on Unix. | |
1708 | This function measures wall time. |
|
1699 | This function measures wall time. | |
1709 |
|
1700 | |||
1710 | -c: use time.clock to measure the time, which is the default on |
|
1701 | -c: use time.clock to measure the time, which is the default on | |
1711 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1702 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1712 | instead and returns the CPU user time. |
|
1703 | instead and returns the CPU user time. | |
1713 |
|
1704 | |||
1714 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1705 | -p<P>: use a precision of <P> digits to display the timing result. | |
1715 | Default: 3 |
|
1706 | Default: 3 | |
1716 |
|
1707 | |||
1717 |
|
1708 | |||
1718 | Examples: |
|
1709 | Examples: | |
1719 |
|
1710 | |||
1720 | In [1]: %timeit pass |
|
1711 | In [1]: %timeit pass | |
1721 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1712 | 10000000 loops, best of 3: 53.3 ns per loop | |
1722 |
|
1713 | |||
1723 | In [2]: u = None |
|
1714 | In [2]: u = None | |
1724 |
|
1715 | |||
1725 | In [3]: %timeit u is None |
|
1716 | In [3]: %timeit u is None | |
1726 | 10000000 loops, best of 3: 184 ns per loop |
|
1717 | 10000000 loops, best of 3: 184 ns per loop | |
1727 |
|
1718 | |||
1728 | In [4]: %timeit -r 4 u == None |
|
1719 | In [4]: %timeit -r 4 u == None | |
1729 | 1000000 loops, best of 4: 242 ns per loop |
|
1720 | 1000000 loops, best of 4: 242 ns per loop | |
1730 |
|
1721 | |||
1731 | In [5]: import time |
|
1722 | In [5]: import time | |
1732 |
|
1723 | |||
1733 | In [6]: %timeit -n1 time.sleep(2) |
|
1724 | In [6]: %timeit -n1 time.sleep(2) | |
1734 | 1 loops, best of 3: 2 s per loop |
|
1725 | 1 loops, best of 3: 2 s per loop | |
1735 |
|
1726 | |||
1736 |
|
1727 | |||
1737 | The times reported by %timeit will be slightly higher than those |
|
1728 | The times reported by %timeit will be slightly higher than those | |
1738 | reported by the timeit.py script when variables are accessed. This is |
|
1729 | reported by the timeit.py script when variables are accessed. This is | |
1739 | due to the fact that %timeit executes the statement in the namespace |
|
1730 | due to the fact that %timeit executes the statement in the namespace | |
1740 | of the shell, compared with timeit.py, which uses a single setup |
|
1731 | of the shell, compared with timeit.py, which uses a single setup | |
1741 | statement to import function or create variables. Generally, the bias |
|
1732 | statement to import function or create variables. Generally, the bias | |
1742 | does not matter as long as results from timeit.py are not mixed with |
|
1733 | does not matter as long as results from timeit.py are not mixed with | |
1743 | those from %timeit.""" |
|
1734 | those from %timeit.""" | |
1744 |
|
1735 | |||
1745 | import timeit |
|
1736 | import timeit | |
1746 | import math |
|
1737 | import math | |
1747 |
|
1738 | |||
1748 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1739 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1749 | # certain terminals. Until we figure out a robust way of |
|
1740 | # certain terminals. Until we figure out a robust way of | |
1750 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1741 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1751 | # microseconds. I am really NOT happy about disabling the proper |
|
1742 | # microseconds. I am really NOT happy about disabling the proper | |
1752 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1743 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1753 | # right solution for this is, I'm all ears... |
|
1744 | # right solution for this is, I'm all ears... | |
1754 | # |
|
1745 | # | |
1755 | # Note: using |
|
1746 | # Note: using | |
1756 | # |
|
1747 | # | |
1757 | # s = u'\xb5' |
|
1748 | # s = u'\xb5' | |
1758 | # s.encode(sys.getdefaultencoding()) |
|
1749 | # s.encode(sys.getdefaultencoding()) | |
1759 | # |
|
1750 | # | |
1760 | # is not sufficient, as I've seen terminals where that fails but |
|
1751 | # is not sufficient, as I've seen terminals where that fails but | |
1761 | # print s |
|
1752 | # print s | |
1762 | # |
|
1753 | # | |
1763 | # succeeds |
|
1754 | # succeeds | |
1764 | # |
|
1755 | # | |
1765 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1756 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1766 |
|
1757 | |||
1767 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1758 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1768 | units = [u"s", u"ms",u'us',"ns"] |
|
1759 | units = [u"s", u"ms",u'us',"ns"] | |
1769 |
|
1760 | |||
1770 | scaling = [1, 1e3, 1e6, 1e9] |
|
1761 | scaling = [1, 1e3, 1e6, 1e9] | |
1771 |
|
1762 | |||
1772 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1763 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1773 | posix=False) |
|
1764 | posix=False) | |
1774 | if stmt == "": |
|
1765 | if stmt == "": | |
1775 | return |
|
1766 | return | |
1776 | timefunc = timeit.default_timer |
|
1767 | timefunc = timeit.default_timer | |
1777 | number = int(getattr(opts, "n", 0)) |
|
1768 | number = int(getattr(opts, "n", 0)) | |
1778 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1769 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1779 | precision = int(getattr(opts, "p", 3)) |
|
1770 | precision = int(getattr(opts, "p", 3)) | |
1780 | if hasattr(opts, "t"): |
|
1771 | if hasattr(opts, "t"): | |
1781 | timefunc = time.time |
|
1772 | timefunc = time.time | |
1782 | if hasattr(opts, "c"): |
|
1773 | if hasattr(opts, "c"): | |
1783 | timefunc = clock |
|
1774 | timefunc = clock | |
1784 |
|
1775 | |||
1785 | timer = timeit.Timer(timer=timefunc) |
|
1776 | timer = timeit.Timer(timer=timefunc) | |
1786 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1777 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1787 | # but is there a better way to achieve that the code stmt has access |
|
1778 | # but is there a better way to achieve that the code stmt has access | |
1788 | # to the shell namespace? |
|
1779 | # to the shell namespace? | |
1789 |
|
1780 | |||
1790 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1781 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1791 | 'setup': "pass"} |
|
1782 | 'setup': "pass"} | |
1792 | # Track compilation time so it can be reported if too long |
|
1783 | # Track compilation time so it can be reported if too long | |
1793 | # Minimum time above which compilation time will be reported |
|
1784 | # Minimum time above which compilation time will be reported | |
1794 | tc_min = 0.1 |
|
1785 | tc_min = 0.1 | |
1795 |
|
1786 | |||
1796 | t0 = clock() |
|
1787 | t0 = clock() | |
1797 | code = compile(src, "<magic-timeit>", "exec") |
|
1788 | code = compile(src, "<magic-timeit>", "exec") | |
1798 | tc = clock()-t0 |
|
1789 | tc = clock()-t0 | |
1799 |
|
1790 | |||
1800 | ns = {} |
|
1791 | ns = {} | |
1801 | exec code in self.shell.user_ns, ns |
|
1792 | exec code in self.shell.user_ns, ns | |
1802 | timer.inner = ns["inner"] |
|
1793 | timer.inner = ns["inner"] | |
1803 |
|
1794 | |||
1804 | if number == 0: |
|
1795 | if number == 0: | |
1805 | # determine number so that 0.2 <= total time < 2.0 |
|
1796 | # determine number so that 0.2 <= total time < 2.0 | |
1806 | number = 1 |
|
1797 | number = 1 | |
1807 | for i in range(1, 10): |
|
1798 | for i in range(1, 10): | |
1808 | if timer.timeit(number) >= 0.2: |
|
1799 | if timer.timeit(number) >= 0.2: | |
1809 | break |
|
1800 | break | |
1810 | number *= 10 |
|
1801 | number *= 10 | |
1811 |
|
1802 | |||
1812 | best = min(timer.repeat(repeat, number)) / number |
|
1803 | best = min(timer.repeat(repeat, number)) / number | |
1813 |
|
1804 | |||
1814 | if best > 0.0 and best < 1000.0: |
|
1805 | if best > 0.0 and best < 1000.0: | |
1815 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1806 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1816 | elif best >= 1000.0: |
|
1807 | elif best >= 1000.0: | |
1817 | order = 0 |
|
1808 | order = 0 | |
1818 | else: |
|
1809 | else: | |
1819 | order = 3 |
|
1810 | order = 3 | |
1820 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1811 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1821 | precision, |
|
1812 | precision, | |
1822 | best * scaling[order], |
|
1813 | best * scaling[order], | |
1823 | units[order]) |
|
1814 | units[order]) | |
1824 | if tc > tc_min: |
|
1815 | if tc > tc_min: | |
1825 | print "Compiler time: %.2f s" % tc |
|
1816 | print "Compiler time: %.2f s" % tc | |
1826 |
|
1817 | |||
1827 | @testdec.skip_doctest |
|
1818 | @testdec.skip_doctest | |
1828 | def magic_time(self,parameter_s = ''): |
|
1819 | def magic_time(self,parameter_s = ''): | |
1829 | """Time execution of a Python statement or expression. |
|
1820 | """Time execution of a Python statement or expression. | |
1830 |
|
1821 | |||
1831 | The CPU and wall clock times are printed, and the value of the |
|
1822 | The CPU and wall clock times are printed, and the value of the | |
1832 | expression (if any) is returned. Note that under Win32, system time |
|
1823 | expression (if any) is returned. Note that under Win32, system time | |
1833 | is always reported as 0, since it can not be measured. |
|
1824 | is always reported as 0, since it can not be measured. | |
1834 |
|
1825 | |||
1835 | This function provides very basic timing functionality. In Python |
|
1826 | This function provides very basic timing functionality. In Python | |
1836 | 2.3, the timeit module offers more control and sophistication, so this |
|
1827 | 2.3, the timeit module offers more control and sophistication, so this | |
1837 | could be rewritten to use it (patches welcome). |
|
1828 | could be rewritten to use it (patches welcome). | |
1838 |
|
1829 | |||
1839 | Some examples: |
|
1830 | Some examples: | |
1840 |
|
1831 | |||
1841 | In [1]: time 2**128 |
|
1832 | In [1]: time 2**128 | |
1842 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1833 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1843 | Wall time: 0.00 |
|
1834 | Wall time: 0.00 | |
1844 | Out[1]: 340282366920938463463374607431768211456L |
|
1835 | Out[1]: 340282366920938463463374607431768211456L | |
1845 |
|
1836 | |||
1846 | In [2]: n = 1000000 |
|
1837 | In [2]: n = 1000000 | |
1847 |
|
1838 | |||
1848 | In [3]: time sum(range(n)) |
|
1839 | In [3]: time sum(range(n)) | |
1849 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1840 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1850 | Wall time: 1.37 |
|
1841 | Wall time: 1.37 | |
1851 | Out[3]: 499999500000L |
|
1842 | Out[3]: 499999500000L | |
1852 |
|
1843 | |||
1853 | In [4]: time print 'hello world' |
|
1844 | In [4]: time print 'hello world' | |
1854 | hello world |
|
1845 | hello world | |
1855 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1846 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1856 | Wall time: 0.00 |
|
1847 | Wall time: 0.00 | |
1857 |
|
1848 | |||
1858 | Note that the time needed by Python to compile the given expression |
|
1849 | Note that the time needed by Python to compile the given expression | |
1859 | will be reported if it is more than 0.1s. In this example, the |
|
1850 | will be reported if it is more than 0.1s. In this example, the | |
1860 | actual exponentiation is done by Python at compilation time, so while |
|
1851 | actual exponentiation is done by Python at compilation time, so while | |
1861 | the expression can take a noticeable amount of time to compute, that |
|
1852 | the expression can take a noticeable amount of time to compute, that | |
1862 | time is purely due to the compilation: |
|
1853 | time is purely due to the compilation: | |
1863 |
|
1854 | |||
1864 | In [5]: time 3**9999; |
|
1855 | In [5]: time 3**9999; | |
1865 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1856 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1866 | Wall time: 0.00 s |
|
1857 | Wall time: 0.00 s | |
1867 |
|
1858 | |||
1868 | In [6]: time 3**999999; |
|
1859 | In [6]: time 3**999999; | |
1869 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1860 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1870 | Wall time: 0.00 s |
|
1861 | Wall time: 0.00 s | |
1871 | Compiler : 0.78 s |
|
1862 | Compiler : 0.78 s | |
1872 | """ |
|
1863 | """ | |
1873 |
|
1864 | |||
1874 | # fail immediately if the given expression can't be compiled |
|
1865 | # fail immediately if the given expression can't be compiled | |
1875 |
|
1866 | |||
1876 | expr = self.shell.prefilter(parameter_s,False) |
|
1867 | expr = self.shell.prefilter(parameter_s,False) | |
1877 |
|
1868 | |||
1878 | # Minimum time above which compilation time will be reported |
|
1869 | # Minimum time above which compilation time will be reported | |
1879 | tc_min = 0.1 |
|
1870 | tc_min = 0.1 | |
1880 |
|
1871 | |||
1881 | try: |
|
1872 | try: | |
1882 | mode = 'eval' |
|
1873 | mode = 'eval' | |
1883 | t0 = clock() |
|
1874 | t0 = clock() | |
1884 | code = compile(expr,'<timed eval>',mode) |
|
1875 | code = compile(expr,'<timed eval>',mode) | |
1885 | tc = clock()-t0 |
|
1876 | tc = clock()-t0 | |
1886 | except SyntaxError: |
|
1877 | except SyntaxError: | |
1887 | mode = 'exec' |
|
1878 | mode = 'exec' | |
1888 | t0 = clock() |
|
1879 | t0 = clock() | |
1889 | code = compile(expr,'<timed exec>',mode) |
|
1880 | code = compile(expr,'<timed exec>',mode) | |
1890 | tc = clock()-t0 |
|
1881 | tc = clock()-t0 | |
1891 | # skew measurement as little as possible |
|
1882 | # skew measurement as little as possible | |
1892 | glob = self.shell.user_ns |
|
1883 | glob = self.shell.user_ns | |
1893 | clk = clock2 |
|
1884 | clk = clock2 | |
1894 | wtime = time.time |
|
1885 | wtime = time.time | |
1895 | # time execution |
|
1886 | # time execution | |
1896 | wall_st = wtime() |
|
1887 | wall_st = wtime() | |
1897 | if mode=='eval': |
|
1888 | if mode=='eval': | |
1898 | st = clk() |
|
1889 | st = clk() | |
1899 | out = eval(code,glob) |
|
1890 | out = eval(code,glob) | |
1900 | end = clk() |
|
1891 | end = clk() | |
1901 | else: |
|
1892 | else: | |
1902 | st = clk() |
|
1893 | st = clk() | |
1903 | exec code in glob |
|
1894 | exec code in glob | |
1904 | end = clk() |
|
1895 | end = clk() | |
1905 | out = None |
|
1896 | out = None | |
1906 | wall_end = wtime() |
|
1897 | wall_end = wtime() | |
1907 | # Compute actual times and report |
|
1898 | # Compute actual times and report | |
1908 | wall_time = wall_end-wall_st |
|
1899 | wall_time = wall_end-wall_st | |
1909 | cpu_user = end[0]-st[0] |
|
1900 | cpu_user = end[0]-st[0] | |
1910 | cpu_sys = end[1]-st[1] |
|
1901 | cpu_sys = end[1]-st[1] | |
1911 | cpu_tot = cpu_user+cpu_sys |
|
1902 | cpu_tot = cpu_user+cpu_sys | |
1912 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1903 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1913 | (cpu_user,cpu_sys,cpu_tot) |
|
1904 | (cpu_user,cpu_sys,cpu_tot) | |
1914 | print "Wall time: %.2f s" % wall_time |
|
1905 | print "Wall time: %.2f s" % wall_time | |
1915 | if tc > tc_min: |
|
1906 | if tc > tc_min: | |
1916 | print "Compiler : %.2f s" % tc |
|
1907 | print "Compiler : %.2f s" % tc | |
1917 | return out |
|
1908 | return out | |
1918 |
|
1909 | |||
1919 | @testdec.skip_doctest |
|
1910 | @testdec.skip_doctest | |
1920 | def magic_macro(self,parameter_s = ''): |
|
1911 | def magic_macro(self,parameter_s = ''): | |
1921 | """Define a set of input lines as a macro for future re-execution. |
|
1912 | """Define a set of input lines as a macro for future re-execution. | |
1922 |
|
1913 | |||
1923 | Usage:\\ |
|
1914 | Usage:\\ | |
1924 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1915 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1925 |
|
1916 | |||
1926 | Options: |
|
1917 | Options: | |
1927 |
|
1918 | |||
1928 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1919 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1929 | so that magics are loaded in their transformed version to valid |
|
1920 | so that magics are loaded in their transformed version to valid | |
1930 | Python. If this option is given, the raw input as typed as the |
|
1921 | Python. If this option is given, the raw input as typed as the | |
1931 | command line is used instead. |
|
1922 | command line is used instead. | |
1932 |
|
1923 | |||
1933 | This will define a global variable called `name` which is a string |
|
1924 | This will define a global variable called `name` which is a string | |
1934 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1925 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1935 | above) from your input history into a single string. This variable |
|
1926 | above) from your input history into a single string. This variable | |
1936 | acts like an automatic function which re-executes those lines as if |
|
1927 | acts like an automatic function which re-executes those lines as if | |
1937 | you had typed them. You just type 'name' at the prompt and the code |
|
1928 | you had typed them. You just type 'name' at the prompt and the code | |
1938 | executes. |
|
1929 | executes. | |
1939 |
|
1930 | |||
1940 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1931 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1941 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1932 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1942 | using the lines numbered 5,6 and 7. |
|
1933 | using the lines numbered 5,6 and 7. | |
1943 |
|
1934 | |||
1944 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1935 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1945 | notation, where N:M means numbers N through M-1. |
|
1936 | notation, where N:M means numbers N through M-1. | |
1946 |
|
1937 | |||
1947 | For example, if your history contains (%hist prints it): |
|
1938 | For example, if your history contains (%hist prints it): | |
1948 |
|
1939 | |||
1949 | 44: x=1 |
|
1940 | 44: x=1 | |
1950 | 45: y=3 |
|
1941 | 45: y=3 | |
1951 | 46: z=x+y |
|
1942 | 46: z=x+y | |
1952 | 47: print x |
|
1943 | 47: print x | |
1953 | 48: a=5 |
|
1944 | 48: a=5 | |
1954 | 49: print 'x',x,'y',y |
|
1945 | 49: print 'x',x,'y',y | |
1955 |
|
1946 | |||
1956 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1947 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1957 | called my_macro with: |
|
1948 | called my_macro with: | |
1958 |
|
1949 | |||
1959 | In [55]: %macro my_macro 44-47 49 |
|
1950 | In [55]: %macro my_macro 44-47 49 | |
1960 |
|
1951 | |||
1961 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1952 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1962 | in one pass. |
|
1953 | in one pass. | |
1963 |
|
1954 | |||
1964 | You don't need to give the line-numbers in order, and any given line |
|
1955 | You don't need to give the line-numbers in order, and any given line | |
1965 | number can appear multiple times. You can assemble macros with any |
|
1956 | number can appear multiple times. You can assemble macros with any | |
1966 | lines from your input history in any order. |
|
1957 | lines from your input history in any order. | |
1967 |
|
1958 | |||
1968 | The macro is a simple object which holds its value in an attribute, |
|
1959 | The macro is a simple object which holds its value in an attribute, | |
1969 | but IPython's display system checks for macros and executes them as |
|
1960 | but IPython's display system checks for macros and executes them as | |
1970 | code instead of printing them when you type their name. |
|
1961 | code instead of printing them when you type their name. | |
1971 |
|
1962 | |||
1972 | You can view a macro's contents by explicitly printing it with: |
|
1963 | You can view a macro's contents by explicitly printing it with: | |
1973 |
|
1964 | |||
1974 | 'print macro_name'. |
|
1965 | 'print macro_name'. | |
1975 |
|
1966 | |||
1976 | For one-off cases which DON'T contain magic function calls in them you |
|
1967 | For one-off cases which DON'T contain magic function calls in them you | |
1977 | can obtain similar results by explicitly executing slices from your |
|
1968 | can obtain similar results by explicitly executing slices from your | |
1978 | input history with: |
|
1969 | input history with: | |
1979 |
|
1970 | |||
1980 | In [60]: exec In[44:48]+In[49]""" |
|
1971 | In [60]: exec In[44:48]+In[49]""" | |
1981 |
|
1972 | |||
1982 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1973 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1983 | if not args: |
|
1974 | if not args: | |
1984 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1975 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1985 | macs.sort() |
|
1976 | macs.sort() | |
1986 | return macs |
|
1977 | return macs | |
1987 | if len(args) == 1: |
|
1978 | if len(args) == 1: | |
1988 | raise UsageError( |
|
1979 | raise UsageError( | |
1989 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1980 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1990 | name,ranges = args[0], args[1:] |
|
1981 | name,ranges = args[0], args[1:] | |
1991 |
|
1982 | |||
1992 | #print 'rng',ranges # dbg |
|
1983 | #print 'rng',ranges # dbg | |
1993 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1984 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1994 | macro = Macro(lines) |
|
1985 | macro = Macro(lines) | |
1995 | self.shell.define_macro(name, macro) |
|
1986 | self.shell.define_macro(name, macro) | |
1996 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1987 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1997 | print 'Macro contents:' |
|
1988 | print 'Macro contents:' | |
1998 | print macro, |
|
1989 | print macro, | |
1999 |
|
1990 | |||
2000 | def magic_save(self,parameter_s = ''): |
|
1991 | def magic_save(self,parameter_s = ''): | |
2001 | """Save a set of lines to a given filename. |
|
1992 | """Save a set of lines to a given filename. | |
2002 |
|
1993 | |||
2003 | Usage:\\ |
|
1994 | Usage:\\ | |
2004 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1995 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2005 |
|
1996 | |||
2006 | Options: |
|
1997 | Options: | |
2007 |
|
1998 | |||
2008 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1999 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2009 | so that magics are loaded in their transformed version to valid |
|
2000 | so that magics are loaded in their transformed version to valid | |
2010 | Python. If this option is given, the raw input as typed as the |
|
2001 | Python. If this option is given, the raw input as typed as the | |
2011 | command line is used instead. |
|
2002 | command line is used instead. | |
2012 |
|
2003 | |||
2013 | This function uses the same syntax as %macro for line extraction, but |
|
2004 | This function uses the same syntax as %macro for line extraction, but | |
2014 | instead of creating a macro it saves the resulting string to the |
|
2005 | instead of creating a macro it saves the resulting string to the | |
2015 | filename you specify. |
|
2006 | filename you specify. | |
2016 |
|
2007 | |||
2017 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2008 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2018 | it asks for confirmation before overwriting existing files.""" |
|
2009 | it asks for confirmation before overwriting existing files.""" | |
2019 |
|
2010 | |||
2020 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2011 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2021 | fname,ranges = args[0], args[1:] |
|
2012 | fname,ranges = args[0], args[1:] | |
2022 | if not fname.endswith('.py'): |
|
2013 | if not fname.endswith('.py'): | |
2023 | fname += '.py' |
|
2014 | fname += '.py' | |
2024 | if os.path.isfile(fname): |
|
2015 | if os.path.isfile(fname): | |
2025 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2016 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2026 | if ans.lower() not in ['y','yes']: |
|
2017 | if ans.lower() not in ['y','yes']: | |
2027 | print 'Operation cancelled.' |
|
2018 | print 'Operation cancelled.' | |
2028 | return |
|
2019 | return | |
2029 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2020 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2030 | f = file(fname,'w') |
|
2021 | f = file(fname,'w') | |
2031 | f.write(cmds) |
|
2022 | f.write(cmds) | |
2032 | f.close() |
|
2023 | f.close() | |
2033 | print 'The following commands were written to file `%s`:' % fname |
|
2024 | print 'The following commands were written to file `%s`:' % fname | |
2034 | print cmds |
|
2025 | print cmds | |
2035 |
|
2026 | |||
2036 | def _edit_macro(self,mname,macro): |
|
2027 | def _edit_macro(self,mname,macro): | |
2037 | """open an editor with the macro data in a file""" |
|
2028 | """open an editor with the macro data in a file""" | |
2038 | filename = self.shell.mktempfile(macro.value) |
|
2029 | filename = self.shell.mktempfile(macro.value) | |
2039 | self.shell.hooks.editor(filename) |
|
2030 | self.shell.hooks.editor(filename) | |
2040 |
|
2031 | |||
2041 | # and make a new macro object, to replace the old one |
|
2032 | # and make a new macro object, to replace the old one | |
2042 | mfile = open(filename) |
|
2033 | mfile = open(filename) | |
2043 | mvalue = mfile.read() |
|
2034 | mvalue = mfile.read() | |
2044 | mfile.close() |
|
2035 | mfile.close() | |
2045 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2036 | self.shell.user_ns[mname] = Macro(mvalue) | |
2046 |
|
2037 | |||
2047 | def magic_ed(self,parameter_s=''): |
|
2038 | def magic_ed(self,parameter_s=''): | |
2048 | """Alias to %edit.""" |
|
2039 | """Alias to %edit.""" | |
2049 | return self.magic_edit(parameter_s) |
|
2040 | return self.magic_edit(parameter_s) | |
2050 |
|
2041 | |||
2051 | @testdec.skip_doctest |
|
2042 | @testdec.skip_doctest | |
2052 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2043 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2053 | """Bring up an editor and execute the resulting code. |
|
2044 | """Bring up an editor and execute the resulting code. | |
2054 |
|
2045 | |||
2055 | Usage: |
|
2046 | Usage: | |
2056 | %edit [options] [args] |
|
2047 | %edit [options] [args] | |
2057 |
|
2048 | |||
2058 | %edit runs IPython's editor hook. The default version of this hook is |
|
2049 | %edit runs IPython's editor hook. The default version of this hook is | |
2059 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2050 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2060 | environment variable $EDITOR. If this isn't found, it will default to |
|
2051 | environment variable $EDITOR. If this isn't found, it will default to | |
2061 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2052 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2062 | docstring for how to change the editor hook. |
|
2053 | docstring for how to change the editor hook. | |
2063 |
|
2054 | |||
2064 | You can also set the value of this editor via the command line option |
|
2055 | You can also set the value of this editor via the command line option | |
2065 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2056 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2066 | specifically for IPython an editor different from your typical default |
|
2057 | specifically for IPython an editor different from your typical default | |
2067 | (and for Windows users who typically don't set environment variables). |
|
2058 | (and for Windows users who typically don't set environment variables). | |
2068 |
|
2059 | |||
2069 | This command allows you to conveniently edit multi-line code right in |
|
2060 | This command allows you to conveniently edit multi-line code right in | |
2070 | your IPython session. |
|
2061 | your IPython session. | |
2071 |
|
2062 | |||
2072 | If called without arguments, %edit opens up an empty editor with a |
|
2063 | If called without arguments, %edit opens up an empty editor with a | |
2073 | temporary file and will execute the contents of this file when you |
|
2064 | temporary file and will execute the contents of this file when you | |
2074 | close it (don't forget to save it!). |
|
2065 | close it (don't forget to save it!). | |
2075 |
|
2066 | |||
2076 |
|
2067 | |||
2077 | Options: |
|
2068 | Options: | |
2078 |
|
2069 | |||
2079 | -n <number>: open the editor at a specified line number. By default, |
|
2070 | -n <number>: open the editor at a specified line number. By default, | |
2080 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2071 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2081 | you can configure this by providing your own modified hook if your |
|
2072 | you can configure this by providing your own modified hook if your | |
2082 | favorite editor supports line-number specifications with a different |
|
2073 | favorite editor supports line-number specifications with a different | |
2083 | syntax. |
|
2074 | syntax. | |
2084 |
|
2075 | |||
2085 | -p: this will call the editor with the same data as the previous time |
|
2076 | -p: this will call the editor with the same data as the previous time | |
2086 | it was used, regardless of how long ago (in your current session) it |
|
2077 | it was used, regardless of how long ago (in your current session) it | |
2087 | was. |
|
2078 | was. | |
2088 |
|
2079 | |||
2089 | -r: use 'raw' input. This option only applies to input taken from the |
|
2080 | -r: use 'raw' input. This option only applies to input taken from the | |
2090 | user's history. By default, the 'processed' history is used, so that |
|
2081 | user's history. By default, the 'processed' history is used, so that | |
2091 | magics are loaded in their transformed version to valid Python. If |
|
2082 | magics are loaded in their transformed version to valid Python. If | |
2092 | this option is given, the raw input as typed as the command line is |
|
2083 | this option is given, the raw input as typed as the command line is | |
2093 | used instead. When you exit the editor, it will be executed by |
|
2084 | used instead. When you exit the editor, it will be executed by | |
2094 | IPython's own processor. |
|
2085 | IPython's own processor. | |
2095 |
|
2086 | |||
2096 | -x: do not execute the edited code immediately upon exit. This is |
|
2087 | -x: do not execute the edited code immediately upon exit. This is | |
2097 | mainly useful if you are editing programs which need to be called with |
|
2088 | mainly useful if you are editing programs which need to be called with | |
2098 | command line arguments, which you can then do using %run. |
|
2089 | command line arguments, which you can then do using %run. | |
2099 |
|
2090 | |||
2100 |
|
2091 | |||
2101 | Arguments: |
|
2092 | Arguments: | |
2102 |
|
2093 | |||
2103 | If arguments are given, the following possibilites exist: |
|
2094 | If arguments are given, the following possibilites exist: | |
2104 |
|
2095 | |||
2105 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2096 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2106 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2097 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2107 | loaded into the editor. The syntax is the same of the %macro command. |
|
2098 | loaded into the editor. The syntax is the same of the %macro command. | |
2108 |
|
2099 | |||
2109 | - If the argument doesn't start with a number, it is evaluated as a |
|
2100 | - If the argument doesn't start with a number, it is evaluated as a | |
2110 | variable and its contents loaded into the editor. You can thus edit |
|
2101 | variable and its contents loaded into the editor. You can thus edit | |
2111 | any string which contains python code (including the result of |
|
2102 | any string which contains python code (including the result of | |
2112 | previous edits). |
|
2103 | previous edits). | |
2113 |
|
2104 | |||
2114 | - If the argument is the name of an object (other than a string), |
|
2105 | - If the argument is the name of an object (other than a string), | |
2115 | IPython will try to locate the file where it was defined and open the |
|
2106 | IPython will try to locate the file where it was defined and open the | |
2116 | editor at the point where it is defined. You can use `%edit function` |
|
2107 | editor at the point where it is defined. You can use `%edit function` | |
2117 | to load an editor exactly at the point where 'function' is defined, |
|
2108 | to load an editor exactly at the point where 'function' is defined, | |
2118 | edit it and have the file be executed automatically. |
|
2109 | edit it and have the file be executed automatically. | |
2119 |
|
2110 | |||
2120 | If the object is a macro (see %macro for details), this opens up your |
|
2111 | If the object is a macro (see %macro for details), this opens up your | |
2121 | specified editor with a temporary file containing the macro's data. |
|
2112 | specified editor with a temporary file containing the macro's data. | |
2122 | Upon exit, the macro is reloaded with the contents of the file. |
|
2113 | Upon exit, the macro is reloaded with the contents of the file. | |
2123 |
|
2114 | |||
2124 | Note: opening at an exact line is only supported under Unix, and some |
|
2115 | Note: opening at an exact line is only supported under Unix, and some | |
2125 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2116 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2126 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2117 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2127 | (X)Emacs, vi, jed, pico and joe all do. |
|
2118 | (X)Emacs, vi, jed, pico and joe all do. | |
2128 |
|
2119 | |||
2129 | - If the argument is not found as a variable, IPython will look for a |
|
2120 | - If the argument is not found as a variable, IPython will look for a | |
2130 | file with that name (adding .py if necessary) and load it into the |
|
2121 | file with that name (adding .py if necessary) and load it into the | |
2131 | editor. It will execute its contents with execfile() when you exit, |
|
2122 | editor. It will execute its contents with execfile() when you exit, | |
2132 | loading any code in the file into your interactive namespace. |
|
2123 | loading any code in the file into your interactive namespace. | |
2133 |
|
2124 | |||
2134 | After executing your code, %edit will return as output the code you |
|
2125 | After executing your code, %edit will return as output the code you | |
2135 | typed in the editor (except when it was an existing file). This way |
|
2126 | typed in the editor (except when it was an existing file). This way | |
2136 | you can reload the code in further invocations of %edit as a variable, |
|
2127 | you can reload the code in further invocations of %edit as a variable, | |
2137 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2128 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2138 | the output. |
|
2129 | the output. | |
2139 |
|
2130 | |||
2140 | Note that %edit is also available through the alias %ed. |
|
2131 | Note that %edit is also available through the alias %ed. | |
2141 |
|
2132 | |||
2142 | This is an example of creating a simple function inside the editor and |
|
2133 | This is an example of creating a simple function inside the editor and | |
2143 | then modifying it. First, start up the editor: |
|
2134 | then modifying it. First, start up the editor: | |
2144 |
|
2135 | |||
2145 | In [1]: ed |
|
2136 | In [1]: ed | |
2146 | Editing... done. Executing edited code... |
|
2137 | Editing... done. Executing edited code... | |
2147 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2138 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2148 |
|
2139 | |||
2149 | We can then call the function foo(): |
|
2140 | We can then call the function foo(): | |
2150 |
|
2141 | |||
2151 | In [2]: foo() |
|
2142 | In [2]: foo() | |
2152 | foo() was defined in an editing session |
|
2143 | foo() was defined in an editing session | |
2153 |
|
2144 | |||
2154 | Now we edit foo. IPython automatically loads the editor with the |
|
2145 | Now we edit foo. IPython automatically loads the editor with the | |
2155 | (temporary) file where foo() was previously defined: |
|
2146 | (temporary) file where foo() was previously defined: | |
2156 |
|
2147 | |||
2157 | In [3]: ed foo |
|
2148 | In [3]: ed foo | |
2158 | Editing... done. Executing edited code... |
|
2149 | Editing... done. Executing edited code... | |
2159 |
|
2150 | |||
2160 | And if we call foo() again we get the modified version: |
|
2151 | And if we call foo() again we get the modified version: | |
2161 |
|
2152 | |||
2162 | In [4]: foo() |
|
2153 | In [4]: foo() | |
2163 | foo() has now been changed! |
|
2154 | foo() has now been changed! | |
2164 |
|
2155 | |||
2165 | Here is an example of how to edit a code snippet successive |
|
2156 | Here is an example of how to edit a code snippet successive | |
2166 | times. First we call the editor: |
|
2157 | times. First we call the editor: | |
2167 |
|
2158 | |||
2168 | In [5]: ed |
|
2159 | In [5]: ed | |
2169 | Editing... done. Executing edited code... |
|
2160 | Editing... done. Executing edited code... | |
2170 | hello |
|
2161 | hello | |
2171 | Out[5]: "print 'hello'n" |
|
2162 | Out[5]: "print 'hello'n" | |
2172 |
|
2163 | |||
2173 | Now we call it again with the previous output (stored in _): |
|
2164 | Now we call it again with the previous output (stored in _): | |
2174 |
|
2165 | |||
2175 | In [6]: ed _ |
|
2166 | In [6]: ed _ | |
2176 | Editing... done. Executing edited code... |
|
2167 | Editing... done. Executing edited code... | |
2177 | hello world |
|
2168 | hello world | |
2178 | Out[6]: "print 'hello world'n" |
|
2169 | Out[6]: "print 'hello world'n" | |
2179 |
|
2170 | |||
2180 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2171 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2181 |
|
2172 | |||
2182 | In [7]: ed _8 |
|
2173 | In [7]: ed _8 | |
2183 | Editing... done. Executing edited code... |
|
2174 | Editing... done. Executing edited code... | |
2184 | hello again |
|
2175 | hello again | |
2185 | Out[7]: "print 'hello again'n" |
|
2176 | Out[7]: "print 'hello again'n" | |
2186 |
|
2177 | |||
2187 |
|
2178 | |||
2188 | Changing the default editor hook: |
|
2179 | Changing the default editor hook: | |
2189 |
|
2180 | |||
2190 | If you wish to write your own editor hook, you can put it in a |
|
2181 | If you wish to write your own editor hook, you can put it in a | |
2191 | configuration file which you load at startup time. The default hook |
|
2182 | configuration file which you load at startup time. The default hook | |
2192 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2183 | is defined in the IPython.core.hooks module, and you can use that as a | |
2193 | starting example for further modifications. That file also has |
|
2184 | starting example for further modifications. That file also has | |
2194 | general instructions on how to set a new hook for use once you've |
|
2185 | general instructions on how to set a new hook for use once you've | |
2195 | defined it.""" |
|
2186 | defined it.""" | |
2196 |
|
2187 | |||
2197 | # FIXME: This function has become a convoluted mess. It needs a |
|
2188 | # FIXME: This function has become a convoluted mess. It needs a | |
2198 | # ground-up rewrite with clean, simple logic. |
|
2189 | # ground-up rewrite with clean, simple logic. | |
2199 |
|
2190 | |||
2200 | def make_filename(arg): |
|
2191 | def make_filename(arg): | |
2201 | "Make a filename from the given args" |
|
2192 | "Make a filename from the given args" | |
2202 | try: |
|
2193 | try: | |
2203 | filename = get_py_filename(arg) |
|
2194 | filename = get_py_filename(arg) | |
2204 | except IOError: |
|
2195 | except IOError: | |
2205 | if args.endswith('.py'): |
|
2196 | if args.endswith('.py'): | |
2206 | filename = arg |
|
2197 | filename = arg | |
2207 | else: |
|
2198 | else: | |
2208 | filename = None |
|
2199 | filename = None | |
2209 | return filename |
|
2200 | return filename | |
2210 |
|
2201 | |||
2211 | # custom exceptions |
|
2202 | # custom exceptions | |
2212 | class DataIsObject(Exception): pass |
|
2203 | class DataIsObject(Exception): pass | |
2213 |
|
2204 | |||
2214 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2205 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2215 | # Set a few locals from the options for convenience: |
|
2206 | # Set a few locals from the options for convenience: | |
2216 | opts_p = opts.has_key('p') |
|
2207 | opts_p = opts.has_key('p') | |
2217 | opts_r = opts.has_key('r') |
|
2208 | opts_r = opts.has_key('r') | |
2218 |
|
2209 | |||
2219 | # Default line number value |
|
2210 | # Default line number value | |
2220 | lineno = opts.get('n',None) |
|
2211 | lineno = opts.get('n',None) | |
2221 |
|
2212 | |||
2222 | if opts_p: |
|
2213 | if opts_p: | |
2223 | args = '_%s' % last_call[0] |
|
2214 | args = '_%s' % last_call[0] | |
2224 | if not self.shell.user_ns.has_key(args): |
|
2215 | if not self.shell.user_ns.has_key(args): | |
2225 | args = last_call[1] |
|
2216 | args = last_call[1] | |
2226 |
|
2217 | |||
2227 | # use last_call to remember the state of the previous call, but don't |
|
2218 | # use last_call to remember the state of the previous call, but don't | |
2228 | # let it be clobbered by successive '-p' calls. |
|
2219 | # let it be clobbered by successive '-p' calls. | |
2229 | try: |
|
2220 | try: | |
2230 | last_call[0] = self.shell.displayhook.prompt_count |
|
2221 | last_call[0] = self.shell.displayhook.prompt_count | |
2231 | if not opts_p: |
|
2222 | if not opts_p: | |
2232 | last_call[1] = parameter_s |
|
2223 | last_call[1] = parameter_s | |
2233 | except: |
|
2224 | except: | |
2234 | pass |
|
2225 | pass | |
2235 |
|
2226 | |||
2236 | # by default this is done with temp files, except when the given |
|
2227 | # by default this is done with temp files, except when the given | |
2237 | # arg is a filename |
|
2228 | # arg is a filename | |
2238 | use_temp = 1 |
|
2229 | use_temp = 1 | |
2239 |
|
2230 | |||
2240 | if re.match(r'\d',args): |
|
2231 | if re.match(r'\d',args): | |
2241 | # Mode where user specifies ranges of lines, like in %macro. |
|
2232 | # Mode where user specifies ranges of lines, like in %macro. | |
2242 | # This means that you can't edit files whose names begin with |
|
2233 | # This means that you can't edit files whose names begin with | |
2243 | # numbers this way. Tough. |
|
2234 | # numbers this way. Tough. | |
2244 | ranges = args.split() |
|
2235 | ranges = args.split() | |
2245 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2236 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2246 | elif args.endswith('.py'): |
|
2237 | elif args.endswith('.py'): | |
2247 | filename = make_filename(args) |
|
2238 | filename = make_filename(args) | |
2248 | data = '' |
|
2239 | data = '' | |
2249 | use_temp = 0 |
|
2240 | use_temp = 0 | |
2250 | elif args: |
|
2241 | elif args: | |
2251 | try: |
|
2242 | try: | |
2252 | # Load the parameter given as a variable. If not a string, |
|
2243 | # Load the parameter given as a variable. If not a string, | |
2253 | # process it as an object instead (below) |
|
2244 | # process it as an object instead (below) | |
2254 |
|
2245 | |||
2255 | #print '*** args',args,'type',type(args) # dbg |
|
2246 | #print '*** args',args,'type',type(args) # dbg | |
2256 | data = eval(args,self.shell.user_ns) |
|
2247 | data = eval(args,self.shell.user_ns) | |
2257 | if not type(data) in StringTypes: |
|
2248 | if not type(data) in StringTypes: | |
2258 | raise DataIsObject |
|
2249 | raise DataIsObject | |
2259 |
|
2250 | |||
2260 | except (NameError,SyntaxError): |
|
2251 | except (NameError,SyntaxError): | |
2261 | # given argument is not a variable, try as a filename |
|
2252 | # given argument is not a variable, try as a filename | |
2262 | filename = make_filename(args) |
|
2253 | filename = make_filename(args) | |
2263 | if filename is None: |
|
2254 | if filename is None: | |
2264 | warn("Argument given (%s) can't be found as a variable " |
|
2255 | warn("Argument given (%s) can't be found as a variable " | |
2265 | "or as a filename." % args) |
|
2256 | "or as a filename." % args) | |
2266 | return |
|
2257 | return | |
2267 |
|
2258 | |||
2268 | data = '' |
|
2259 | data = '' | |
2269 | use_temp = 0 |
|
2260 | use_temp = 0 | |
2270 | except DataIsObject: |
|
2261 | except DataIsObject: | |
2271 |
|
2262 | |||
2272 | # macros have a special edit function |
|
2263 | # macros have a special edit function | |
2273 | if isinstance(data,Macro): |
|
2264 | if isinstance(data,Macro): | |
2274 | self._edit_macro(args,data) |
|
2265 | self._edit_macro(args,data) | |
2275 | return |
|
2266 | return | |
2276 |
|
2267 | |||
2277 | # For objects, try to edit the file where they are defined |
|
2268 | # For objects, try to edit the file where they are defined | |
2278 | try: |
|
2269 | try: | |
2279 | filename = inspect.getabsfile(data) |
|
2270 | filename = inspect.getabsfile(data) | |
2280 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2271 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2281 | # class created by %edit? Try to find source |
|
2272 | # class created by %edit? Try to find source | |
2282 | # by looking for method definitions instead, the |
|
2273 | # by looking for method definitions instead, the | |
2283 | # __module__ in those classes is FakeModule. |
|
2274 | # __module__ in those classes is FakeModule. | |
2284 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2275 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2285 | for attr in attrs: |
|
2276 | for attr in attrs: | |
2286 | if not inspect.ismethod(attr): |
|
2277 | if not inspect.ismethod(attr): | |
2287 | continue |
|
2278 | continue | |
2288 | filename = inspect.getabsfile(attr) |
|
2279 | filename = inspect.getabsfile(attr) | |
2289 | if filename and 'fakemodule' not in filename.lower(): |
|
2280 | if filename and 'fakemodule' not in filename.lower(): | |
2290 | # change the attribute to be the edit target instead |
|
2281 | # change the attribute to be the edit target instead | |
2291 | data = attr |
|
2282 | data = attr | |
2292 | break |
|
2283 | break | |
2293 |
|
2284 | |||
2294 | datafile = 1 |
|
2285 | datafile = 1 | |
2295 | except TypeError: |
|
2286 | except TypeError: | |
2296 | filename = make_filename(args) |
|
2287 | filename = make_filename(args) | |
2297 | datafile = 1 |
|
2288 | datafile = 1 | |
2298 | warn('Could not find file where `%s` is defined.\n' |
|
2289 | warn('Could not find file where `%s` is defined.\n' | |
2299 | 'Opening a file named `%s`' % (args,filename)) |
|
2290 | 'Opening a file named `%s`' % (args,filename)) | |
2300 | # Now, make sure we can actually read the source (if it was in |
|
2291 | # Now, make sure we can actually read the source (if it was in | |
2301 | # a temp file it's gone by now). |
|
2292 | # a temp file it's gone by now). | |
2302 | if datafile: |
|
2293 | if datafile: | |
2303 | try: |
|
2294 | try: | |
2304 | if lineno is None: |
|
2295 | if lineno is None: | |
2305 | lineno = inspect.getsourcelines(data)[1] |
|
2296 | lineno = inspect.getsourcelines(data)[1] | |
2306 | except IOError: |
|
2297 | except IOError: | |
2307 | filename = make_filename(args) |
|
2298 | filename = make_filename(args) | |
2308 | if filename is None: |
|
2299 | if filename is None: | |
2309 | warn('The file `%s` where `%s` was defined cannot ' |
|
2300 | warn('The file `%s` where `%s` was defined cannot ' | |
2310 | 'be read.' % (filename,data)) |
|
2301 | 'be read.' % (filename,data)) | |
2311 | return |
|
2302 | return | |
2312 | use_temp = 0 |
|
2303 | use_temp = 0 | |
2313 | else: |
|
2304 | else: | |
2314 | data = '' |
|
2305 | data = '' | |
2315 |
|
2306 | |||
2316 | if use_temp: |
|
2307 | if use_temp: | |
2317 | filename = self.shell.mktempfile(data) |
|
2308 | filename = self.shell.mktempfile(data) | |
2318 | print 'IPython will make a temporary file named:',filename |
|
2309 | print 'IPython will make a temporary file named:',filename | |
2319 |
|
2310 | |||
2320 | # do actual editing here |
|
2311 | # do actual editing here | |
2321 | print 'Editing...', |
|
2312 | print 'Editing...', | |
2322 | sys.stdout.flush() |
|
2313 | sys.stdout.flush() | |
2323 | try: |
|
2314 | try: | |
2324 | # Quote filenames that may have spaces in them |
|
2315 | # Quote filenames that may have spaces in them | |
2325 | if ' ' in filename: |
|
2316 | if ' ' in filename: | |
2326 | filename = "%s" % filename |
|
2317 | filename = "%s" % filename | |
2327 | self.shell.hooks.editor(filename,lineno) |
|
2318 | self.shell.hooks.editor(filename,lineno) | |
2328 | except TryNext: |
|
2319 | except TryNext: | |
2329 | warn('Could not open editor') |
|
2320 | warn('Could not open editor') | |
2330 | return |
|
2321 | return | |
2331 |
|
2322 | |||
2332 | # XXX TODO: should this be generalized for all string vars? |
|
2323 | # XXX TODO: should this be generalized for all string vars? | |
2333 | # For now, this is special-cased to blocks created by cpaste |
|
2324 | # For now, this is special-cased to blocks created by cpaste | |
2334 | if args.strip() == 'pasted_block': |
|
2325 | if args.strip() == 'pasted_block': | |
2335 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2326 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2336 |
|
2327 | |||
2337 | if opts.has_key('x'): # -x prevents actual execution |
|
2328 | if opts.has_key('x'): # -x prevents actual execution | |
2338 |
|
2329 | |||
2339 | else: |
|
2330 | else: | |
2340 | print 'done. Executing edited code...' |
|
2331 | print 'done. Executing edited code...' | |
2341 | if opts_r: |
|
2332 | if opts_r: | |
2342 | self.shell.runlines(file_read(filename)) |
|
2333 | self.shell.runlines(file_read(filename)) | |
2343 | else: |
|
2334 | else: | |
2344 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2335 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2345 | self.shell.user_ns) |
|
2336 | self.shell.user_ns) | |
2346 |
|
2337 | |||
2347 |
|
2338 | |||
2348 | if use_temp: |
|
2339 | if use_temp: | |
2349 | try: |
|
2340 | try: | |
2350 | return open(filename).read() |
|
2341 | return open(filename).read() | |
2351 | except IOError,msg: |
|
2342 | except IOError,msg: | |
2352 | if msg.filename == filename: |
|
2343 | if msg.filename == filename: | |
2353 | warn('File not found. Did you forget to save?') |
|
2344 | warn('File not found. Did you forget to save?') | |
2354 | return |
|
2345 | return | |
2355 | else: |
|
2346 | else: | |
2356 | self.shell.showtraceback() |
|
2347 | self.shell.showtraceback() | |
2357 |
|
2348 | |||
2358 | def magic_xmode(self,parameter_s = ''): |
|
2349 | def magic_xmode(self,parameter_s = ''): | |
2359 | """Switch modes for the exception handlers. |
|
2350 | """Switch modes for the exception handlers. | |
2360 |
|
2351 | |||
2361 | Valid modes: Plain, Context and Verbose. |
|
2352 | Valid modes: Plain, Context and Verbose. | |
2362 |
|
2353 | |||
2363 | If called without arguments, acts as a toggle.""" |
|
2354 | If called without arguments, acts as a toggle.""" | |
2364 |
|
2355 | |||
2365 | def xmode_switch_err(name): |
|
2356 | def xmode_switch_err(name): | |
2366 | warn('Error changing %s exception modes.\n%s' % |
|
2357 | warn('Error changing %s exception modes.\n%s' % | |
2367 | (name,sys.exc_info()[1])) |
|
2358 | (name,sys.exc_info()[1])) | |
2368 |
|
2359 | |||
2369 | shell = self.shell |
|
2360 | shell = self.shell | |
2370 | new_mode = parameter_s.strip().capitalize() |
|
2361 | new_mode = parameter_s.strip().capitalize() | |
2371 | try: |
|
2362 | try: | |
2372 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2363 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2373 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2364 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2374 | except: |
|
2365 | except: | |
2375 | xmode_switch_err('user') |
|
2366 | xmode_switch_err('user') | |
2376 |
|
2367 | |||
2377 | def magic_colors(self,parameter_s = ''): |
|
2368 | def magic_colors(self,parameter_s = ''): | |
2378 | """Switch color scheme for prompts, info system and exception handlers. |
|
2369 | """Switch color scheme for prompts, info system and exception handlers. | |
2379 |
|
2370 | |||
2380 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2371 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2381 |
|
2372 | |||
2382 | Color scheme names are not case-sensitive.""" |
|
2373 | Color scheme names are not case-sensitive.""" | |
2383 |
|
2374 | |||
2384 | def color_switch_err(name): |
|
2375 | def color_switch_err(name): | |
2385 | warn('Error changing %s color schemes.\n%s' % |
|
2376 | warn('Error changing %s color schemes.\n%s' % | |
2386 | (name,sys.exc_info()[1])) |
|
2377 | (name,sys.exc_info()[1])) | |
2387 |
|
2378 | |||
2388 |
|
2379 | |||
2389 | new_scheme = parameter_s.strip() |
|
2380 | new_scheme = parameter_s.strip() | |
2390 | if not new_scheme: |
|
2381 | if not new_scheme: | |
2391 | raise UsageError( |
|
2382 | raise UsageError( | |
2392 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2383 | "%colors: you must specify a color scheme. See '%colors?'") | |
2393 | return |
|
2384 | return | |
2394 | # local shortcut |
|
2385 | # local shortcut | |
2395 | shell = self.shell |
|
2386 | shell = self.shell | |
2396 |
|
2387 | |||
2397 | import IPython.utils.rlineimpl as readline |
|
2388 | import IPython.utils.rlineimpl as readline | |
2398 |
|
2389 | |||
2399 | if not readline.have_readline and sys.platform == "win32": |
|
2390 | if not readline.have_readline and sys.platform == "win32": | |
2400 | msg = """\ |
|
2391 | msg = """\ | |
2401 | Proper color support under MS Windows requires the pyreadline library. |
|
2392 | Proper color support under MS Windows requires the pyreadline library. | |
2402 | You can find it at: |
|
2393 | You can find it at: | |
2403 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2394 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2404 | Gary's readline needs the ctypes module, from: |
|
2395 | Gary's readline needs the ctypes module, from: | |
2405 | http://starship.python.net/crew/theller/ctypes |
|
2396 | http://starship.python.net/crew/theller/ctypes | |
2406 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2397 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2407 |
|
2398 | |||
2408 | Defaulting color scheme to 'NoColor'""" |
|
2399 | Defaulting color scheme to 'NoColor'""" | |
2409 | new_scheme = 'NoColor' |
|
2400 | new_scheme = 'NoColor' | |
2410 | warn(msg) |
|
2401 | warn(msg) | |
2411 |
|
2402 | |||
2412 | # readline option is 0 |
|
2403 | # readline option is 0 | |
2413 | if not shell.has_readline: |
|
2404 | if not shell.has_readline: | |
2414 | new_scheme = 'NoColor' |
|
2405 | new_scheme = 'NoColor' | |
2415 |
|
2406 | |||
2416 | # Set prompt colors |
|
2407 | # Set prompt colors | |
2417 | try: |
|
2408 | try: | |
2418 | shell.displayhook.set_colors(new_scheme) |
|
2409 | shell.displayhook.set_colors(new_scheme) | |
2419 | except: |
|
2410 | except: | |
2420 | color_switch_err('prompt') |
|
2411 | color_switch_err('prompt') | |
2421 | else: |
|
2412 | else: | |
2422 | shell.colors = \ |
|
2413 | shell.colors = \ | |
2423 | shell.displayhook.color_table.active_scheme_name |
|
2414 | shell.displayhook.color_table.active_scheme_name | |
2424 | # Set exception colors |
|
2415 | # Set exception colors | |
2425 | try: |
|
2416 | try: | |
2426 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2417 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2427 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2418 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2428 | except: |
|
2419 | except: | |
2429 | color_switch_err('exception') |
|
2420 | color_switch_err('exception') | |
2430 |
|
2421 | |||
2431 | # Set info (for 'object?') colors |
|
2422 | # Set info (for 'object?') colors | |
2432 | if shell.color_info: |
|
2423 | if shell.color_info: | |
2433 | try: |
|
2424 | try: | |
2434 | shell.inspector.set_active_scheme(new_scheme) |
|
2425 | shell.inspector.set_active_scheme(new_scheme) | |
2435 | except: |
|
2426 | except: | |
2436 | color_switch_err('object inspector') |
|
2427 | color_switch_err('object inspector') | |
2437 | else: |
|
2428 | else: | |
2438 | shell.inspector.set_active_scheme('NoColor') |
|
2429 | shell.inspector.set_active_scheme('NoColor') | |
2439 |
|
2430 | |||
2440 | def magic_color_info(self,parameter_s = ''): |
|
2431 | def magic_color_info(self,parameter_s = ''): | |
2441 | """Toggle color_info. |
|
2432 | """Toggle color_info. | |
2442 |
|
2433 | |||
2443 | The color_info configuration parameter controls whether colors are |
|
2434 | The color_info configuration parameter controls whether colors are | |
2444 | used for displaying object details (by things like %psource, %pfile or |
|
2435 | used for displaying object details (by things like %psource, %pfile or | |
2445 | the '?' system). This function toggles this value with each call. |
|
2436 | the '?' system). This function toggles this value with each call. | |
2446 |
|
2437 | |||
2447 | Note that unless you have a fairly recent pager (less works better |
|
2438 | Note that unless you have a fairly recent pager (less works better | |
2448 | than more) in your system, using colored object information displays |
|
2439 | than more) in your system, using colored object information displays | |
2449 | will not work properly. Test it and see.""" |
|
2440 | will not work properly. Test it and see.""" | |
2450 |
|
2441 | |||
2451 | self.shell.color_info = not self.shell.color_info |
|
2442 | self.shell.color_info = not self.shell.color_info | |
2452 | self.magic_colors(self.shell.colors) |
|
2443 | self.magic_colors(self.shell.colors) | |
2453 | print 'Object introspection functions have now coloring:', |
|
2444 | print 'Object introspection functions have now coloring:', | |
2454 | print ['OFF','ON'][int(self.shell.color_info)] |
|
2445 | print ['OFF','ON'][int(self.shell.color_info)] | |
2455 |
|
2446 | |||
2456 | def magic_Pprint(self, parameter_s=''): |
|
2447 | def magic_Pprint(self, parameter_s=''): | |
2457 | """Toggle pretty printing on/off.""" |
|
2448 | """Toggle pretty printing on/off.""" | |
2458 |
|
2449 | |||
2459 | self.shell.pprint = 1 - self.shell.pprint |
|
2450 | self.shell.pprint = 1 - self.shell.pprint | |
2460 | print 'Pretty printing has been turned', \ |
|
2451 | print 'Pretty printing has been turned', \ | |
2461 | ['OFF','ON'][self.shell.pprint] |
|
2452 | ['OFF','ON'][self.shell.pprint] | |
2462 |
|
2453 | |||
2463 | def magic_Exit(self, parameter_s=''): |
|
2454 | def magic_Exit(self, parameter_s=''): | |
2464 | """Exit IPython without confirmation.""" |
|
2455 | """Exit IPython without confirmation.""" | |
2465 |
|
2456 | |||
2466 | self.shell.ask_exit() |
|
2457 | self.shell.ask_exit() | |
2467 |
|
2458 | |||
2468 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2459 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2469 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2460 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2470 |
|
2461 | |||
2471 | #...................................................................... |
|
2462 | #...................................................................... | |
2472 | # Functions to implement unix shell-type things |
|
2463 | # Functions to implement unix shell-type things | |
2473 |
|
2464 | |||
2474 | @testdec.skip_doctest |
|
2465 | @testdec.skip_doctest | |
2475 | def magic_alias(self, parameter_s = ''): |
|
2466 | def magic_alias(self, parameter_s = ''): | |
2476 | """Define an alias for a system command. |
|
2467 | """Define an alias for a system command. | |
2477 |
|
2468 | |||
2478 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2469 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2479 |
|
2470 | |||
2480 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2471 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2481 | params' (from your underlying operating system). |
|
2472 | params' (from your underlying operating system). | |
2482 |
|
2473 | |||
2483 | Aliases have lower precedence than magic functions and Python normal |
|
2474 | Aliases have lower precedence than magic functions and Python normal | |
2484 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2475 | variables, so if 'foo' is both a Python variable and an alias, the | |
2485 | alias can not be executed until 'del foo' removes the Python variable. |
|
2476 | alias can not be executed until 'del foo' removes the Python variable. | |
2486 |
|
2477 | |||
2487 | You can use the %l specifier in an alias definition to represent the |
|
2478 | You can use the %l specifier in an alias definition to represent the | |
2488 | whole line when the alias is called. For example: |
|
2479 | whole line when the alias is called. For example: | |
2489 |
|
2480 | |||
2490 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2481 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2491 | In [3]: bracket hello world |
|
2482 | In [3]: bracket hello world | |
2492 | Input in brackets: <hello world> |
|
2483 | Input in brackets: <hello world> | |
2493 |
|
2484 | |||
2494 | You can also define aliases with parameters using %s specifiers (one |
|
2485 | You can also define aliases with parameters using %s specifiers (one | |
2495 | per parameter): |
|
2486 | per parameter): | |
2496 |
|
2487 | |||
2497 | In [1]: alias parts echo first %s second %s |
|
2488 | In [1]: alias parts echo first %s second %s | |
2498 | In [2]: %parts A B |
|
2489 | In [2]: %parts A B | |
2499 | first A second B |
|
2490 | first A second B | |
2500 | In [3]: %parts A |
|
2491 | In [3]: %parts A | |
2501 | Incorrect number of arguments: 2 expected. |
|
2492 | Incorrect number of arguments: 2 expected. | |
2502 | parts is an alias to: 'echo first %s second %s' |
|
2493 | parts is an alias to: 'echo first %s second %s' | |
2503 |
|
2494 | |||
2504 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2495 | Note that %l and %s are mutually exclusive. You can only use one or | |
2505 | the other in your aliases. |
|
2496 | the other in your aliases. | |
2506 |
|
2497 | |||
2507 | Aliases expand Python variables just like system calls using ! or !! |
|
2498 | Aliases expand Python variables just like system calls using ! or !! | |
2508 | do: all expressions prefixed with '$' get expanded. For details of |
|
2499 | do: all expressions prefixed with '$' get expanded. For details of | |
2509 | the semantic rules, see PEP-215: |
|
2500 | the semantic rules, see PEP-215: | |
2510 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2501 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2511 | IPython for variable expansion. If you want to access a true shell |
|
2502 | IPython for variable expansion. If you want to access a true shell | |
2512 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2503 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2513 |
|
2504 | |||
2514 | In [6]: alias show echo |
|
2505 | In [6]: alias show echo | |
2515 | In [7]: PATH='A Python string' |
|
2506 | In [7]: PATH='A Python string' | |
2516 | In [8]: show $PATH |
|
2507 | In [8]: show $PATH | |
2517 | A Python string |
|
2508 | A Python string | |
2518 | In [9]: show $$PATH |
|
2509 | In [9]: show $$PATH | |
2519 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2510 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2520 |
|
2511 | |||
2521 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2512 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2522 | and %rehashx functions, which automatically create aliases for the |
|
2513 | and %rehashx functions, which automatically create aliases for the | |
2523 | contents of your $PATH. |
|
2514 | contents of your $PATH. | |
2524 |
|
2515 | |||
2525 | If called with no parameters, %alias prints the current alias table.""" |
|
2516 | If called with no parameters, %alias prints the current alias table.""" | |
2526 |
|
2517 | |||
2527 | par = parameter_s.strip() |
|
2518 | par = parameter_s.strip() | |
2528 | if not par: |
|
2519 | if not par: | |
2529 | stored = self.db.get('stored_aliases', {} ) |
|
2520 | stored = self.db.get('stored_aliases', {} ) | |
2530 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2521 | aliases = sorted(self.shell.alias_manager.aliases) | |
2531 | # for k, v in stored: |
|
2522 | # for k, v in stored: | |
2532 | # atab.append(k, v[0]) |
|
2523 | # atab.append(k, v[0]) | |
2533 |
|
2524 | |||
2534 | print "Total number of aliases:", len(aliases) |
|
2525 | print "Total number of aliases:", len(aliases) | |
2535 | return aliases |
|
2526 | return aliases | |
2536 |
|
2527 | |||
2537 | # Now try to define a new one |
|
2528 | # Now try to define a new one | |
2538 | try: |
|
2529 | try: | |
2539 | alias,cmd = par.split(None, 1) |
|
2530 | alias,cmd = par.split(None, 1) | |
2540 | except: |
|
2531 | except: | |
2541 | print oinspect.getdoc(self.magic_alias) |
|
2532 | print oinspect.getdoc(self.magic_alias) | |
2542 | else: |
|
2533 | else: | |
2543 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2534 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2544 | # end magic_alias |
|
2535 | # end magic_alias | |
2545 |
|
2536 | |||
2546 | def magic_unalias(self, parameter_s = ''): |
|
2537 | def magic_unalias(self, parameter_s = ''): | |
2547 | """Remove an alias""" |
|
2538 | """Remove an alias""" | |
2548 |
|
2539 | |||
2549 | aname = parameter_s.strip() |
|
2540 | aname = parameter_s.strip() | |
2550 | self.shell.alias_manager.undefine_alias(aname) |
|
2541 | self.shell.alias_manager.undefine_alias(aname) | |
2551 | stored = self.db.get('stored_aliases', {} ) |
|
2542 | stored = self.db.get('stored_aliases', {} ) | |
2552 | if aname in stored: |
|
2543 | if aname in stored: | |
2553 | print "Removing %stored alias",aname |
|
2544 | print "Removing %stored alias",aname | |
2554 | del stored[aname] |
|
2545 | del stored[aname] | |
2555 | self.db['stored_aliases'] = stored |
|
2546 | self.db['stored_aliases'] = stored | |
2556 |
|
2547 | |||
2557 |
|
2548 | |||
2558 | def magic_rehashx(self, parameter_s = ''): |
|
2549 | def magic_rehashx(self, parameter_s = ''): | |
2559 | """Update the alias table with all executable files in $PATH. |
|
2550 | """Update the alias table with all executable files in $PATH. | |
2560 |
|
2551 | |||
2561 | This version explicitly checks that every entry in $PATH is a file |
|
2552 | This version explicitly checks that every entry in $PATH is a file | |
2562 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2553 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2563 |
|
2554 | |||
2564 | Under Windows, it checks executability as a match agains a |
|
2555 | Under Windows, it checks executability as a match agains a | |
2565 | '|'-separated string of extensions, stored in the IPython config |
|
2556 | '|'-separated string of extensions, stored in the IPython config | |
2566 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2557 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2567 |
|
2558 | |||
2568 | This function also resets the root module cache of module completer, |
|
2559 | This function also resets the root module cache of module completer, | |
2569 | used on slow filesystems. |
|
2560 | used on slow filesystems. | |
2570 | """ |
|
2561 | """ | |
2571 | from IPython.core.alias import InvalidAliasError |
|
2562 | from IPython.core.alias import InvalidAliasError | |
2572 |
|
2563 | |||
2573 | # for the benefit of module completer in ipy_completers.py |
|
2564 | # for the benefit of module completer in ipy_completers.py | |
2574 | del self.db['rootmodules'] |
|
2565 | del self.db['rootmodules'] | |
2575 |
|
2566 | |||
2576 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2567 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2577 | os.environ.get('PATH','').split(os.pathsep)] |
|
2568 | os.environ.get('PATH','').split(os.pathsep)] | |
2578 | path = filter(os.path.isdir,path) |
|
2569 | path = filter(os.path.isdir,path) | |
2579 |
|
2570 | |||
2580 | syscmdlist = [] |
|
2571 | syscmdlist = [] | |
2581 | # Now define isexec in a cross platform manner. |
|
2572 | # Now define isexec in a cross platform manner. | |
2582 | if os.name == 'posix': |
|
2573 | if os.name == 'posix': | |
2583 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2574 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2584 | os.access(fname,os.X_OK) |
|
2575 | os.access(fname,os.X_OK) | |
2585 | else: |
|
2576 | else: | |
2586 | try: |
|
2577 | try: | |
2587 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2578 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2588 | except KeyError: |
|
2579 | except KeyError: | |
2589 | winext = 'exe|com|bat|py' |
|
2580 | winext = 'exe|com|bat|py' | |
2590 | if 'py' not in winext: |
|
2581 | if 'py' not in winext: | |
2591 | winext += '|py' |
|
2582 | winext += '|py' | |
2592 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2583 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2593 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2584 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2594 | savedir = os.getcwd() |
|
2585 | savedir = os.getcwd() | |
2595 |
|
2586 | |||
2596 | # Now walk the paths looking for executables to alias. |
|
2587 | # Now walk the paths looking for executables to alias. | |
2597 | try: |
|
2588 | try: | |
2598 | # write the whole loop for posix/Windows so we don't have an if in |
|
2589 | # write the whole loop for posix/Windows so we don't have an if in | |
2599 | # the innermost part |
|
2590 | # the innermost part | |
2600 | if os.name == 'posix': |
|
2591 | if os.name == 'posix': | |
2601 | for pdir in path: |
|
2592 | for pdir in path: | |
2602 | os.chdir(pdir) |
|
2593 | os.chdir(pdir) | |
2603 | for ff in os.listdir(pdir): |
|
2594 | for ff in os.listdir(pdir): | |
2604 | if isexec(ff): |
|
2595 | if isexec(ff): | |
2605 | try: |
|
2596 | try: | |
2606 | # Removes dots from the name since ipython |
|
2597 | # Removes dots from the name since ipython | |
2607 | # will assume names with dots to be python. |
|
2598 | # will assume names with dots to be python. | |
2608 | self.shell.alias_manager.define_alias( |
|
2599 | self.shell.alias_manager.define_alias( | |
2609 | ff.replace('.',''), ff) |
|
2600 | ff.replace('.',''), ff) | |
2610 | except InvalidAliasError: |
|
2601 | except InvalidAliasError: | |
2611 | pass |
|
2602 | pass | |
2612 | else: |
|
2603 | else: | |
2613 | syscmdlist.append(ff) |
|
2604 | syscmdlist.append(ff) | |
2614 | else: |
|
2605 | else: | |
2615 | no_alias = self.shell.alias_manager.no_alias |
|
2606 | no_alias = self.shell.alias_manager.no_alias | |
2616 | for pdir in path: |
|
2607 | for pdir in path: | |
2617 | os.chdir(pdir) |
|
2608 | os.chdir(pdir) | |
2618 | for ff in os.listdir(pdir): |
|
2609 | for ff in os.listdir(pdir): | |
2619 | base, ext = os.path.splitext(ff) |
|
2610 | base, ext = os.path.splitext(ff) | |
2620 | if isexec(ff) and base.lower() not in no_alias: |
|
2611 | if isexec(ff) and base.lower() not in no_alias: | |
2621 | if ext.lower() == '.exe': |
|
2612 | if ext.lower() == '.exe': | |
2622 | ff = base |
|
2613 | ff = base | |
2623 | try: |
|
2614 | try: | |
2624 | # Removes dots from the name since ipython |
|
2615 | # Removes dots from the name since ipython | |
2625 | # will assume names with dots to be python. |
|
2616 | # will assume names with dots to be python. | |
2626 | self.shell.alias_manager.define_alias( |
|
2617 | self.shell.alias_manager.define_alias( | |
2627 | base.lower().replace('.',''), ff) |
|
2618 | base.lower().replace('.',''), ff) | |
2628 | except InvalidAliasError: |
|
2619 | except InvalidAliasError: | |
2629 | pass |
|
2620 | pass | |
2630 | syscmdlist.append(ff) |
|
2621 | syscmdlist.append(ff) | |
2631 | db = self.db |
|
2622 | db = self.db | |
2632 | db['syscmdlist'] = syscmdlist |
|
2623 | db['syscmdlist'] = syscmdlist | |
2633 | finally: |
|
2624 | finally: | |
2634 | os.chdir(savedir) |
|
2625 | os.chdir(savedir) | |
2635 |
|
2626 | |||
2636 | def magic_pwd(self, parameter_s = ''): |
|
2627 | def magic_pwd(self, parameter_s = ''): | |
2637 | """Return the current working directory path.""" |
|
2628 | """Return the current working directory path.""" | |
2638 | return os.getcwd() |
|
2629 | return os.getcwd() | |
2639 |
|
2630 | |||
2640 | def magic_cd(self, parameter_s=''): |
|
2631 | def magic_cd(self, parameter_s=''): | |
2641 | """Change the current working directory. |
|
2632 | """Change the current working directory. | |
2642 |
|
2633 | |||
2643 | This command automatically maintains an internal list of directories |
|
2634 | This command automatically maintains an internal list of directories | |
2644 | you visit during your IPython session, in the variable _dh. The |
|
2635 | you visit during your IPython session, in the variable _dh. The | |
2645 | command %dhist shows this history nicely formatted. You can also |
|
2636 | command %dhist shows this history nicely formatted. You can also | |
2646 | do 'cd -<tab>' to see directory history conveniently. |
|
2637 | do 'cd -<tab>' to see directory history conveniently. | |
2647 |
|
2638 | |||
2648 | Usage: |
|
2639 | Usage: | |
2649 |
|
2640 | |||
2650 | cd 'dir': changes to directory 'dir'. |
|
2641 | cd 'dir': changes to directory 'dir'. | |
2651 |
|
2642 | |||
2652 | cd -: changes to the last visited directory. |
|
2643 | cd -: changes to the last visited directory. | |
2653 |
|
2644 | |||
2654 | cd -<n>: changes to the n-th directory in the directory history. |
|
2645 | cd -<n>: changes to the n-th directory in the directory history. | |
2655 |
|
2646 | |||
2656 | cd --foo: change to directory that matches 'foo' in history |
|
2647 | cd --foo: change to directory that matches 'foo' in history | |
2657 |
|
2648 | |||
2658 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2649 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2659 | (note: cd <bookmark_name> is enough if there is no |
|
2650 | (note: cd <bookmark_name> is enough if there is no | |
2660 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2651 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2661 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2652 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2662 |
|
2653 | |||
2663 | Options: |
|
2654 | Options: | |
2664 |
|
2655 | |||
2665 | -q: quiet. Do not print the working directory after the cd command is |
|
2656 | -q: quiet. Do not print the working directory after the cd command is | |
2666 | executed. By default IPython's cd command does print this directory, |
|
2657 | executed. By default IPython's cd command does print this directory, | |
2667 | since the default prompts do not display path information. |
|
2658 | since the default prompts do not display path information. | |
2668 |
|
2659 | |||
2669 | Note that !cd doesn't work for this purpose because the shell where |
|
2660 | Note that !cd doesn't work for this purpose because the shell where | |
2670 | !command runs is immediately discarded after executing 'command'.""" |
|
2661 | !command runs is immediately discarded after executing 'command'.""" | |
2671 |
|
2662 | |||
2672 | parameter_s = parameter_s.strip() |
|
2663 | parameter_s = parameter_s.strip() | |
2673 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2664 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2674 |
|
2665 | |||
2675 | oldcwd = os.getcwd() |
|
2666 | oldcwd = os.getcwd() | |
2676 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2667 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2677 | # jump in directory history by number |
|
2668 | # jump in directory history by number | |
2678 | if numcd: |
|
2669 | if numcd: | |
2679 | nn = int(numcd.group(2)) |
|
2670 | nn = int(numcd.group(2)) | |
2680 | try: |
|
2671 | try: | |
2681 | ps = self.shell.user_ns['_dh'][nn] |
|
2672 | ps = self.shell.user_ns['_dh'][nn] | |
2682 | except IndexError: |
|
2673 | except IndexError: | |
2683 | print 'The requested directory does not exist in history.' |
|
2674 | print 'The requested directory does not exist in history.' | |
2684 | return |
|
2675 | return | |
2685 | else: |
|
2676 | else: | |
2686 | opts = {} |
|
2677 | opts = {} | |
2687 | elif parameter_s.startswith('--'): |
|
2678 | elif parameter_s.startswith('--'): | |
2688 | ps = None |
|
2679 | ps = None | |
2689 | fallback = None |
|
2680 | fallback = None | |
2690 | pat = parameter_s[2:] |
|
2681 | pat = parameter_s[2:] | |
2691 | dh = self.shell.user_ns['_dh'] |
|
2682 | dh = self.shell.user_ns['_dh'] | |
2692 | # first search only by basename (last component) |
|
2683 | # first search only by basename (last component) | |
2693 | for ent in reversed(dh): |
|
2684 | for ent in reversed(dh): | |
2694 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2685 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2695 | ps = ent |
|
2686 | ps = ent | |
2696 | break |
|
2687 | break | |
2697 |
|
2688 | |||
2698 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2689 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2699 | fallback = ent |
|
2690 | fallback = ent | |
2700 |
|
2691 | |||
2701 | # if we have no last part match, pick the first full path match |
|
2692 | # if we have no last part match, pick the first full path match | |
2702 | if ps is None: |
|
2693 | if ps is None: | |
2703 | ps = fallback |
|
2694 | ps = fallback | |
2704 |
|
2695 | |||
2705 | if ps is None: |
|
2696 | if ps is None: | |
2706 | print "No matching entry in directory history" |
|
2697 | print "No matching entry in directory history" | |
2707 | return |
|
2698 | return | |
2708 | else: |
|
2699 | else: | |
2709 | opts = {} |
|
2700 | opts = {} | |
2710 |
|
2701 | |||
2711 |
|
2702 | |||
2712 | else: |
|
2703 | else: | |
2713 | #turn all non-space-escaping backslashes to slashes, |
|
2704 | #turn all non-space-escaping backslashes to slashes, | |
2714 | # for c:\windows\directory\names\ |
|
2705 | # for c:\windows\directory\names\ | |
2715 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2706 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2716 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2707 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2717 | # jump to previous |
|
2708 | # jump to previous | |
2718 | if ps == '-': |
|
2709 | if ps == '-': | |
2719 | try: |
|
2710 | try: | |
2720 | ps = self.shell.user_ns['_dh'][-2] |
|
2711 | ps = self.shell.user_ns['_dh'][-2] | |
2721 | except IndexError: |
|
2712 | except IndexError: | |
2722 | raise UsageError('%cd -: No previous directory to change to.') |
|
2713 | raise UsageError('%cd -: No previous directory to change to.') | |
2723 | # jump to bookmark if needed |
|
2714 | # jump to bookmark if needed | |
2724 | else: |
|
2715 | else: | |
2725 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2716 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2726 | bkms = self.db.get('bookmarks', {}) |
|
2717 | bkms = self.db.get('bookmarks', {}) | |
2727 |
|
2718 | |||
2728 | if bkms.has_key(ps): |
|
2719 | if bkms.has_key(ps): | |
2729 | target = bkms[ps] |
|
2720 | target = bkms[ps] | |
2730 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2721 | print '(bookmark:%s) -> %s' % (ps,target) | |
2731 | ps = target |
|
2722 | ps = target | |
2732 | else: |
|
2723 | else: | |
2733 | if opts.has_key('b'): |
|
2724 | if opts.has_key('b'): | |
2734 | raise UsageError("Bookmark '%s' not found. " |
|
2725 | raise UsageError("Bookmark '%s' not found. " | |
2735 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2726 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2736 |
|
2727 | |||
2737 | # at this point ps should point to the target dir |
|
2728 | # at this point ps should point to the target dir | |
2738 | if ps: |
|
2729 | if ps: | |
2739 | try: |
|
2730 | try: | |
2740 | os.chdir(os.path.expanduser(ps)) |
|
2731 | os.chdir(os.path.expanduser(ps)) | |
2741 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2732 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2742 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2733 | set_term_title('IPython: ' + abbrev_cwd()) | |
2743 | except OSError: |
|
2734 | except OSError: | |
2744 | print sys.exc_info()[1] |
|
2735 | print sys.exc_info()[1] | |
2745 | else: |
|
2736 | else: | |
2746 | cwd = os.getcwd() |
|
2737 | cwd = os.getcwd() | |
2747 | dhist = self.shell.user_ns['_dh'] |
|
2738 | dhist = self.shell.user_ns['_dh'] | |
2748 | if oldcwd != cwd: |
|
2739 | if oldcwd != cwd: | |
2749 | dhist.append(cwd) |
|
2740 | dhist.append(cwd) | |
2750 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2741 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2751 |
|
2742 | |||
2752 | else: |
|
2743 | else: | |
2753 | os.chdir(self.shell.home_dir) |
|
2744 | os.chdir(self.shell.home_dir) | |
2754 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2745 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2755 | set_term_title('IPython: ' + '~') |
|
2746 | set_term_title('IPython: ' + '~') | |
2756 | cwd = os.getcwd() |
|
2747 | cwd = os.getcwd() | |
2757 | dhist = self.shell.user_ns['_dh'] |
|
2748 | dhist = self.shell.user_ns['_dh'] | |
2758 |
|
2749 | |||
2759 | if oldcwd != cwd: |
|
2750 | if oldcwd != cwd: | |
2760 | dhist.append(cwd) |
|
2751 | dhist.append(cwd) | |
2761 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2752 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2762 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2753 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2763 | print self.shell.user_ns['_dh'][-1] |
|
2754 | print self.shell.user_ns['_dh'][-1] | |
2764 |
|
2755 | |||
2765 |
|
2756 | |||
2766 | def magic_env(self, parameter_s=''): |
|
2757 | def magic_env(self, parameter_s=''): | |
2767 | """List environment variables.""" |
|
2758 | """List environment variables.""" | |
2768 |
|
2759 | |||
2769 | return os.environ.data |
|
2760 | return os.environ.data | |
2770 |
|
2761 | |||
2771 | def magic_pushd(self, parameter_s=''): |
|
2762 | def magic_pushd(self, parameter_s=''): | |
2772 | """Place the current dir on stack and change directory. |
|
2763 | """Place the current dir on stack and change directory. | |
2773 |
|
2764 | |||
2774 | Usage:\\ |
|
2765 | Usage:\\ | |
2775 | %pushd ['dirname'] |
|
2766 | %pushd ['dirname'] | |
2776 | """ |
|
2767 | """ | |
2777 |
|
2768 | |||
2778 | dir_s = self.shell.dir_stack |
|
2769 | dir_s = self.shell.dir_stack | |
2779 | tgt = os.path.expanduser(parameter_s) |
|
2770 | tgt = os.path.expanduser(parameter_s) | |
2780 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2771 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2781 | if tgt: |
|
2772 | if tgt: | |
2782 | self.magic_cd(parameter_s) |
|
2773 | self.magic_cd(parameter_s) | |
2783 | dir_s.insert(0,cwd) |
|
2774 | dir_s.insert(0,cwd) | |
2784 | return self.magic_dirs() |
|
2775 | return self.magic_dirs() | |
2785 |
|
2776 | |||
2786 | def magic_popd(self, parameter_s=''): |
|
2777 | def magic_popd(self, parameter_s=''): | |
2787 | """Change to directory popped off the top of the stack. |
|
2778 | """Change to directory popped off the top of the stack. | |
2788 | """ |
|
2779 | """ | |
2789 | if not self.shell.dir_stack: |
|
2780 | if not self.shell.dir_stack: | |
2790 | raise UsageError("%popd on empty stack") |
|
2781 | raise UsageError("%popd on empty stack") | |
2791 | top = self.shell.dir_stack.pop(0) |
|
2782 | top = self.shell.dir_stack.pop(0) | |
2792 | self.magic_cd(top) |
|
2783 | self.magic_cd(top) | |
2793 | print "popd ->",top |
|
2784 | print "popd ->",top | |
2794 |
|
2785 | |||
2795 | def magic_dirs(self, parameter_s=''): |
|
2786 | def magic_dirs(self, parameter_s=''): | |
2796 | """Return the current directory stack.""" |
|
2787 | """Return the current directory stack.""" | |
2797 |
|
2788 | |||
2798 | return self.shell.dir_stack |
|
2789 | return self.shell.dir_stack | |
2799 |
|
2790 | |||
2800 | def magic_dhist(self, parameter_s=''): |
|
2791 | def magic_dhist(self, parameter_s=''): | |
2801 | """Print your history of visited directories. |
|
2792 | """Print your history of visited directories. | |
2802 |
|
2793 | |||
2803 | %dhist -> print full history\\ |
|
2794 | %dhist -> print full history\\ | |
2804 | %dhist n -> print last n entries only\\ |
|
2795 | %dhist n -> print last n entries only\\ | |
2805 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2796 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2806 |
|
2797 | |||
2807 | This history is automatically maintained by the %cd command, and |
|
2798 | This history is automatically maintained by the %cd command, and | |
2808 | always available as the global list variable _dh. You can use %cd -<n> |
|
2799 | always available as the global list variable _dh. You can use %cd -<n> | |
2809 | to go to directory number <n>. |
|
2800 | to go to directory number <n>. | |
2810 |
|
2801 | |||
2811 | Note that most of time, you should view directory history by entering |
|
2802 | Note that most of time, you should view directory history by entering | |
2812 | cd -<TAB>. |
|
2803 | cd -<TAB>. | |
2813 |
|
2804 | |||
2814 | """ |
|
2805 | """ | |
2815 |
|
2806 | |||
2816 | dh = self.shell.user_ns['_dh'] |
|
2807 | dh = self.shell.user_ns['_dh'] | |
2817 | if parameter_s: |
|
2808 | if parameter_s: | |
2818 | try: |
|
2809 | try: | |
2819 | args = map(int,parameter_s.split()) |
|
2810 | args = map(int,parameter_s.split()) | |
2820 | except: |
|
2811 | except: | |
2821 | self.arg_err(Magic.magic_dhist) |
|
2812 | self.arg_err(Magic.magic_dhist) | |
2822 | return |
|
2813 | return | |
2823 | if len(args) == 1: |
|
2814 | if len(args) == 1: | |
2824 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2815 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2825 | elif len(args) == 2: |
|
2816 | elif len(args) == 2: | |
2826 | ini,fin = args |
|
2817 | ini,fin = args | |
2827 | else: |
|
2818 | else: | |
2828 | self.arg_err(Magic.magic_dhist) |
|
2819 | self.arg_err(Magic.magic_dhist) | |
2829 | return |
|
2820 | return | |
2830 | else: |
|
2821 | else: | |
2831 | ini,fin = 0,len(dh) |
|
2822 | ini,fin = 0,len(dh) | |
2832 | nlprint(dh, |
|
2823 | nlprint(dh, | |
2833 | header = 'Directory history (kept in _dh)', |
|
2824 | header = 'Directory history (kept in _dh)', | |
2834 | start=ini,stop=fin) |
|
2825 | start=ini,stop=fin) | |
2835 |
|
2826 | |||
2836 | @testdec.skip_doctest |
|
2827 | @testdec.skip_doctest | |
2837 | def magic_sc(self, parameter_s=''): |
|
2828 | def magic_sc(self, parameter_s=''): | |
2838 | """Shell capture - execute a shell command and capture its output. |
|
2829 | """Shell capture - execute a shell command and capture its output. | |
2839 |
|
2830 | |||
2840 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2831 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2841 |
|
2832 | |||
2842 | You should use the form 'var = !command' instead. Example: |
|
2833 | You should use the form 'var = !command' instead. Example: | |
2843 |
|
2834 | |||
2844 | "%sc -l myfiles = ls ~" should now be written as |
|
2835 | "%sc -l myfiles = ls ~" should now be written as | |
2845 |
|
2836 | |||
2846 | "myfiles = !ls ~" |
|
2837 | "myfiles = !ls ~" | |
2847 |
|
2838 | |||
2848 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2839 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2849 | below. |
|
2840 | below. | |
2850 |
|
2841 | |||
2851 | -- |
|
2842 | -- | |
2852 | %sc [options] varname=command |
|
2843 | %sc [options] varname=command | |
2853 |
|
2844 | |||
2854 | IPython will run the given command using commands.getoutput(), and |
|
2845 | IPython will run the given command using commands.getoutput(), and | |
2855 | will then update the user's interactive namespace with a variable |
|
2846 | will then update the user's interactive namespace with a variable | |
2856 | called varname, containing the value of the call. Your command can |
|
2847 | called varname, containing the value of the call. Your command can | |
2857 | contain shell wildcards, pipes, etc. |
|
2848 | contain shell wildcards, pipes, etc. | |
2858 |
|
2849 | |||
2859 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2850 | The '=' sign in the syntax is mandatory, and the variable name you | |
2860 | supply must follow Python's standard conventions for valid names. |
|
2851 | supply must follow Python's standard conventions for valid names. | |
2861 |
|
2852 | |||
2862 | (A special format without variable name exists for internal use) |
|
2853 | (A special format without variable name exists for internal use) | |
2863 |
|
2854 | |||
2864 | Options: |
|
2855 | Options: | |
2865 |
|
2856 | |||
2866 | -l: list output. Split the output on newlines into a list before |
|
2857 | -l: list output. Split the output on newlines into a list before | |
2867 | assigning it to the given variable. By default the output is stored |
|
2858 | assigning it to the given variable. By default the output is stored | |
2868 | as a single string. |
|
2859 | as a single string. | |
2869 |
|
2860 | |||
2870 | -v: verbose. Print the contents of the variable. |
|
2861 | -v: verbose. Print the contents of the variable. | |
2871 |
|
2862 | |||
2872 | In most cases you should not need to split as a list, because the |
|
2863 | In most cases you should not need to split as a list, because the | |
2873 | returned value is a special type of string which can automatically |
|
2864 | returned value is a special type of string which can automatically | |
2874 | provide its contents either as a list (split on newlines) or as a |
|
2865 | provide its contents either as a list (split on newlines) or as a | |
2875 | space-separated string. These are convenient, respectively, either |
|
2866 | space-separated string. These are convenient, respectively, either | |
2876 | for sequential processing or to be passed to a shell command. |
|
2867 | for sequential processing or to be passed to a shell command. | |
2877 |
|
2868 | |||
2878 | For example: |
|
2869 | For example: | |
2879 |
|
2870 | |||
2880 | # all-random |
|
2871 | # all-random | |
2881 |
|
2872 | |||
2882 | # Capture into variable a |
|
2873 | # Capture into variable a | |
2883 | In [1]: sc a=ls *py |
|
2874 | In [1]: sc a=ls *py | |
2884 |
|
2875 | |||
2885 | # a is a string with embedded newlines |
|
2876 | # a is a string with embedded newlines | |
2886 | In [2]: a |
|
2877 | In [2]: a | |
2887 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2878 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2888 |
|
2879 | |||
2889 | # which can be seen as a list: |
|
2880 | # which can be seen as a list: | |
2890 | In [3]: a.l |
|
2881 | In [3]: a.l | |
2891 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2882 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2892 |
|
2883 | |||
2893 | # or as a whitespace-separated string: |
|
2884 | # or as a whitespace-separated string: | |
2894 | In [4]: a.s |
|
2885 | In [4]: a.s | |
2895 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2886 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2896 |
|
2887 | |||
2897 | # a.s is useful to pass as a single command line: |
|
2888 | # a.s is useful to pass as a single command line: | |
2898 | In [5]: !wc -l $a.s |
|
2889 | In [5]: !wc -l $a.s | |
2899 | 146 setup.py |
|
2890 | 146 setup.py | |
2900 | 130 win32_manual_post_install.py |
|
2891 | 130 win32_manual_post_install.py | |
2901 | 276 total |
|
2892 | 276 total | |
2902 |
|
2893 | |||
2903 | # while the list form is useful to loop over: |
|
2894 | # while the list form is useful to loop over: | |
2904 | In [6]: for f in a.l: |
|
2895 | In [6]: for f in a.l: | |
2905 | ...: !wc -l $f |
|
2896 | ...: !wc -l $f | |
2906 | ...: |
|
2897 | ...: | |
2907 | 146 setup.py |
|
2898 | 146 setup.py | |
2908 | 130 win32_manual_post_install.py |
|
2899 | 130 win32_manual_post_install.py | |
2909 |
|
2900 | |||
2910 | Similiarly, the lists returned by the -l option are also special, in |
|
2901 | Similiarly, the lists returned by the -l option are also special, in | |
2911 | the sense that you can equally invoke the .s attribute on them to |
|
2902 | the sense that you can equally invoke the .s attribute on them to | |
2912 | automatically get a whitespace-separated string from their contents: |
|
2903 | automatically get a whitespace-separated string from their contents: | |
2913 |
|
2904 | |||
2914 | In [7]: sc -l b=ls *py |
|
2905 | In [7]: sc -l b=ls *py | |
2915 |
|
2906 | |||
2916 | In [8]: b |
|
2907 | In [8]: b | |
2917 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2908 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2918 |
|
2909 | |||
2919 | In [9]: b.s |
|
2910 | In [9]: b.s | |
2920 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2911 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2921 |
|
2912 | |||
2922 | In summary, both the lists and strings used for ouptut capture have |
|
2913 | In summary, both the lists and strings used for ouptut capture have | |
2923 | the following special attributes: |
|
2914 | the following special attributes: | |
2924 |
|
2915 | |||
2925 | .l (or .list) : value as list. |
|
2916 | .l (or .list) : value as list. | |
2926 | .n (or .nlstr): value as newline-separated string. |
|
2917 | .n (or .nlstr): value as newline-separated string. | |
2927 | .s (or .spstr): value as space-separated string. |
|
2918 | .s (or .spstr): value as space-separated string. | |
2928 | """ |
|
2919 | """ | |
2929 |
|
2920 | |||
2930 | opts,args = self.parse_options(parameter_s,'lv') |
|
2921 | opts,args = self.parse_options(parameter_s,'lv') | |
2931 | # Try to get a variable name and command to run |
|
2922 | # Try to get a variable name and command to run | |
2932 | try: |
|
2923 | try: | |
2933 | # the variable name must be obtained from the parse_options |
|
2924 | # the variable name must be obtained from the parse_options | |
2934 | # output, which uses shlex.split to strip options out. |
|
2925 | # output, which uses shlex.split to strip options out. | |
2935 | var,_ = args.split('=',1) |
|
2926 | var,_ = args.split('=',1) | |
2936 | var = var.strip() |
|
2927 | var = var.strip() | |
2937 | # But the the command has to be extracted from the original input |
|
2928 | # But the the command has to be extracted from the original input | |
2938 | # parameter_s, not on what parse_options returns, to avoid the |
|
2929 | # parameter_s, not on what parse_options returns, to avoid the | |
2939 | # quote stripping which shlex.split performs on it. |
|
2930 | # quote stripping which shlex.split performs on it. | |
2940 | _,cmd = parameter_s.split('=',1) |
|
2931 | _,cmd = parameter_s.split('=',1) | |
2941 | except ValueError: |
|
2932 | except ValueError: | |
2942 | var,cmd = '','' |
|
2933 | var,cmd = '','' | |
2943 | # If all looks ok, proceed |
|
2934 | # If all looks ok, proceed | |
2944 | out = self.shell.getoutput(cmd) |
|
2935 | out = self.shell.getoutput(cmd) | |
2945 | if opts.has_key('l'): |
|
2936 | if opts.has_key('l'): | |
2946 | out = SList(out.split('\n')) |
|
2937 | out = SList(out.split('\n')) | |
2947 | else: |
|
2938 | else: | |
2948 | out = LSString(out) |
|
2939 | out = LSString(out) | |
2949 | if opts.has_key('v'): |
|
2940 | if opts.has_key('v'): | |
2950 | print '%s ==\n%s' % (var,pformat(out)) |
|
2941 | print '%s ==\n%s' % (var,pformat(out)) | |
2951 | if var: |
|
2942 | if var: | |
2952 | self.shell.user_ns.update({var:out}) |
|
2943 | self.shell.user_ns.update({var:out}) | |
2953 | else: |
|
2944 | else: | |
2954 | return out |
|
2945 | return out | |
2955 |
|
2946 | |||
2956 | def magic_sx(self, parameter_s=''): |
|
2947 | def magic_sx(self, parameter_s=''): | |
2957 | """Shell execute - run a shell command and capture its output. |
|
2948 | """Shell execute - run a shell command and capture its output. | |
2958 |
|
2949 | |||
2959 | %sx command |
|
2950 | %sx command | |
2960 |
|
2951 | |||
2961 | IPython will run the given command using commands.getoutput(), and |
|
2952 | IPython will run the given command using commands.getoutput(), and | |
2962 | return the result formatted as a list (split on '\\n'). Since the |
|
2953 | return the result formatted as a list (split on '\\n'). Since the | |
2963 | output is _returned_, it will be stored in ipython's regular output |
|
2954 | output is _returned_, it will be stored in ipython's regular output | |
2964 | cache Out[N] and in the '_N' automatic variables. |
|
2955 | cache Out[N] and in the '_N' automatic variables. | |
2965 |
|
2956 | |||
2966 | Notes: |
|
2957 | Notes: | |
2967 |
|
2958 | |||
2968 | 1) If an input line begins with '!!', then %sx is automatically |
|
2959 | 1) If an input line begins with '!!', then %sx is automatically | |
2969 | invoked. That is, while: |
|
2960 | invoked. That is, while: | |
2970 | !ls |
|
2961 | !ls | |
2971 | causes ipython to simply issue system('ls'), typing |
|
2962 | causes ipython to simply issue system('ls'), typing | |
2972 | !!ls |
|
2963 | !!ls | |
2973 | is a shorthand equivalent to: |
|
2964 | is a shorthand equivalent to: | |
2974 | %sx ls |
|
2965 | %sx ls | |
2975 |
|
2966 | |||
2976 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2967 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2977 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2968 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2978 | to process line-oriented shell output via further python commands. |
|
2969 | to process line-oriented shell output via further python commands. | |
2979 | %sc is meant to provide much finer control, but requires more |
|
2970 | %sc is meant to provide much finer control, but requires more | |
2980 | typing. |
|
2971 | typing. | |
2981 |
|
2972 | |||
2982 | 3) Just like %sc -l, this is a list with special attributes: |
|
2973 | 3) Just like %sc -l, this is a list with special attributes: | |
2983 |
|
2974 | |||
2984 | .l (or .list) : value as list. |
|
2975 | .l (or .list) : value as list. | |
2985 | .n (or .nlstr): value as newline-separated string. |
|
2976 | .n (or .nlstr): value as newline-separated string. | |
2986 | .s (or .spstr): value as whitespace-separated string. |
|
2977 | .s (or .spstr): value as whitespace-separated string. | |
2987 |
|
2978 | |||
2988 | This is very useful when trying to use such lists as arguments to |
|
2979 | This is very useful when trying to use such lists as arguments to | |
2989 | system commands.""" |
|
2980 | system commands.""" | |
2990 |
|
2981 | |||
2991 | if parameter_s: |
|
2982 | if parameter_s: | |
2992 | out = self.shell.getoutput(parameter_s) |
|
2983 | out = self.shell.getoutput(parameter_s) | |
2993 | if out is not None: |
|
2984 | if out is not None: | |
2994 | return SList(out.splitlines()) |
|
2985 | return SList(out.splitlines()) | |
2995 |
|
2986 | |||
2996 | def magic_r(self, parameter_s=''): |
|
2987 | def magic_r(self, parameter_s=''): | |
2997 | """Repeat previous input. |
|
2988 | """Repeat previous input. | |
2998 |
|
2989 | |||
2999 | Note: Consider using the more powerfull %rep instead! |
|
2990 | Note: Consider using the more powerfull %rep instead! | |
3000 |
|
2991 | |||
3001 | If given an argument, repeats the previous command which starts with |
|
2992 | If given an argument, repeats the previous command which starts with | |
3002 | the same string, otherwise it just repeats the previous input. |
|
2993 | the same string, otherwise it just repeats the previous input. | |
3003 |
|
2994 | |||
3004 | Shell escaped commands (with ! as first character) are not recognized |
|
2995 | Shell escaped commands (with ! as first character) are not recognized | |
3005 | by this system, only pure python code and magic commands. |
|
2996 | by this system, only pure python code and magic commands. | |
3006 | """ |
|
2997 | """ | |
3007 |
|
2998 | |||
3008 | start = parameter_s.strip() |
|
2999 | start = parameter_s.strip() | |
3009 | esc_magic = ESC_MAGIC |
|
3000 | esc_magic = ESC_MAGIC | |
3010 | # Identify magic commands even if automagic is on (which means |
|
3001 | # Identify magic commands even if automagic is on (which means | |
3011 | # the in-memory version is different from that typed by the user). |
|
3002 | # the in-memory version is different from that typed by the user). | |
3012 | if self.shell.automagic: |
|
3003 | if self.shell.automagic: | |
3013 | start_magic = esc_magic+start |
|
3004 | start_magic = esc_magic+start | |
3014 | else: |
|
3005 | else: | |
3015 | start_magic = start |
|
3006 | start_magic = start | |
3016 | # Look through the input history in reverse |
|
3007 | # Look through the input history in reverse | |
3017 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3008 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
3018 | input = self.shell.input_hist[n] |
|
3009 | input = self.shell.input_hist[n] | |
3019 | # skip plain 'r' lines so we don't recurse to infinity |
|
3010 | # skip plain 'r' lines so we don't recurse to infinity | |
3020 | if input != '_ip.magic("r")\n' and \ |
|
3011 | if input != '_ip.magic("r")\n' and \ | |
3021 | (input.startswith(start) or input.startswith(start_magic)): |
|
3012 | (input.startswith(start) or input.startswith(start_magic)): | |
3022 | #print 'match',`input` # dbg |
|
3013 | #print 'match',`input` # dbg | |
3023 | print 'Executing:',input, |
|
3014 | print 'Executing:',input, | |
3024 | self.shell.runlines(input) |
|
3015 | self.shell.runlines(input) | |
3025 | return |
|
3016 | return | |
3026 | print 'No previous input matching `%s` found.' % start |
|
3017 | print 'No previous input matching `%s` found.' % start | |
3027 |
|
3018 | |||
3028 |
|
3019 | |||
3029 | def magic_bookmark(self, parameter_s=''): |
|
3020 | def magic_bookmark(self, parameter_s=''): | |
3030 | """Manage IPython's bookmark system. |
|
3021 | """Manage IPython's bookmark system. | |
3031 |
|
3022 | |||
3032 | %bookmark <name> - set bookmark to current dir |
|
3023 | %bookmark <name> - set bookmark to current dir | |
3033 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3024 | %bookmark <name> <dir> - set bookmark to <dir> | |
3034 | %bookmark -l - list all bookmarks |
|
3025 | %bookmark -l - list all bookmarks | |
3035 | %bookmark -d <name> - remove bookmark |
|
3026 | %bookmark -d <name> - remove bookmark | |
3036 | %bookmark -r - remove all bookmarks |
|
3027 | %bookmark -r - remove all bookmarks | |
3037 |
|
3028 | |||
3038 | You can later on access a bookmarked folder with: |
|
3029 | You can later on access a bookmarked folder with: | |
3039 | %cd -b <name> |
|
3030 | %cd -b <name> | |
3040 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3031 | or simply '%cd <name>' if there is no directory called <name> AND | |
3041 | there is such a bookmark defined. |
|
3032 | there is such a bookmark defined. | |
3042 |
|
3033 | |||
3043 | Your bookmarks persist through IPython sessions, but they are |
|
3034 | Your bookmarks persist through IPython sessions, but they are | |
3044 | associated with each profile.""" |
|
3035 | associated with each profile.""" | |
3045 |
|
3036 | |||
3046 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3037 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3047 | if len(args) > 2: |
|
3038 | if len(args) > 2: | |
3048 | raise UsageError("%bookmark: too many arguments") |
|
3039 | raise UsageError("%bookmark: too many arguments") | |
3049 |
|
3040 | |||
3050 | bkms = self.db.get('bookmarks',{}) |
|
3041 | bkms = self.db.get('bookmarks',{}) | |
3051 |
|
3042 | |||
3052 | if opts.has_key('d'): |
|
3043 | if opts.has_key('d'): | |
3053 | try: |
|
3044 | try: | |
3054 | todel = args[0] |
|
3045 | todel = args[0] | |
3055 | except IndexError: |
|
3046 | except IndexError: | |
3056 | raise UsageError( |
|
3047 | raise UsageError( | |
3057 | "%bookmark -d: must provide a bookmark to delete") |
|
3048 | "%bookmark -d: must provide a bookmark to delete") | |
3058 | else: |
|
3049 | else: | |
3059 | try: |
|
3050 | try: | |
3060 | del bkms[todel] |
|
3051 | del bkms[todel] | |
3061 | except KeyError: |
|
3052 | except KeyError: | |
3062 | raise UsageError( |
|
3053 | raise UsageError( | |
3063 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3054 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3064 |
|
3055 | |||
3065 | elif opts.has_key('r'): |
|
3056 | elif opts.has_key('r'): | |
3066 | bkms = {} |
|
3057 | bkms = {} | |
3067 | elif opts.has_key('l'): |
|
3058 | elif opts.has_key('l'): | |
3068 | bks = bkms.keys() |
|
3059 | bks = bkms.keys() | |
3069 | bks.sort() |
|
3060 | bks.sort() | |
3070 | if bks: |
|
3061 | if bks: | |
3071 | size = max(map(len,bks)) |
|
3062 | size = max(map(len,bks)) | |
3072 | else: |
|
3063 | else: | |
3073 | size = 0 |
|
3064 | size = 0 | |
3074 | fmt = '%-'+str(size)+'s -> %s' |
|
3065 | fmt = '%-'+str(size)+'s -> %s' | |
3075 | print 'Current bookmarks:' |
|
3066 | print 'Current bookmarks:' | |
3076 | for bk in bks: |
|
3067 | for bk in bks: | |
3077 | print fmt % (bk,bkms[bk]) |
|
3068 | print fmt % (bk,bkms[bk]) | |
3078 | else: |
|
3069 | else: | |
3079 | if not args: |
|
3070 | if not args: | |
3080 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3071 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3081 | elif len(args)==1: |
|
3072 | elif len(args)==1: | |
3082 | bkms[args[0]] = os.getcwd() |
|
3073 | bkms[args[0]] = os.getcwd() | |
3083 | elif len(args)==2: |
|
3074 | elif len(args)==2: | |
3084 | bkms[args[0]] = args[1] |
|
3075 | bkms[args[0]] = args[1] | |
3085 | self.db['bookmarks'] = bkms |
|
3076 | self.db['bookmarks'] = bkms | |
3086 |
|
3077 | |||
3087 | def magic_pycat(self, parameter_s=''): |
|
3078 | def magic_pycat(self, parameter_s=''): | |
3088 | """Show a syntax-highlighted file through a pager. |
|
3079 | """Show a syntax-highlighted file through a pager. | |
3089 |
|
3080 | |||
3090 | This magic is similar to the cat utility, but it will assume the file |
|
3081 | This magic is similar to the cat utility, but it will assume the file | |
3091 | to be Python source and will show it with syntax highlighting. """ |
|
3082 | to be Python source and will show it with syntax highlighting. """ | |
3092 |
|
3083 | |||
3093 | try: |
|
3084 | try: | |
3094 | filename = get_py_filename(parameter_s) |
|
3085 | filename = get_py_filename(parameter_s) | |
3095 | cont = file_read(filename) |
|
3086 | cont = file_read(filename) | |
3096 | except IOError: |
|
3087 | except IOError: | |
3097 | try: |
|
3088 | try: | |
3098 | cont = eval(parameter_s,self.user_ns) |
|
3089 | cont = eval(parameter_s,self.user_ns) | |
3099 | except NameError: |
|
3090 | except NameError: | |
3100 | cont = None |
|
3091 | cont = None | |
3101 | if cont is None: |
|
3092 | if cont is None: | |
3102 | print "Error: no such file or variable" |
|
3093 | print "Error: no such file or variable" | |
3103 | return |
|
3094 | return | |
3104 |
|
3095 | |||
3105 | page.page(self.shell.pycolorize(cont)) |
|
3096 | page.page(self.shell.pycolorize(cont)) | |
3106 |
|
3097 | |||
3107 | def _rerun_pasted(self): |
|
3098 | def _rerun_pasted(self): | |
3108 | """ Rerun a previously pasted command. |
|
3099 | """ Rerun a previously pasted command. | |
3109 | """ |
|
3100 | """ | |
3110 | b = self.user_ns.get('pasted_block', None) |
|
3101 | b = self.user_ns.get('pasted_block', None) | |
3111 | if b is None: |
|
3102 | if b is None: | |
3112 | raise UsageError('No previous pasted block available') |
|
3103 | raise UsageError('No previous pasted block available') | |
3113 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3104 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3114 | exec b in self.user_ns |
|
3105 | exec b in self.user_ns | |
3115 |
|
3106 | |||
3116 | def _get_pasted_lines(self, sentinel): |
|
3107 | def _get_pasted_lines(self, sentinel): | |
3117 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3108 | """ Yield pasted lines until the user enters the given sentinel value. | |
3118 | """ |
|
3109 | """ | |
3119 | from IPython.core import interactiveshell |
|
3110 | from IPython.core import interactiveshell | |
3120 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3111 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3121 | while True: |
|
3112 | while True: | |
3122 | l = interactiveshell.raw_input_original(':') |
|
3113 | l = interactiveshell.raw_input_original(':') | |
3123 | if l == sentinel: |
|
3114 | if l == sentinel: | |
3124 | return |
|
3115 | return | |
3125 | else: |
|
3116 | else: | |
3126 | yield l |
|
3117 | yield l | |
3127 |
|
3118 | |||
3128 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3119 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3129 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3120 | """ Strip non-code parts of a sequence of lines to return a block of | |
3130 | code. |
|
3121 | code. | |
3131 | """ |
|
3122 | """ | |
3132 | # Regular expressions that declare text we strip from the input: |
|
3123 | # Regular expressions that declare text we strip from the input: | |
3133 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3124 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3134 | r'^\s*(\s?>)+', # Python input prompt |
|
3125 | r'^\s*(\s?>)+', # Python input prompt | |
3135 | r'^\s*\.{3,}', # Continuation prompts |
|
3126 | r'^\s*\.{3,}', # Continuation prompts | |
3136 | r'^\++', |
|
3127 | r'^\++', | |
3137 | ] |
|
3128 | ] | |
3138 |
|
3129 | |||
3139 | strip_from_start = map(re.compile,strip_re) |
|
3130 | strip_from_start = map(re.compile,strip_re) | |
3140 |
|
3131 | |||
3141 | lines = [] |
|
3132 | lines = [] | |
3142 | for l in raw_lines: |
|
3133 | for l in raw_lines: | |
3143 | for pat in strip_from_start: |
|
3134 | for pat in strip_from_start: | |
3144 | l = pat.sub('',l) |
|
3135 | l = pat.sub('',l) | |
3145 | lines.append(l) |
|
3136 | lines.append(l) | |
3146 |
|
3137 | |||
3147 | block = "\n".join(lines) + '\n' |
|
3138 | block = "\n".join(lines) + '\n' | |
3148 | #print "block:\n",block |
|
3139 | #print "block:\n",block | |
3149 | return block |
|
3140 | return block | |
3150 |
|
3141 | |||
3151 | def _execute_block(self, block, par): |
|
3142 | def _execute_block(self, block, par): | |
3152 | """ Execute a block, or store it in a variable, per the user's request. |
|
3143 | """ Execute a block, or store it in a variable, per the user's request. | |
3153 | """ |
|
3144 | """ | |
3154 | if not par: |
|
3145 | if not par: | |
3155 | b = textwrap.dedent(block) |
|
3146 | b = textwrap.dedent(block) | |
3156 | self.user_ns['pasted_block'] = b |
|
3147 | self.user_ns['pasted_block'] = b | |
3157 | exec b in self.user_ns |
|
3148 | exec b in self.user_ns | |
3158 | else: |
|
3149 | else: | |
3159 | self.user_ns[par] = SList(block.splitlines()) |
|
3150 | self.user_ns[par] = SList(block.splitlines()) | |
3160 | print "Block assigned to '%s'" % par |
|
3151 | print "Block assigned to '%s'" % par | |
3161 |
|
3152 | |||
3162 | def magic_cpaste(self, parameter_s=''): |
|
3153 | def magic_cpaste(self, parameter_s=''): | |
3163 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3154 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3164 |
|
3155 | |||
3165 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3156 | You must terminate the block with '--' (two minus-signs) alone on the | |
3166 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3157 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
3167 | is the new sentinel for this operation) |
|
3158 | is the new sentinel for this operation) | |
3168 |
|
3159 | |||
3169 | The block is dedented prior to execution to enable execution of method |
|
3160 | The block is dedented prior to execution to enable execution of method | |
3170 | definitions. '>' and '+' characters at the beginning of a line are |
|
3161 | definitions. '>' and '+' characters at the beginning of a line are | |
3171 | ignored, to allow pasting directly from e-mails, diff files and |
|
3162 | ignored, to allow pasting directly from e-mails, diff files and | |
3172 | doctests (the '...' continuation prompt is also stripped). The |
|
3163 | doctests (the '...' continuation prompt is also stripped). The | |
3173 | executed block is also assigned to variable named 'pasted_block' for |
|
3164 | executed block is also assigned to variable named 'pasted_block' for | |
3174 | later editing with '%edit pasted_block'. |
|
3165 | later editing with '%edit pasted_block'. | |
3175 |
|
3166 | |||
3176 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3167 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
3177 | This assigns the pasted block to variable 'foo' as string, without |
|
3168 | This assigns the pasted block to variable 'foo' as string, without | |
3178 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3169 | dedenting or executing it (preceding >>> and + is still stripped) | |
3179 |
|
3170 | |||
3180 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3171 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
3181 |
|
3172 | |||
3182 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3173 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
3183 | Just press enter and type -- (and press enter again) and the block |
|
3174 | Just press enter and type -- (and press enter again) and the block | |
3184 | will be what was just pasted. |
|
3175 | will be what was just pasted. | |
3185 |
|
3176 | |||
3186 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3177 | IPython statements (magics, shell escapes) are not supported (yet). | |
3187 |
|
3178 | |||
3188 | See also |
|
3179 | See also | |
3189 | -------- |
|
3180 | -------- | |
3190 | paste: automatically pull code from clipboard. |
|
3181 | paste: automatically pull code from clipboard. | |
3191 | """ |
|
3182 | """ | |
3192 |
|
3183 | |||
3193 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3184 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
3194 | par = args.strip() |
|
3185 | par = args.strip() | |
3195 | if opts.has_key('r'): |
|
3186 | if opts.has_key('r'): | |
3196 | self._rerun_pasted() |
|
3187 | self._rerun_pasted() | |
3197 | return |
|
3188 | return | |
3198 |
|
3189 | |||
3199 | sentinel = opts.get('s','--') |
|
3190 | sentinel = opts.get('s','--') | |
3200 |
|
3191 | |||
3201 | block = self._strip_pasted_lines_for_code( |
|
3192 | block = self._strip_pasted_lines_for_code( | |
3202 | self._get_pasted_lines(sentinel)) |
|
3193 | self._get_pasted_lines(sentinel)) | |
3203 |
|
3194 | |||
3204 | self._execute_block(block, par) |
|
3195 | self._execute_block(block, par) | |
3205 |
|
3196 | |||
3206 | def magic_paste(self, parameter_s=''): |
|
3197 | def magic_paste(self, parameter_s=''): | |
3207 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3198 | """Allows you to paste & execute a pre-formatted code block from clipboard. | |
3208 |
|
3199 | |||
3209 | The text is pulled directly from the clipboard without user |
|
3200 | The text is pulled directly from the clipboard without user | |
3210 | intervention and printed back on the screen before execution (unless |
|
3201 | intervention and printed back on the screen before execution (unless | |
3211 | the -q flag is given to force quiet mode). |
|
3202 | the -q flag is given to force quiet mode). | |
3212 |
|
3203 | |||
3213 | The block is dedented prior to execution to enable execution of method |
|
3204 | The block is dedented prior to execution to enable execution of method | |
3214 | definitions. '>' and '+' characters at the beginning of a line are |
|
3205 | definitions. '>' and '+' characters at the beginning of a line are | |
3215 | ignored, to allow pasting directly from e-mails, diff files and |
|
3206 | ignored, to allow pasting directly from e-mails, diff files and | |
3216 | doctests (the '...' continuation prompt is also stripped). The |
|
3207 | doctests (the '...' continuation prompt is also stripped). The | |
3217 | executed block is also assigned to variable named 'pasted_block' for |
|
3208 | executed block is also assigned to variable named 'pasted_block' for | |
3218 | later editing with '%edit pasted_block'. |
|
3209 | later editing with '%edit pasted_block'. | |
3219 |
|
3210 | |||
3220 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3211 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
3221 | This assigns the pasted block to variable 'foo' as string, without |
|
3212 | This assigns the pasted block to variable 'foo' as string, without | |
3222 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3213 | dedenting or executing it (preceding >>> and + is still stripped) | |
3223 |
|
3214 | |||
3224 | Options |
|
3215 | Options | |
3225 | ------- |
|
3216 | ------- | |
3226 |
|
3217 | |||
3227 | -r: re-executes the block previously entered by cpaste. |
|
3218 | -r: re-executes the block previously entered by cpaste. | |
3228 |
|
3219 | |||
3229 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
3220 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
3230 |
|
3221 | |||
3231 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3222 | IPython statements (magics, shell escapes) are not supported (yet). | |
3232 |
|
3223 | |||
3233 | See also |
|
3224 | See also | |
3234 | -------- |
|
3225 | -------- | |
3235 | cpaste: manually paste code into terminal until you mark its end. |
|
3226 | cpaste: manually paste code into terminal until you mark its end. | |
3236 | """ |
|
3227 | """ | |
3237 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
3228 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |
3238 | par = args.strip() |
|
3229 | par = args.strip() | |
3239 | if opts.has_key('r'): |
|
3230 | if opts.has_key('r'): | |
3240 | self._rerun_pasted() |
|
3231 | self._rerun_pasted() | |
3241 | return |
|
3232 | return | |
3242 |
|
3233 | |||
3243 | text = self.shell.hooks.clipboard_get() |
|
3234 | text = self.shell.hooks.clipboard_get() | |
3244 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3235 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
3245 |
|
3236 | |||
3246 | # By default, echo back to terminal unless quiet mode is requested |
|
3237 | # By default, echo back to terminal unless quiet mode is requested | |
3247 | if not opts.has_key('q'): |
|
3238 | if not opts.has_key('q'): | |
3248 | write = self.shell.write |
|
3239 | write = self.shell.write | |
3249 | write(self.shell.pycolorize(block)) |
|
3240 | write(self.shell.pycolorize(block)) | |
3250 | if not block.endswith('\n'): |
|
3241 | if not block.endswith('\n'): | |
3251 | write('\n') |
|
3242 | write('\n') | |
3252 | write("## -- End pasted text --\n") |
|
3243 | write("## -- End pasted text --\n") | |
3253 |
|
3244 | |||
3254 | self._execute_block(block, par) |
|
3245 | self._execute_block(block, par) | |
3255 |
|
3246 | |||
3256 | def magic_quickref(self,arg): |
|
3247 | def magic_quickref(self,arg): | |
3257 | """ Show a quick reference sheet """ |
|
3248 | """ Show a quick reference sheet """ | |
3258 | import IPython.core.usage |
|
3249 | import IPython.core.usage | |
3259 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3250 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3260 |
|
3251 | |||
3261 | page.page(qr) |
|
3252 | page.page(qr) | |
3262 |
|
3253 | |||
3263 | def magic_doctest_mode(self,parameter_s=''): |
|
3254 | def magic_doctest_mode(self,parameter_s=''): | |
3264 | """Toggle doctest mode on and off. |
|
3255 | """Toggle doctest mode on and off. | |
3265 |
|
3256 | |||
3266 | This mode allows you to toggle the prompt behavior between normal |
|
3257 | This mode allows you to toggle the prompt behavior between normal | |
3267 | IPython prompts and ones that are as similar to the default IPython |
|
3258 | IPython prompts and ones that are as similar to the default IPython | |
3268 | interpreter as possible. |
|
3259 | interpreter as possible. | |
3269 |
|
3260 | |||
3270 | It also supports the pasting of code snippets that have leading '>>>' |
|
3261 | It also supports the pasting of code snippets that have leading '>>>' | |
3271 | and '...' prompts in them. This means that you can paste doctests from |
|
3262 | and '...' prompts in them. This means that you can paste doctests from | |
3272 | files or docstrings (even if they have leading whitespace), and the |
|
3263 | files or docstrings (even if they have leading whitespace), and the | |
3273 | code will execute correctly. You can then use '%history -tn' to see |
|
3264 | code will execute correctly. You can then use '%history -tn' to see | |
3274 | the translated history without line numbers; this will give you the |
|
3265 | the translated history without line numbers; this will give you the | |
3275 | input after removal of all the leading prompts and whitespace, which |
|
3266 | input after removal of all the leading prompts and whitespace, which | |
3276 | can be pasted back into an editor. |
|
3267 | can be pasted back into an editor. | |
3277 |
|
3268 | |||
3278 | With these features, you can switch into this mode easily whenever you |
|
3269 | With these features, you can switch into this mode easily whenever you | |
3279 | need to do testing and changes to doctests, without having to leave |
|
3270 | need to do testing and changes to doctests, without having to leave | |
3280 | your existing IPython session. |
|
3271 | your existing IPython session. | |
3281 | """ |
|
3272 | """ | |
3282 |
|
3273 | |||
3283 | from IPython.utils.ipstruct import Struct |
|
3274 | from IPython.utils.ipstruct import Struct | |
3284 |
|
3275 | |||
3285 | # Shorthands |
|
3276 | # Shorthands | |
3286 | shell = self.shell |
|
3277 | shell = self.shell | |
3287 | oc = shell.displayhook |
|
3278 | oc = shell.displayhook | |
3288 | meta = shell.meta |
|
3279 | meta = shell.meta | |
3289 | # dstore is a data store kept in the instance metadata bag to track any |
|
3280 | # dstore is a data store kept in the instance metadata bag to track any | |
3290 | # changes we make, so we can undo them later. |
|
3281 | # changes we make, so we can undo them later. | |
3291 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3282 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3292 | save_dstore = dstore.setdefault |
|
3283 | save_dstore = dstore.setdefault | |
3293 |
|
3284 | |||
3294 | # save a few values we'll need to recover later |
|
3285 | # save a few values we'll need to recover later | |
3295 | mode = save_dstore('mode',False) |
|
3286 | mode = save_dstore('mode',False) | |
3296 | save_dstore('rc_pprint',shell.pprint) |
|
3287 | save_dstore('rc_pprint',shell.pprint) | |
3297 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3288 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3298 | save_dstore('rc_separate_out',shell.separate_out) |
|
3289 | save_dstore('rc_separate_out',shell.separate_out) | |
3299 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3290 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3300 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3291 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3301 | save_dstore('rc_separate_in',shell.separate_in) |
|
3292 | save_dstore('rc_separate_in',shell.separate_in) | |
3302 |
|
3293 | |||
3303 | if mode == False: |
|
3294 | if mode == False: | |
3304 | # turn on |
|
3295 | # turn on | |
3305 | oc.prompt1.p_template = '>>> ' |
|
3296 | oc.prompt1.p_template = '>>> ' | |
3306 | oc.prompt2.p_template = '... ' |
|
3297 | oc.prompt2.p_template = '... ' | |
3307 | oc.prompt_out.p_template = '' |
|
3298 | oc.prompt_out.p_template = '' | |
3308 |
|
3299 | |||
3309 | # Prompt separators like plain python |
|
3300 | # Prompt separators like plain python | |
3310 | oc.input_sep = oc.prompt1.sep = '' |
|
3301 | oc.input_sep = oc.prompt1.sep = '' | |
3311 | oc.output_sep = '' |
|
3302 | oc.output_sep = '' | |
3312 | oc.output_sep2 = '' |
|
3303 | oc.output_sep2 = '' | |
3313 |
|
3304 | |||
3314 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3305 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3315 | oc.prompt_out.pad_left = False |
|
3306 | oc.prompt_out.pad_left = False | |
3316 |
|
3307 | |||
3317 | shell.pprint = False |
|
3308 | shell.pprint = False | |
3318 |
|
3309 | |||
3319 | shell.magic_xmode('Plain') |
|
3310 | shell.magic_xmode('Plain') | |
3320 |
|
3311 | |||
3321 | else: |
|
3312 | else: | |
3322 | # turn off |
|
3313 | # turn off | |
3323 | oc.prompt1.p_template = shell.prompt_in1 |
|
3314 | oc.prompt1.p_template = shell.prompt_in1 | |
3324 | oc.prompt2.p_template = shell.prompt_in2 |
|
3315 | oc.prompt2.p_template = shell.prompt_in2 | |
3325 | oc.prompt_out.p_template = shell.prompt_out |
|
3316 | oc.prompt_out.p_template = shell.prompt_out | |
3326 |
|
3317 | |||
3327 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3318 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3328 |
|
3319 | |||
3329 | oc.output_sep = dstore.rc_separate_out |
|
3320 | oc.output_sep = dstore.rc_separate_out | |
3330 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3321 | oc.output_sep2 = dstore.rc_separate_out2 | |
3331 |
|
3322 | |||
3332 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3323 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3333 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3324 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3334 |
|
3325 | |||
3335 | shell.pprint = dstore.rc_pprint |
|
3326 | shell.pprint = dstore.rc_pprint | |
3336 |
|
3327 | |||
3337 | shell.magic_xmode(dstore.xmode) |
|
3328 | shell.magic_xmode(dstore.xmode) | |
3338 |
|
3329 | |||
3339 | # Store new mode and inform |
|
3330 | # Store new mode and inform | |
3340 | dstore.mode = bool(1-int(mode)) |
|
3331 | dstore.mode = bool(1-int(mode)) | |
3341 | print 'Doctest mode is:', |
|
3332 | print 'Doctest mode is:', | |
3342 | print ['OFF','ON'][dstore.mode] |
|
3333 | print ['OFF','ON'][dstore.mode] | |
3343 |
|
3334 | |||
3344 | def magic_gui(self, parameter_s=''): |
|
3335 | def magic_gui(self, parameter_s=''): | |
3345 | """Enable or disable IPython GUI event loop integration. |
|
3336 | """Enable or disable IPython GUI event loop integration. | |
3346 |
|
3337 | |||
3347 | %gui [GUINAME] |
|
3338 | %gui [GUINAME] | |
3348 |
|
3339 | |||
3349 | This magic replaces IPython's threaded shells that were activated |
|
3340 | This magic replaces IPython's threaded shells that were activated | |
3350 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3341 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3351 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3342 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3352 | interrupts should work without any problems. The following toolkits |
|
3343 | interrupts should work without any problems. The following toolkits | |
3353 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3344 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3354 |
|
3345 | |||
3355 | %gui wx # enable wxPython event loop integration |
|
3346 | %gui wx # enable wxPython event loop integration | |
3356 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3347 | %gui qt4|qt # enable PyQt4 event loop integration | |
3357 | %gui gtk # enable PyGTK event loop integration |
|
3348 | %gui gtk # enable PyGTK event loop integration | |
3358 | %gui tk # enable Tk event loop integration |
|
3349 | %gui tk # enable Tk event loop integration | |
3359 | %gui # disable all event loop integration |
|
3350 | %gui # disable all event loop integration | |
3360 |
|
3351 | |||
3361 | WARNING: after any of these has been called you can simply create |
|
3352 | WARNING: after any of these has been called you can simply create | |
3362 | an application object, but DO NOT start the event loop yourself, as |
|
3353 | an application object, but DO NOT start the event loop yourself, as | |
3363 | we have already handled that. |
|
3354 | we have already handled that. | |
3364 | """ |
|
3355 | """ | |
3365 | from IPython.lib.inputhook import enable_gui |
|
3356 | from IPython.lib.inputhook import enable_gui | |
3366 | opts, arg = self.parse_options(parameter_s='') |
|
3357 | opts, arg = self.parse_options(parameter_s='') | |
3367 | if arg=='': arg = None |
|
3358 | if arg=='': arg = None | |
3368 | return enable_gui(arg) |
|
3359 | return enable_gui(arg) | |
3369 |
|
3360 | |||
3370 | def magic_load_ext(self, module_str): |
|
3361 | def magic_load_ext(self, module_str): | |
3371 | """Load an IPython extension by its module name.""" |
|
3362 | """Load an IPython extension by its module name.""" | |
3372 | return self.extension_manager.load_extension(module_str) |
|
3363 | return self.extension_manager.load_extension(module_str) | |
3373 |
|
3364 | |||
3374 | def magic_unload_ext(self, module_str): |
|
3365 | def magic_unload_ext(self, module_str): | |
3375 | """Unload an IPython extension by its module name.""" |
|
3366 | """Unload an IPython extension by its module name.""" | |
3376 | self.extension_manager.unload_extension(module_str) |
|
3367 | self.extension_manager.unload_extension(module_str) | |
3377 |
|
3368 | |||
3378 | def magic_reload_ext(self, module_str): |
|
3369 | def magic_reload_ext(self, module_str): | |
3379 | """Reload an IPython extension by its module name.""" |
|
3370 | """Reload an IPython extension by its module name.""" | |
3380 | self.extension_manager.reload_extension(module_str) |
|
3371 | self.extension_manager.reload_extension(module_str) | |
3381 |
|
3372 | |||
3382 | @testdec.skip_doctest |
|
3373 | @testdec.skip_doctest | |
3383 | def magic_install_profiles(self, s): |
|
3374 | def magic_install_profiles(self, s): | |
3384 | """Install the default IPython profiles into the .ipython dir. |
|
3375 | """Install the default IPython profiles into the .ipython dir. | |
3385 |
|
3376 | |||
3386 | If the default profiles have already been installed, they will not |
|
3377 | If the default profiles have already been installed, they will not | |
3387 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3378 | be overwritten. You can force overwriting them by using the ``-o`` | |
3388 | option:: |
|
3379 | option:: | |
3389 |
|
3380 | |||
3390 | In [1]: %install_profiles -o |
|
3381 | In [1]: %install_profiles -o | |
3391 | """ |
|
3382 | """ | |
3392 | if '-o' in s: |
|
3383 | if '-o' in s: | |
3393 | overwrite = True |
|
3384 | overwrite = True | |
3394 | else: |
|
3385 | else: | |
3395 | overwrite = False |
|
3386 | overwrite = False | |
3396 | from IPython.config import profile |
|
3387 | from IPython.config import profile | |
3397 | profile_dir = os.path.split(profile.__file__)[0] |
|
3388 | profile_dir = os.path.split(profile.__file__)[0] | |
3398 | ipython_dir = self.ipython_dir |
|
3389 | ipython_dir = self.ipython_dir | |
3399 | files = os.listdir(profile_dir) |
|
3390 | files = os.listdir(profile_dir) | |
3400 |
|
3391 | |||
3401 | to_install = [] |
|
3392 | to_install = [] | |
3402 | for f in files: |
|
3393 | for f in files: | |
3403 | if f.startswith('ipython_config'): |
|
3394 | if f.startswith('ipython_config'): | |
3404 | src = os.path.join(profile_dir, f) |
|
3395 | src = os.path.join(profile_dir, f) | |
3405 | dst = os.path.join(ipython_dir, f) |
|
3396 | dst = os.path.join(ipython_dir, f) | |
3406 | if (not os.path.isfile(dst)) or overwrite: |
|
3397 | if (not os.path.isfile(dst)) or overwrite: | |
3407 | to_install.append((f, src, dst)) |
|
3398 | to_install.append((f, src, dst)) | |
3408 | if len(to_install)>0: |
|
3399 | if len(to_install)>0: | |
3409 | print "Installing profiles to: ", ipython_dir |
|
3400 | print "Installing profiles to: ", ipython_dir | |
3410 | for (f, src, dst) in to_install: |
|
3401 | for (f, src, dst) in to_install: | |
3411 | shutil.copy(src, dst) |
|
3402 | shutil.copy(src, dst) | |
3412 | print " %s" % f |
|
3403 | print " %s" % f | |
3413 |
|
3404 | |||
3414 | def magic_install_default_config(self, s): |
|
3405 | def magic_install_default_config(self, s): | |
3415 | """Install IPython's default config file into the .ipython dir. |
|
3406 | """Install IPython's default config file into the .ipython dir. | |
3416 |
|
3407 | |||
3417 | If the default config file (:file:`ipython_config.py`) is already |
|
3408 | If the default config file (:file:`ipython_config.py`) is already | |
3418 | installed, it will not be overwritten. You can force overwriting |
|
3409 | installed, it will not be overwritten. You can force overwriting | |
3419 | by using the ``-o`` option:: |
|
3410 | by using the ``-o`` option:: | |
3420 |
|
3411 | |||
3421 | In [1]: %install_default_config |
|
3412 | In [1]: %install_default_config | |
3422 | """ |
|
3413 | """ | |
3423 | if '-o' in s: |
|
3414 | if '-o' in s: | |
3424 | overwrite = True |
|
3415 | overwrite = True | |
3425 | else: |
|
3416 | else: | |
3426 | overwrite = False |
|
3417 | overwrite = False | |
3427 | from IPython.config import default |
|
3418 | from IPython.config import default | |
3428 | config_dir = os.path.split(default.__file__)[0] |
|
3419 | config_dir = os.path.split(default.__file__)[0] | |
3429 | ipython_dir = self.ipython_dir |
|
3420 | ipython_dir = self.ipython_dir | |
3430 | default_config_file_name = 'ipython_config.py' |
|
3421 | default_config_file_name = 'ipython_config.py' | |
3431 | src = os.path.join(config_dir, default_config_file_name) |
|
3422 | src = os.path.join(config_dir, default_config_file_name) | |
3432 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3423 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3433 | if (not os.path.isfile(dst)) or overwrite: |
|
3424 | if (not os.path.isfile(dst)) or overwrite: | |
3434 | shutil.copy(src, dst) |
|
3425 | shutil.copy(src, dst) | |
3435 | print "Installing default config file: %s" % dst |
|
3426 | print "Installing default config file: %s" % dst | |
3436 |
|
3427 | |||
3437 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3428 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3438 | # handling and modify slightly %run |
|
3429 | # handling and modify slightly %run | |
3439 |
|
3430 | |||
3440 | @testdec.skip_doctest |
|
3431 | @testdec.skip_doctest | |
3441 | def _pylab_magic_run(self, parameter_s=''): |
|
3432 | def _pylab_magic_run(self, parameter_s=''): | |
3442 | Magic.magic_run(self, parameter_s, |
|
3433 | Magic.magic_run(self, parameter_s, | |
3443 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3434 | runner=mpl_runner(self.shell.safe_execfile)) | |
3444 |
|
3435 | |||
3445 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3436 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3446 |
|
3437 | |||
3447 | @testdec.skip_doctest |
|
3438 | @testdec.skip_doctest | |
3448 | def magic_pylab(self, s): |
|
3439 | def magic_pylab(self, s): | |
3449 | """Load numpy and matplotlib to work interactively. |
|
3440 | """Load numpy and matplotlib to work interactively. | |
3450 |
|
3441 | |||
3451 | %pylab [GUINAME] |
|
3442 | %pylab [GUINAME] | |
3452 |
|
3443 | |||
3453 | This function lets you activate pylab (matplotlib, numpy and |
|
3444 | This function lets you activate pylab (matplotlib, numpy and | |
3454 | interactive support) at any point during an IPython session. |
|
3445 | interactive support) at any point during an IPython session. | |
3455 |
|
3446 | |||
3456 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3447 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3457 | pylab and mlab, as well as all names from numpy and pylab. |
|
3448 | pylab and mlab, as well as all names from numpy and pylab. | |
3458 |
|
3449 | |||
3459 | Parameters |
|
3450 | Parameters | |
3460 | ---------- |
|
3451 | ---------- | |
3461 | guiname : optional |
|
3452 | guiname : optional | |
3462 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3453 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3463 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3454 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3464 | otherwise matplotlib's default (which you can override in your |
|
3455 | otherwise matplotlib's default (which you can override in your | |
3465 | matplotlib config file) is used. |
|
3456 | matplotlib config file) is used. | |
3466 |
|
3457 | |||
3467 | Examples |
|
3458 | Examples | |
3468 | -------- |
|
3459 | -------- | |
3469 | In this case, where the MPL default is TkAgg: |
|
3460 | In this case, where the MPL default is TkAgg: | |
3470 | In [2]: %pylab |
|
3461 | In [2]: %pylab | |
3471 |
|
3462 | |||
3472 | Welcome to pylab, a matplotlib-based Python environment. |
|
3463 | Welcome to pylab, a matplotlib-based Python environment. | |
3473 | Backend in use: TkAgg |
|
3464 | Backend in use: TkAgg | |
3474 | For more information, type 'help(pylab)'. |
|
3465 | For more information, type 'help(pylab)'. | |
3475 |
|
3466 | |||
3476 | But you can explicitly request a different backend: |
|
3467 | But you can explicitly request a different backend: | |
3477 | In [3]: %pylab qt |
|
3468 | In [3]: %pylab qt | |
3478 |
|
3469 | |||
3479 | Welcome to pylab, a matplotlib-based Python environment. |
|
3470 | Welcome to pylab, a matplotlib-based Python environment. | |
3480 | Backend in use: Qt4Agg |
|
3471 | Backend in use: Qt4Agg | |
3481 | For more information, type 'help(pylab)'. |
|
3472 | For more information, type 'help(pylab)'. | |
3482 | """ |
|
3473 | """ | |
3483 | self.shell.enable_pylab(s) |
|
3474 | self.shell.enable_pylab(s) | |
3484 |
|
3475 | |||
3485 | def magic_tb(self, s): |
|
3476 | def magic_tb(self, s): | |
3486 | """Print the last traceback with the currently active exception mode. |
|
3477 | """Print the last traceback with the currently active exception mode. | |
3487 |
|
3478 | |||
3488 | See %xmode for changing exception reporting modes.""" |
|
3479 | See %xmode for changing exception reporting modes.""" | |
3489 | self.shell.showtraceback() |
|
3480 | self.shell.showtraceback() | |
3490 |
|
3481 | |||
3491 | # end Magic |
|
3482 | # end Magic |
@@ -1,609 +1,609 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tools for inspecting Python objects. |
|
2 | """Tools for inspecting Python objects. | |
3 |
|
3 | |||
4 | Uses syntax highlighting for presenting the various information elements. |
|
4 | Uses syntax highlighting for presenting the various information elements. | |
5 |
|
5 | |||
6 | Similar in spirit to the inspect module, but all calls take a name argument to |
|
6 | Similar in spirit to the inspect module, but all calls take a name argument to | |
7 | reference the name under which an object is being read. |
|
7 | reference the name under which an object is being read. | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
11 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | __all__ = ['Inspector','InspectColors'] |
|
17 | __all__ = ['Inspector','InspectColors'] | |
18 |
|
18 | |||
19 | # stdlib modules |
|
19 | # stdlib modules | |
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import StringIO |
|
21 | import StringIO | |
22 | import inspect |
|
22 | import inspect | |
23 | import linecache |
|
23 | import linecache | |
24 | import os |
|
24 | import os | |
25 | import string |
|
25 | import string | |
26 | import sys |
|
26 | import sys | |
27 | import types |
|
27 | import types | |
28 |
|
28 | |||
29 | # IPython's own |
|
29 | # IPython's own | |
30 | from IPython.core import page |
|
30 | from IPython.core import page | |
31 | from IPython.external.Itpl import itpl |
|
31 | from IPython.external.Itpl import itpl | |
32 | from IPython.utils import PyColorize |
|
32 | from IPython.utils import PyColorize | |
33 | import IPython.utils.io |
|
33 | import IPython.utils.io | |
34 | from IPython.utils.text import indent |
|
34 | from IPython.utils.text import indent | |
35 | from IPython.utils.wildcard import list_namespace |
|
35 | from IPython.utils.wildcard import list_namespace | |
36 | from IPython.utils.coloransi import * |
|
36 | from IPython.utils.coloransi import * | |
37 |
|
37 | |||
38 | #**************************************************************************** |
|
38 | #**************************************************************************** | |
39 | # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We |
|
39 | # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We | |
40 | # simply monkeypatch inspect with code copied from python 2.4. |
|
40 | # simply monkeypatch inspect with code copied from python 2.4. | |
41 | if sys.version_info[:2] == (2,3): |
|
41 | if sys.version_info[:2] == (2,3): | |
42 | from inspect import ismodule, getabsfile, modulesbyfile |
|
42 | from inspect import ismodule, getabsfile, modulesbyfile | |
43 | def getmodule(object): |
|
43 | def getmodule(object): | |
44 | """Return the module an object was defined in, or None if not found.""" |
|
44 | """Return the module an object was defined in, or None if not found.""" | |
45 | if ismodule(object): |
|
45 | if ismodule(object): | |
46 | return object |
|
46 | return object | |
47 | if hasattr(object, '__module__'): |
|
47 | if hasattr(object, '__module__'): | |
48 | return sys.modules.get(object.__module__) |
|
48 | return sys.modules.get(object.__module__) | |
49 | try: |
|
49 | try: | |
50 | file = getabsfile(object) |
|
50 | file = getabsfile(object) | |
51 | except TypeError: |
|
51 | except TypeError: | |
52 | return None |
|
52 | return None | |
53 | if file in modulesbyfile: |
|
53 | if file in modulesbyfile: | |
54 | return sys.modules.get(modulesbyfile[file]) |
|
54 | return sys.modules.get(modulesbyfile[file]) | |
55 | for module in sys.modules.values(): |
|
55 | for module in sys.modules.values(): | |
56 | if hasattr(module, '__file__'): |
|
56 | if hasattr(module, '__file__'): | |
57 | modulesbyfile[ |
|
57 | modulesbyfile[ | |
58 | os.path.realpath( |
|
58 | os.path.realpath( | |
59 | getabsfile(module))] = module.__name__ |
|
59 | getabsfile(module))] = module.__name__ | |
60 | if file in modulesbyfile: |
|
60 | if file in modulesbyfile: | |
61 | return sys.modules.get(modulesbyfile[file]) |
|
61 | return sys.modules.get(modulesbyfile[file]) | |
62 | main = sys.modules['__main__'] |
|
62 | main = sys.modules['__main__'] | |
63 | if not hasattr(object, '__name__'): |
|
63 | if not hasattr(object, '__name__'): | |
64 | return None |
|
64 | return None | |
65 | if hasattr(main, object.__name__): |
|
65 | if hasattr(main, object.__name__): | |
66 | mainobject = getattr(main, object.__name__) |
|
66 | mainobject = getattr(main, object.__name__) | |
67 | if mainobject is object: |
|
67 | if mainobject is object: | |
68 | return main |
|
68 | return main | |
69 | builtin = sys.modules['__builtin__'] |
|
69 | builtin = sys.modules['__builtin__'] | |
70 | if hasattr(builtin, object.__name__): |
|
70 | if hasattr(builtin, object.__name__): | |
71 | builtinobject = getattr(builtin, object.__name__) |
|
71 | builtinobject = getattr(builtin, object.__name__) | |
72 | if builtinobject is object: |
|
72 | if builtinobject is object: | |
73 | return builtin |
|
73 | return builtin | |
74 |
|
74 | |||
75 | inspect.getmodule = getmodule |
|
75 | inspect.getmodule = getmodule | |
76 |
|
76 | |||
77 | #**************************************************************************** |
|
77 | #**************************************************************************** | |
78 | # Builtin color schemes |
|
78 | # Builtin color schemes | |
79 |
|
79 | |||
80 | Colors = TermColors # just a shorthand |
|
80 | Colors = TermColors # just a shorthand | |
81 |
|
81 | |||
82 | # Build a few color schemes |
|
82 | # Build a few color schemes | |
83 | NoColor = ColorScheme( |
|
83 | NoColor = ColorScheme( | |
84 | 'NoColor',{ |
|
84 | 'NoColor',{ | |
85 | 'header' : Colors.NoColor, |
|
85 | 'header' : Colors.NoColor, | |
86 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) |
|
86 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) | |
87 | } ) |
|
87 | } ) | |
88 |
|
88 | |||
89 | LinuxColors = ColorScheme( |
|
89 | LinuxColors = ColorScheme( | |
90 | 'Linux',{ |
|
90 | 'Linux',{ | |
91 | 'header' : Colors.LightRed, |
|
91 | 'header' : Colors.LightRed, | |
92 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
92 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) | |
93 | } ) |
|
93 | } ) | |
94 |
|
94 | |||
95 | LightBGColors = ColorScheme( |
|
95 | LightBGColors = ColorScheme( | |
96 | 'LightBG',{ |
|
96 | 'LightBG',{ | |
97 | 'header' : Colors.Red, |
|
97 | 'header' : Colors.Red, | |
98 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
98 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) | |
99 | } ) |
|
99 | } ) | |
100 |
|
100 | |||
101 | # Build table of color schemes (needed by the parser) |
|
101 | # Build table of color schemes (needed by the parser) | |
102 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], |
|
102 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], | |
103 | 'Linux') |
|
103 | 'Linux') | |
104 |
|
104 | |||
105 | #**************************************************************************** |
|
105 | #**************************************************************************** | |
106 | # Auxiliary functions |
|
106 | # Auxiliary functions | |
107 | def getdoc(obj): |
|
107 | def getdoc(obj): | |
108 | """Stable wrapper around inspect.getdoc. |
|
108 | """Stable wrapper around inspect.getdoc. | |
109 |
|
109 | |||
110 | This can't crash because of attribute problems. |
|
110 | This can't crash because of attribute problems. | |
111 |
|
111 | |||
112 | It also attempts to call a getdoc() method on the given object. This |
|
112 | It also attempts to call a getdoc() method on the given object. This | |
113 | allows objects which provide their docstrings via non-standard mechanisms |
|
113 | allows objects which provide their docstrings via non-standard mechanisms | |
114 | (like Pyro proxies) to still be inspected by ipython's ? system.""" |
|
114 | (like Pyro proxies) to still be inspected by ipython's ? system.""" | |
115 |
|
115 | |||
116 | ds = None # default return value |
|
116 | ds = None # default return value | |
117 | try: |
|
117 | try: | |
118 | ds = inspect.getdoc(obj) |
|
118 | ds = inspect.getdoc(obj) | |
119 | except: |
|
119 | except: | |
120 | # Harden against an inspect failure, which can occur with |
|
120 | # Harden against an inspect failure, which can occur with | |
121 | # SWIG-wrapped extensions. |
|
121 | # SWIG-wrapped extensions. | |
122 | pass |
|
122 | pass | |
123 | # Allow objects to offer customized documentation via a getdoc method: |
|
123 | # Allow objects to offer customized documentation via a getdoc method: | |
124 | try: |
|
124 | try: | |
125 | ds2 = obj.getdoc() |
|
125 | ds2 = obj.getdoc() | |
126 | except: |
|
126 | except: | |
127 | pass |
|
127 | pass | |
128 | else: |
|
128 | else: | |
129 | # if we get extra info, we add it to the normal docstring. |
|
129 | # if we get extra info, we add it to the normal docstring. | |
130 | if ds is None: |
|
130 | if ds is None: | |
131 | ds = ds2 |
|
131 | ds = ds2 | |
132 | else: |
|
132 | else: | |
133 | ds = '%s\n%s' % (ds,ds2) |
|
133 | ds = '%s\n%s' % (ds,ds2) | |
134 | return ds |
|
134 | return ds | |
135 |
|
135 | |||
136 |
|
136 | |||
137 | def getsource(obj,is_binary=False): |
|
137 | def getsource(obj,is_binary=False): | |
138 | """Wrapper around inspect.getsource. |
|
138 | """Wrapper around inspect.getsource. | |
139 |
|
139 | |||
140 | This can be modified by other projects to provide customized source |
|
140 | This can be modified by other projects to provide customized source | |
141 | extraction. |
|
141 | extraction. | |
142 |
|
142 | |||
143 | Inputs: |
|
143 | Inputs: | |
144 |
|
144 | |||
145 | - obj: an object whose source code we will attempt to extract. |
|
145 | - obj: an object whose source code we will attempt to extract. | |
146 |
|
146 | |||
147 | Optional inputs: |
|
147 | Optional inputs: | |
148 |
|
148 | |||
149 | - is_binary: whether the object is known to come from a binary source. |
|
149 | - is_binary: whether the object is known to come from a binary source. | |
150 | This implementation will skip returning any output for binary objects, but |
|
150 | This implementation will skip returning any output for binary objects, but | |
151 | custom extractors may know how to meaningfully process them.""" |
|
151 | custom extractors may know how to meaningfully process them.""" | |
152 |
|
152 | |||
153 | if is_binary: |
|
153 | if is_binary: | |
154 | return None |
|
154 | return None | |
155 | else: |
|
155 | else: | |
156 | try: |
|
156 | try: | |
157 | src = inspect.getsource(obj) |
|
157 | src = inspect.getsource(obj) | |
158 | except TypeError: |
|
158 | except TypeError: | |
159 | if hasattr(obj,'__class__'): |
|
159 | if hasattr(obj,'__class__'): | |
160 | src = inspect.getsource(obj.__class__) |
|
160 | src = inspect.getsource(obj.__class__) | |
161 | return src |
|
161 | return src | |
162 |
|
162 | |||
163 | def getargspec(obj): |
|
163 | def getargspec(obj): | |
164 | """Get the names and default values of a function's arguments. |
|
164 | """Get the names and default values of a function's arguments. | |
165 |
|
165 | |||
166 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
166 | A tuple of four things is returned: (args, varargs, varkw, defaults). | |
167 | 'args' is a list of the argument names (it may contain nested lists). |
|
167 | 'args' is a list of the argument names (it may contain nested lists). | |
168 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
168 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. | |
169 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
169 | 'defaults' is an n-tuple of the default values of the last n arguments. | |
170 |
|
170 | |||
171 | Modified version of inspect.getargspec from the Python Standard |
|
171 | Modified version of inspect.getargspec from the Python Standard | |
172 | Library.""" |
|
172 | Library.""" | |
173 |
|
173 | |||
174 | if inspect.isfunction(obj): |
|
174 | if inspect.isfunction(obj): | |
175 | func_obj = obj |
|
175 | func_obj = obj | |
176 | elif inspect.ismethod(obj): |
|
176 | elif inspect.ismethod(obj): | |
177 | func_obj = obj.im_func |
|
177 | func_obj = obj.im_func | |
178 | else: |
|
178 | else: | |
179 | raise TypeError, 'arg is not a Python function' |
|
179 | raise TypeError, 'arg is not a Python function' | |
180 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
180 | args, varargs, varkw = inspect.getargs(func_obj.func_code) | |
181 | return args, varargs, varkw, func_obj.func_defaults |
|
181 | return args, varargs, varkw, func_obj.func_defaults | |
182 |
|
182 | |||
183 | #**************************************************************************** |
|
183 | #**************************************************************************** | |
184 | # Class definitions |
|
184 | # Class definitions | |
185 |
|
185 | |||
186 | class myStringIO(StringIO.StringIO): |
|
186 | class myStringIO(StringIO.StringIO): | |
187 | """Adds a writeln method to normal StringIO.""" |
|
187 | """Adds a writeln method to normal StringIO.""" | |
188 | def writeln(self,*arg,**kw): |
|
188 | def writeln(self,*arg,**kw): | |
189 | """Does a write() and then a write('\n')""" |
|
189 | """Does a write() and then a write('\n')""" | |
190 | self.write(*arg,**kw) |
|
190 | self.write(*arg,**kw) | |
191 | self.write('\n') |
|
191 | self.write('\n') | |
192 |
|
192 | |||
193 |
|
193 | |||
194 | class Inspector: |
|
194 | class Inspector: | |
195 | def __init__(self,color_table,code_color_table,scheme, |
|
195 | def __init__(self,color_table,code_color_table,scheme, | |
196 | str_detail_level=0): |
|
196 | str_detail_level=0): | |
197 | self.color_table = color_table |
|
197 | self.color_table = color_table | |
198 | self.parser = PyColorize.Parser(code_color_table,out='str') |
|
198 | self.parser = PyColorize.Parser(code_color_table,out='str') | |
199 | self.format = self.parser.format |
|
199 | self.format = self.parser.format | |
200 | self.str_detail_level = str_detail_level |
|
200 | self.str_detail_level = str_detail_level | |
201 | self.set_active_scheme(scheme) |
|
201 | self.set_active_scheme(scheme) | |
202 |
|
202 | |||
203 |
def |
|
203 | def _getdef(self,obj,oname=''): | |
204 | """Return the definition header for any callable object. |
|
204 | """Return the definition header for any callable object. | |
205 |
|
205 | |||
206 | If any exception is generated, None is returned instead and the |
|
206 | If any exception is generated, None is returned instead and the | |
207 | exception is suppressed.""" |
|
207 | exception is suppressed.""" | |
208 |
|
208 | |||
209 | try: |
|
209 | try: | |
210 | return oname + inspect.formatargspec(*getargspec(obj)) |
|
210 | return oname + inspect.formatargspec(*getargspec(obj)) | |
211 | except: |
|
211 | except: | |
212 | return None |
|
212 | return None | |
213 |
|
213 | |||
214 | def __head(self,h): |
|
214 | def __head(self,h): | |
215 | """Return a header string with proper colors.""" |
|
215 | """Return a header string with proper colors.""" | |
216 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
216 | return '%s%s%s' % (self.color_table.active_colors.header,h, | |
217 | self.color_table.active_colors.normal) |
|
217 | self.color_table.active_colors.normal) | |
218 |
|
218 | |||
219 | def set_active_scheme(self,scheme): |
|
219 | def set_active_scheme(self,scheme): | |
220 | self.color_table.set_active_scheme(scheme) |
|
220 | self.color_table.set_active_scheme(scheme) | |
221 | self.parser.color_table.set_active_scheme(scheme) |
|
221 | self.parser.color_table.set_active_scheme(scheme) | |
222 |
|
222 | |||
223 | def noinfo(self,msg,oname): |
|
223 | def noinfo(self,msg,oname): | |
224 | """Generic message when no information is found.""" |
|
224 | """Generic message when no information is found.""" | |
225 | print 'No %s found' % msg, |
|
225 | print 'No %s found' % msg, | |
226 | if oname: |
|
226 | if oname: | |
227 | print 'for %s' % oname |
|
227 | print 'for %s' % oname | |
228 | else: |
|
228 | else: | |
229 |
|
229 | |||
230 |
|
230 | |||
231 | def pdef(self,obj,oname=''): |
|
231 | def pdef(self,obj,oname=''): | |
232 | """Print the definition header for any callable object. |
|
232 | """Print the definition header for any callable object. | |
233 |
|
233 | |||
234 | If the object is a class, print the constructor information.""" |
|
234 | If the object is a class, print the constructor information.""" | |
235 |
|
235 | |||
236 | if not callable(obj): |
|
236 | if not callable(obj): | |
237 | print 'Object is not callable.' |
|
237 | print 'Object is not callable.' | |
238 | return |
|
238 | return | |
239 |
|
239 | |||
240 | header = '' |
|
240 | header = '' | |
241 |
|
241 | |||
242 | if inspect.isclass(obj): |
|
242 | if inspect.isclass(obj): | |
243 | header = self.__head('Class constructor information:\n') |
|
243 | header = self.__head('Class constructor information:\n') | |
244 | obj = obj.__init__ |
|
244 | obj = obj.__init__ | |
245 | elif type(obj) is types.InstanceType: |
|
245 | elif type(obj) is types.InstanceType: | |
246 | obj = obj.__call__ |
|
246 | obj = obj.__call__ | |
247 |
|
247 | |||
248 |
output = self. |
|
248 | output = self._getdef(obj,oname) | |
249 | if output is None: |
|
249 | if output is None: | |
250 | self.noinfo('definition header',oname) |
|
250 | self.noinfo('definition header',oname) | |
251 | else: |
|
251 | else: | |
252 | print >>IPython.utils.io.Term.cout, header,self.format(output), |
|
252 | print >>IPython.utils.io.Term.cout, header,self.format(output), | |
253 |
|
253 | |||
254 | def pdoc(self,obj,oname='',formatter = None): |
|
254 | def pdoc(self,obj,oname='',formatter = None): | |
255 | """Print the docstring for any object. |
|
255 | """Print the docstring for any object. | |
256 |
|
256 | |||
257 | Optional: |
|
257 | Optional: | |
258 | -formatter: a function to run the docstring through for specially |
|
258 | -formatter: a function to run the docstring through for specially | |
259 | formatted docstrings.""" |
|
259 | formatted docstrings.""" | |
260 |
|
260 | |||
261 | head = self.__head # so that itpl can find it even if private |
|
261 | head = self.__head # so that itpl can find it even if private | |
262 | ds = getdoc(obj) |
|
262 | ds = getdoc(obj) | |
263 | if formatter: |
|
263 | if formatter: | |
264 | ds = formatter(ds) |
|
264 | ds = formatter(ds) | |
265 | if inspect.isclass(obj): |
|
265 | if inspect.isclass(obj): | |
266 | init_ds = getdoc(obj.__init__) |
|
266 | init_ds = getdoc(obj.__init__) | |
267 | output = itpl('$head("Class Docstring:")\n' |
|
267 | output = itpl('$head("Class Docstring:")\n' | |
268 | '$indent(ds)\n' |
|
268 | '$indent(ds)\n' | |
269 | '$head("Constructor Docstring"):\n' |
|
269 | '$head("Constructor Docstring"):\n' | |
270 | '$indent(init_ds)') |
|
270 | '$indent(init_ds)') | |
271 | elif (type(obj) is types.InstanceType or isinstance(obj,object)) \ |
|
271 | elif (type(obj) is types.InstanceType or isinstance(obj,object)) \ | |
272 | and hasattr(obj,'__call__'): |
|
272 | and hasattr(obj,'__call__'): | |
273 | call_ds = getdoc(obj.__call__) |
|
273 | call_ds = getdoc(obj.__call__) | |
274 | if call_ds: |
|
274 | if call_ds: | |
275 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' |
|
275 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' | |
276 | '$head("Calling Docstring:")\n$indent(call_ds)') |
|
276 | '$head("Calling Docstring:")\n$indent(call_ds)') | |
277 | else: |
|
277 | else: | |
278 | output = ds |
|
278 | output = ds | |
279 | else: |
|
279 | else: | |
280 | output = ds |
|
280 | output = ds | |
281 | if output is None: |
|
281 | if output is None: | |
282 | self.noinfo('documentation',oname) |
|
282 | self.noinfo('documentation',oname) | |
283 | return |
|
283 | return | |
284 | page.page(output) |
|
284 | page.page(output) | |
285 |
|
285 | |||
286 | def psource(self,obj,oname=''): |
|
286 | def psource(self,obj,oname=''): | |
287 | """Print the source code for an object.""" |
|
287 | """Print the source code for an object.""" | |
288 |
|
288 | |||
289 | # Flush the source cache because inspect can return out-of-date source |
|
289 | # Flush the source cache because inspect can return out-of-date source | |
290 | linecache.checkcache() |
|
290 | linecache.checkcache() | |
291 | try: |
|
291 | try: | |
292 | src = getsource(obj) |
|
292 | src = getsource(obj) | |
293 | except: |
|
293 | except: | |
294 | self.noinfo('source',oname) |
|
294 | self.noinfo('source',oname) | |
295 | else: |
|
295 | else: | |
296 | page.page(self.format(src)) |
|
296 | page.page(self.format(src)) | |
297 |
|
297 | |||
298 | def pfile(self,obj,oname=''): |
|
298 | def pfile(self,obj,oname=''): | |
299 | """Show the whole file where an object was defined.""" |
|
299 | """Show the whole file where an object was defined.""" | |
300 |
|
300 | |||
301 | try: |
|
301 | try: | |
302 | try: |
|
302 | try: | |
303 | lineno = inspect.getsourcelines(obj)[1] |
|
303 | lineno = inspect.getsourcelines(obj)[1] | |
304 | except TypeError: |
|
304 | except TypeError: | |
305 | # For instances, try the class object like getsource() does |
|
305 | # For instances, try the class object like getsource() does | |
306 | if hasattr(obj,'__class__'): |
|
306 | if hasattr(obj,'__class__'): | |
307 | lineno = inspect.getsourcelines(obj.__class__)[1] |
|
307 | lineno = inspect.getsourcelines(obj.__class__)[1] | |
308 | # Adjust the inspected object so getabsfile() below works |
|
308 | # Adjust the inspected object so getabsfile() below works | |
309 | obj = obj.__class__ |
|
309 | obj = obj.__class__ | |
310 | except: |
|
310 | except: | |
311 | self.noinfo('file',oname) |
|
311 | self.noinfo('file',oname) | |
312 | return |
|
312 | return | |
313 |
|
313 | |||
314 | # We only reach this point if object was successfully queried |
|
314 | # We only reach this point if object was successfully queried | |
315 |
|
315 | |||
316 | # run contents of file through pager starting at line |
|
316 | # run contents of file through pager starting at line | |
317 | # where the object is defined |
|
317 | # where the object is defined | |
318 | ofile = inspect.getabsfile(obj) |
|
318 | ofile = inspect.getabsfile(obj) | |
319 |
|
319 | |||
320 | if (ofile.endswith('.so') or ofile.endswith('.dll')): |
|
320 | if (ofile.endswith('.so') or ofile.endswith('.dll')): | |
321 | print 'File %r is binary, not printing.' % ofile |
|
321 | print 'File %r is binary, not printing.' % ofile | |
322 | elif not os.path.isfile(ofile): |
|
322 | elif not os.path.isfile(ofile): | |
323 | print 'File %r does not exist, not printing.' % ofile |
|
323 | print 'File %r does not exist, not printing.' % ofile | |
324 | else: |
|
324 | else: | |
325 | # Print only text files, not extension binaries. Note that |
|
325 | # Print only text files, not extension binaries. Note that | |
326 | # getsourcelines returns lineno with 1-offset and page() uses |
|
326 | # getsourcelines returns lineno with 1-offset and page() uses | |
327 | # 0-offset, so we must adjust. |
|
327 | # 0-offset, so we must adjust. | |
328 | page.page(self.format(open(ofile).read()),lineno-1) |
|
328 | page.page(self.format(open(ofile).read()),lineno-1) | |
329 |
|
329 | |||
330 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): |
|
330 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): | |
331 | """Show detailed information about an object. |
|
331 | """Show detailed information about an object. | |
332 |
|
332 | |||
333 | Optional arguments: |
|
333 | Optional arguments: | |
334 |
|
334 | |||
335 | - oname: name of the variable pointing to the object. |
|
335 | - oname: name of the variable pointing to the object. | |
336 |
|
336 | |||
337 | - formatter: special formatter for docstrings (see pdoc) |
|
337 | - formatter: special formatter for docstrings (see pdoc) | |
338 |
|
338 | |||
339 | - info: a structure with some information fields which may have been |
|
339 | - info: a structure with some information fields which may have been | |
340 | precomputed already. |
|
340 | precomputed already. | |
341 |
|
341 | |||
342 | - detail_level: if set to 1, more information is given. |
|
342 | - detail_level: if set to 1, more information is given. | |
343 | """ |
|
343 | """ | |
344 |
|
344 | |||
345 | obj_type = type(obj) |
|
345 | obj_type = type(obj) | |
346 |
|
346 | |||
347 | header = self.__head |
|
347 | header = self.__head | |
348 | if info is None: |
|
348 | if info is None: | |
349 | ismagic = 0 |
|
349 | ismagic = 0 | |
350 | isalias = 0 |
|
350 | isalias = 0 | |
351 | ospace = '' |
|
351 | ospace = '' | |
352 | else: |
|
352 | else: | |
353 | ismagic = info.ismagic |
|
353 | ismagic = info.ismagic | |
354 | isalias = info.isalias |
|
354 | isalias = info.isalias | |
355 | ospace = info.namespace |
|
355 | ospace = info.namespace | |
356 | # Get docstring, special-casing aliases: |
|
356 | # Get docstring, special-casing aliases: | |
357 | if isalias: |
|
357 | if isalias: | |
358 | if not callable(obj): |
|
358 | if not callable(obj): | |
359 | try: |
|
359 | try: | |
360 | ds = "Alias to the system command:\n %s" % obj[1] |
|
360 | ds = "Alias to the system command:\n %s" % obj[1] | |
361 | except: |
|
361 | except: | |
362 | ds = "Alias: " + str(obj) |
|
362 | ds = "Alias: " + str(obj) | |
363 | else: |
|
363 | else: | |
364 | ds = "Alias to " + str(obj) |
|
364 | ds = "Alias to " + str(obj) | |
365 | if obj.__doc__: |
|
365 | if obj.__doc__: | |
366 | ds += "\nDocstring:\n" + obj.__doc__ |
|
366 | ds += "\nDocstring:\n" + obj.__doc__ | |
367 | else: |
|
367 | else: | |
368 | ds = getdoc(obj) |
|
368 | ds = getdoc(obj) | |
369 | if ds is None: |
|
369 | if ds is None: | |
370 | ds = '<no docstring>' |
|
370 | ds = '<no docstring>' | |
371 | if formatter is not None: |
|
371 | if formatter is not None: | |
372 | ds = formatter(ds) |
|
372 | ds = formatter(ds) | |
373 |
|
373 | |||
374 | # store output in a list which gets joined with \n at the end. |
|
374 | # store output in a list which gets joined with \n at the end. | |
375 | out = myStringIO() |
|
375 | out = myStringIO() | |
376 |
|
376 | |||
377 | string_max = 200 # max size of strings to show (snipped if longer) |
|
377 | string_max = 200 # max size of strings to show (snipped if longer) | |
378 | shalf = int((string_max -5)/2) |
|
378 | shalf = int((string_max -5)/2) | |
379 |
|
379 | |||
380 | if ismagic: |
|
380 | if ismagic: | |
381 | obj_type_name = 'Magic function' |
|
381 | obj_type_name = 'Magic function' | |
382 | elif isalias: |
|
382 | elif isalias: | |
383 | obj_type_name = 'System alias' |
|
383 | obj_type_name = 'System alias' | |
384 | else: |
|
384 | else: | |
385 | obj_type_name = obj_type.__name__ |
|
385 | obj_type_name = obj_type.__name__ | |
386 | out.writeln(header('Type:\t\t')+obj_type_name) |
|
386 | out.writeln(header('Type:\t\t')+obj_type_name) | |
387 |
|
387 | |||
388 | try: |
|
388 | try: | |
389 | bclass = obj.__class__ |
|
389 | bclass = obj.__class__ | |
390 | out.writeln(header('Base Class:\t')+str(bclass)) |
|
390 | out.writeln(header('Base Class:\t')+str(bclass)) | |
391 | except: pass |
|
391 | except: pass | |
392 |
|
392 | |||
393 | # String form, but snip if too long in ? form (full in ??) |
|
393 | # String form, but snip if too long in ? form (full in ??) | |
394 | if detail_level >= self.str_detail_level: |
|
394 | if detail_level >= self.str_detail_level: | |
395 | try: |
|
395 | try: | |
396 | ostr = str(obj) |
|
396 | ostr = str(obj) | |
397 | str_head = 'String Form:' |
|
397 | str_head = 'String Form:' | |
398 | if not detail_level and len(ostr)>string_max: |
|
398 | if not detail_level and len(ostr)>string_max: | |
399 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
399 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] | |
400 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
400 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ | |
401 | join(map(string.strip,ostr.split("\n"))) |
|
401 | join(map(string.strip,ostr.split("\n"))) | |
402 | if ostr.find('\n') > -1: |
|
402 | if ostr.find('\n') > -1: | |
403 | # Print multi-line strings starting at the next line. |
|
403 | # Print multi-line strings starting at the next line. | |
404 | str_sep = '\n' |
|
404 | str_sep = '\n' | |
405 | else: |
|
405 | else: | |
406 | str_sep = '\t' |
|
406 | str_sep = '\t' | |
407 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) |
|
407 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) | |
408 | except: |
|
408 | except: | |
409 | pass |
|
409 | pass | |
410 |
|
410 | |||
411 | if ospace: |
|
411 | if ospace: | |
412 | out.writeln(header('Namespace:\t')+ospace) |
|
412 | out.writeln(header('Namespace:\t')+ospace) | |
413 |
|
413 | |||
414 | # Length (for strings and lists) |
|
414 | # Length (for strings and lists) | |
415 | try: |
|
415 | try: | |
416 | length = str(len(obj)) |
|
416 | length = str(len(obj)) | |
417 | out.writeln(header('Length:\t\t')+length) |
|
417 | out.writeln(header('Length:\t\t')+length) | |
418 | except: pass |
|
418 | except: pass | |
419 |
|
419 | |||
420 | # Filename where object was defined |
|
420 | # Filename where object was defined | |
421 | binary_file = False |
|
421 | binary_file = False | |
422 | try: |
|
422 | try: | |
423 | try: |
|
423 | try: | |
424 | fname = inspect.getabsfile(obj) |
|
424 | fname = inspect.getabsfile(obj) | |
425 | except TypeError: |
|
425 | except TypeError: | |
426 | # For an instance, the file that matters is where its class was |
|
426 | # For an instance, the file that matters is where its class was | |
427 | # declared. |
|
427 | # declared. | |
428 | if hasattr(obj,'__class__'): |
|
428 | if hasattr(obj,'__class__'): | |
429 | fname = inspect.getabsfile(obj.__class__) |
|
429 | fname = inspect.getabsfile(obj.__class__) | |
430 | if fname.endswith('<string>'): |
|
430 | if fname.endswith('<string>'): | |
431 | fname = 'Dynamically generated function. No source code available.' |
|
431 | fname = 'Dynamically generated function. No source code available.' | |
432 | if (fname.endswith('.so') or fname.endswith('.dll')): |
|
432 | if (fname.endswith('.so') or fname.endswith('.dll')): | |
433 | binary_file = True |
|
433 | binary_file = True | |
434 | out.writeln(header('File:\t\t')+fname) |
|
434 | out.writeln(header('File:\t\t')+fname) | |
435 | except: |
|
435 | except: | |
436 | # if anything goes wrong, we don't want to show source, so it's as |
|
436 | # if anything goes wrong, we don't want to show source, so it's as | |
437 | # if the file was binary |
|
437 | # if the file was binary | |
438 | binary_file = True |
|
438 | binary_file = True | |
439 |
|
439 | |||
440 | # reconstruct the function definition and print it: |
|
440 | # reconstruct the function definition and print it: | |
441 |
defln = self. |
|
441 | defln = self._getdef(obj,oname) | |
442 | if defln: |
|
442 | if defln: | |
443 | out.write(header('Definition:\t')+self.format(defln)) |
|
443 | out.write(header('Definition:\t')+self.format(defln)) | |
444 |
|
444 | |||
445 | # Docstrings only in detail 0 mode, since source contains them (we |
|
445 | # Docstrings only in detail 0 mode, since source contains them (we | |
446 | # avoid repetitions). If source fails, we add them back, see below. |
|
446 | # avoid repetitions). If source fails, we add them back, see below. | |
447 | if ds and detail_level == 0: |
|
447 | if ds and detail_level == 0: | |
448 | out.writeln(header('Docstring:\n') + indent(ds)) |
|
448 | out.writeln(header('Docstring:\n') + indent(ds)) | |
449 |
|
449 | |||
450 | # Original source code for any callable |
|
450 | # Original source code for any callable | |
451 | if detail_level: |
|
451 | if detail_level: | |
452 | # Flush the source cache because inspect can return out-of-date |
|
452 | # Flush the source cache because inspect can return out-of-date | |
453 | # source |
|
453 | # source | |
454 | linecache.checkcache() |
|
454 | linecache.checkcache() | |
455 | source_success = False |
|
455 | source_success = False | |
456 | try: |
|
456 | try: | |
457 | try: |
|
457 | try: | |
458 | src = getsource(obj,binary_file) |
|
458 | src = getsource(obj,binary_file) | |
459 | except TypeError: |
|
459 | except TypeError: | |
460 | if hasattr(obj,'__class__'): |
|
460 | if hasattr(obj,'__class__'): | |
461 | src = getsource(obj.__class__,binary_file) |
|
461 | src = getsource(obj.__class__,binary_file) | |
462 | if src is not None: |
|
462 | if src is not None: | |
463 | source = self.format(src) |
|
463 | source = self.format(src) | |
464 | out.write(header('Source:\n')+source.rstrip()) |
|
464 | out.write(header('Source:\n')+source.rstrip()) | |
465 | source_success = True |
|
465 | source_success = True | |
466 | except Exception, msg: |
|
466 | except Exception, msg: | |
467 | pass |
|
467 | pass | |
468 |
|
468 | |||
469 | if ds and not source_success: |
|
469 | if ds and not source_success: | |
470 | out.writeln(header('Docstring [source file open failed]:\n') |
|
470 | out.writeln(header('Docstring [source file open failed]:\n') | |
471 | + indent(ds)) |
|
471 | + indent(ds)) | |
472 |
|
472 | |||
473 | # Constructor docstring for classes |
|
473 | # Constructor docstring for classes | |
474 | if inspect.isclass(obj): |
|
474 | if inspect.isclass(obj): | |
475 | # reconstruct the function definition and print it: |
|
475 | # reconstruct the function definition and print it: | |
476 | try: |
|
476 | try: | |
477 | obj_init = obj.__init__ |
|
477 | obj_init = obj.__init__ | |
478 | except AttributeError: |
|
478 | except AttributeError: | |
479 | init_def = init_ds = None |
|
479 | init_def = init_ds = None | |
480 | else: |
|
480 | else: | |
481 |
init_def = self. |
|
481 | init_def = self._getdef(obj_init,oname) | |
482 | init_ds = getdoc(obj_init) |
|
482 | init_ds = getdoc(obj_init) | |
483 | # Skip Python's auto-generated docstrings |
|
483 | # Skip Python's auto-generated docstrings | |
484 | if init_ds and \ |
|
484 | if init_ds and \ | |
485 | init_ds.startswith('x.__init__(...) initializes'): |
|
485 | init_ds.startswith('x.__init__(...) initializes'): | |
486 | init_ds = None |
|
486 | init_ds = None | |
487 |
|
487 | |||
488 | if init_def or init_ds: |
|
488 | if init_def or init_ds: | |
489 | out.writeln(header('\nConstructor information:')) |
|
489 | out.writeln(header('\nConstructor information:')) | |
490 | if init_def: |
|
490 | if init_def: | |
491 | out.write(header('Definition:\t')+ self.format(init_def)) |
|
491 | out.write(header('Definition:\t')+ self.format(init_def)) | |
492 | if init_ds: |
|
492 | if init_ds: | |
493 | out.writeln(header('Docstring:\n') + indent(init_ds)) |
|
493 | out.writeln(header('Docstring:\n') + indent(init_ds)) | |
494 | # and class docstring for instances: |
|
494 | # and class docstring for instances: | |
495 | elif obj_type is types.InstanceType or \ |
|
495 | elif obj_type is types.InstanceType or \ | |
496 | isinstance(obj,object): |
|
496 | isinstance(obj,object): | |
497 |
|
497 | |||
498 | # First, check whether the instance docstring is identical to the |
|
498 | # First, check whether the instance docstring is identical to the | |
499 | # class one, and print it separately if they don't coincide. In |
|
499 | # class one, and print it separately if they don't coincide. In | |
500 | # most cases they will, but it's nice to print all the info for |
|
500 | # most cases they will, but it's nice to print all the info for | |
501 | # objects which use instance-customized docstrings. |
|
501 | # objects which use instance-customized docstrings. | |
502 | if ds: |
|
502 | if ds: | |
503 | try: |
|
503 | try: | |
504 | cls = getattr(obj,'__class__') |
|
504 | cls = getattr(obj,'__class__') | |
505 | except: |
|
505 | except: | |
506 | class_ds = None |
|
506 | class_ds = None | |
507 | else: |
|
507 | else: | |
508 | class_ds = getdoc(cls) |
|
508 | class_ds = getdoc(cls) | |
509 | # Skip Python's auto-generated docstrings |
|
509 | # Skip Python's auto-generated docstrings | |
510 | if class_ds and \ |
|
510 | if class_ds and \ | |
511 | (class_ds.startswith('function(code, globals[,') or \ |
|
511 | (class_ds.startswith('function(code, globals[,') or \ | |
512 | class_ds.startswith('instancemethod(function, instance,') or \ |
|
512 | class_ds.startswith('instancemethod(function, instance,') or \ | |
513 | class_ds.startswith('module(name[,') ): |
|
513 | class_ds.startswith('module(name[,') ): | |
514 | class_ds = None |
|
514 | class_ds = None | |
515 | if class_ds and ds != class_ds: |
|
515 | if class_ds and ds != class_ds: | |
516 | out.writeln(header('Class Docstring:\n') + |
|
516 | out.writeln(header('Class Docstring:\n') + | |
517 | indent(class_ds)) |
|
517 | indent(class_ds)) | |
518 |
|
518 | |||
519 | # Next, try to show constructor docstrings |
|
519 | # Next, try to show constructor docstrings | |
520 | try: |
|
520 | try: | |
521 | init_ds = getdoc(obj.__init__) |
|
521 | init_ds = getdoc(obj.__init__) | |
522 | # Skip Python's auto-generated docstrings |
|
522 | # Skip Python's auto-generated docstrings | |
523 | if init_ds and \ |
|
523 | if init_ds and \ | |
524 | init_ds.startswith('x.__init__(...) initializes'): |
|
524 | init_ds.startswith('x.__init__(...) initializes'): | |
525 | init_ds = None |
|
525 | init_ds = None | |
526 | except AttributeError: |
|
526 | except AttributeError: | |
527 | init_ds = None |
|
527 | init_ds = None | |
528 | if init_ds: |
|
528 | if init_ds: | |
529 | out.writeln(header('Constructor Docstring:\n') + |
|
529 | out.writeln(header('Constructor Docstring:\n') + | |
530 | indent(init_ds)) |
|
530 | indent(init_ds)) | |
531 |
|
531 | |||
532 | # Call form docstring for callable instances |
|
532 | # Call form docstring for callable instances | |
533 | if hasattr(obj,'__call__'): |
|
533 | if hasattr(obj,'__call__'): | |
534 | #out.writeln(header('Callable:\t')+'Yes') |
|
534 | #out.writeln(header('Callable:\t')+'Yes') | |
535 |
call_def = self. |
|
535 | call_def = self._getdef(obj.__call__,oname) | |
536 | #if call_def is None: |
|
536 | #if call_def is None: | |
537 | # out.writeln(header('Call def:\t')+ |
|
537 | # out.writeln(header('Call def:\t')+ | |
538 | # 'Calling definition not available.') |
|
538 | # 'Calling definition not available.') | |
539 | if call_def is not None: |
|
539 | if call_def is not None: | |
540 | out.writeln(header('Call def:\t')+self.format(call_def)) |
|
540 | out.writeln(header('Call def:\t')+self.format(call_def)) | |
541 | call_ds = getdoc(obj.__call__) |
|
541 | call_ds = getdoc(obj.__call__) | |
542 | # Skip Python's auto-generated docstrings |
|
542 | # Skip Python's auto-generated docstrings | |
543 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): |
|
543 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): | |
544 | call_ds = None |
|
544 | call_ds = None | |
545 | if call_ds: |
|
545 | if call_ds: | |
546 | out.writeln(header('Call docstring:\n') + indent(call_ds)) |
|
546 | out.writeln(header('Call docstring:\n') + indent(call_ds)) | |
547 |
|
547 | |||
548 | # Finally send to printer/pager |
|
548 | # Finally send to printer/pager | |
549 | output = out.getvalue() |
|
549 | output = out.getvalue() | |
550 | if output: |
|
550 | if output: | |
551 | page.page(output) |
|
551 | page.page(output) | |
552 | # end pinfo |
|
552 | # end pinfo | |
553 |
|
553 | |||
554 | def psearch(self,pattern,ns_table,ns_search=[], |
|
554 | def psearch(self,pattern,ns_table,ns_search=[], | |
555 | ignore_case=False,show_all=False): |
|
555 | ignore_case=False,show_all=False): | |
556 | """Search namespaces with wildcards for objects. |
|
556 | """Search namespaces with wildcards for objects. | |
557 |
|
557 | |||
558 | Arguments: |
|
558 | Arguments: | |
559 |
|
559 | |||
560 | - pattern: string containing shell-like wildcards to use in namespace |
|
560 | - pattern: string containing shell-like wildcards to use in namespace | |
561 | searches and optionally a type specification to narrow the search to |
|
561 | searches and optionally a type specification to narrow the search to | |
562 | objects of that type. |
|
562 | objects of that type. | |
563 |
|
563 | |||
564 | - ns_table: dict of name->namespaces for search. |
|
564 | - ns_table: dict of name->namespaces for search. | |
565 |
|
565 | |||
566 | Optional arguments: |
|
566 | Optional arguments: | |
567 |
|
567 | |||
568 | - ns_search: list of namespace names to include in search. |
|
568 | - ns_search: list of namespace names to include in search. | |
569 |
|
569 | |||
570 | - ignore_case(False): make the search case-insensitive. |
|
570 | - ignore_case(False): make the search case-insensitive. | |
571 |
|
571 | |||
572 | - show_all(False): show all names, including those starting with |
|
572 | - show_all(False): show all names, including those starting with | |
573 | underscores. |
|
573 | underscores. | |
574 | """ |
|
574 | """ | |
575 | #print 'ps pattern:<%r>' % pattern # dbg |
|
575 | #print 'ps pattern:<%r>' % pattern # dbg | |
576 |
|
576 | |||
577 | # defaults |
|
577 | # defaults | |
578 | type_pattern = 'all' |
|
578 | type_pattern = 'all' | |
579 | filter = '' |
|
579 | filter = '' | |
580 |
|
580 | |||
581 | cmds = pattern.split() |
|
581 | cmds = pattern.split() | |
582 | len_cmds = len(cmds) |
|
582 | len_cmds = len(cmds) | |
583 | if len_cmds == 1: |
|
583 | if len_cmds == 1: | |
584 | # Only filter pattern given |
|
584 | # Only filter pattern given | |
585 | filter = cmds[0] |
|
585 | filter = cmds[0] | |
586 | elif len_cmds == 2: |
|
586 | elif len_cmds == 2: | |
587 | # Both filter and type specified |
|
587 | # Both filter and type specified | |
588 | filter,type_pattern = cmds |
|
588 | filter,type_pattern = cmds | |
589 | else: |
|
589 | else: | |
590 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
590 | raise ValueError('invalid argument string for psearch: <%s>' % | |
591 | pattern) |
|
591 | pattern) | |
592 |
|
592 | |||
593 | # filter search namespaces |
|
593 | # filter search namespaces | |
594 | for name in ns_search: |
|
594 | for name in ns_search: | |
595 | if name not in ns_table: |
|
595 | if name not in ns_table: | |
596 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
596 | raise ValueError('invalid namespace <%s>. Valid names: %s' % | |
597 | (name,ns_table.keys())) |
|
597 | (name,ns_table.keys())) | |
598 |
|
598 | |||
599 | #print 'type_pattern:',type_pattern # dbg |
|
599 | #print 'type_pattern:',type_pattern # dbg | |
600 | search_result = [] |
|
600 | search_result = [] | |
601 | for ns_name in ns_search: |
|
601 | for ns_name in ns_search: | |
602 | ns = ns_table[ns_name] |
|
602 | ns = ns_table[ns_name] | |
603 | tmp_res = list(list_namespace(ns,type_pattern,filter, |
|
603 | tmp_res = list(list_namespace(ns,type_pattern,filter, | |
604 | ignore_case=ignore_case, |
|
604 | ignore_case=ignore_case, | |
605 | show_all=show_all)) |
|
605 | show_all=show_all)) | |
606 | search_result.extend(tmp_res) |
|
606 | search_result.extend(tmp_res) | |
607 | search_result.sort() |
|
607 | search_result.sort() | |
608 |
|
608 | |||
609 | page.page('\n'.join(search_result)) |
|
609 | page.page('\n'.join(search_result)) |
@@ -1,489 +1,499 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Utilities for working with strings and text. |
|
3 | Utilities for working with strings and text. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
7 | # Copyright (C) 2008-2009 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 | import __main__ |
|
17 | import __main__ | |
18 |
|
18 | |||
19 | import os |
|
19 | import os | |
20 | import re |
|
20 | import re | |
21 | import shutil |
|
21 | import shutil | |
22 | import types |
|
22 | import types | |
23 |
|
23 | |||
24 | from IPython.external.path import path |
|
24 | from IPython.external.path import path | |
25 |
|
25 | |||
26 | from IPython.utils.io import nlprint |
|
26 | from IPython.utils.io import nlprint | |
27 | from IPython.utils.data import flatten |
|
27 | from IPython.utils.data import flatten | |
28 |
|
28 | |||
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 | # Code |
|
30 | # Code | |
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 |
|
32 | |||
33 | StringTypes = types.StringTypes |
|
33 | StringTypes = types.StringTypes | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | def unquote_ends(istr): |
|
36 | def unquote_ends(istr): | |
37 | """Remove a single pair of quotes from the endpoints of a string.""" |
|
37 | """Remove a single pair of quotes from the endpoints of a string.""" | |
38 |
|
38 | |||
39 | if not istr: |
|
39 | if not istr: | |
40 | return istr |
|
40 | return istr | |
41 | if (istr[0]=="'" and istr[-1]=="'") or \ |
|
41 | if (istr[0]=="'" and istr[-1]=="'") or \ | |
42 | (istr[0]=='"' and istr[-1]=='"'): |
|
42 | (istr[0]=='"' and istr[-1]=='"'): | |
43 | return istr[1:-1] |
|
43 | return istr[1:-1] | |
44 | else: |
|
44 | else: | |
45 | return istr |
|
45 | return istr | |
46 |
|
46 | |||
47 |
|
47 | |||
48 | class LSString(str): |
|
48 | class LSString(str): | |
49 | """String derivative with a special access attributes. |
|
49 | """String derivative with a special access attributes. | |
50 |
|
50 | |||
51 | These are normal strings, but with the special attributes: |
|
51 | These are normal strings, but with the special attributes: | |
52 |
|
52 | |||
53 | .l (or .list) : value as list (split on newlines). |
|
53 | .l (or .list) : value as list (split on newlines). | |
54 | .n (or .nlstr): original value (the string itself). |
|
54 | .n (or .nlstr): original value (the string itself). | |
55 | .s (or .spstr): value as whitespace-separated string. |
|
55 | .s (or .spstr): value as whitespace-separated string. | |
56 | .p (or .paths): list of path objects |
|
56 | .p (or .paths): list of path objects | |
57 |
|
57 | |||
58 | Any values which require transformations are computed only once and |
|
58 | Any values which require transformations are computed only once and | |
59 | cached. |
|
59 | cached. | |
60 |
|
60 | |||
61 | Such strings are very useful to efficiently interact with the shell, which |
|
61 | Such strings are very useful to efficiently interact with the shell, which | |
62 | typically only understands whitespace-separated options for commands.""" |
|
62 | typically only understands whitespace-separated options for commands.""" | |
63 |
|
63 | |||
64 | def get_list(self): |
|
64 | def get_list(self): | |
65 | try: |
|
65 | try: | |
66 | return self.__list |
|
66 | return self.__list | |
67 | except AttributeError: |
|
67 | except AttributeError: | |
68 | self.__list = self.split('\n') |
|
68 | self.__list = self.split('\n') | |
69 | return self.__list |
|
69 | return self.__list | |
70 |
|
70 | |||
71 | l = list = property(get_list) |
|
71 | l = list = property(get_list) | |
72 |
|
72 | |||
73 | def get_spstr(self): |
|
73 | def get_spstr(self): | |
74 | try: |
|
74 | try: | |
75 | return self.__spstr |
|
75 | return self.__spstr | |
76 | except AttributeError: |
|
76 | except AttributeError: | |
77 | self.__spstr = self.replace('\n',' ') |
|
77 | self.__spstr = self.replace('\n',' ') | |
78 | return self.__spstr |
|
78 | return self.__spstr | |
79 |
|
79 | |||
80 | s = spstr = property(get_spstr) |
|
80 | s = spstr = property(get_spstr) | |
81 |
|
81 | |||
82 | def get_nlstr(self): |
|
82 | def get_nlstr(self): | |
83 | return self |
|
83 | return self | |
84 |
|
84 | |||
85 | n = nlstr = property(get_nlstr) |
|
85 | n = nlstr = property(get_nlstr) | |
86 |
|
86 | |||
87 | def get_paths(self): |
|
87 | def get_paths(self): | |
88 | try: |
|
88 | try: | |
89 | return self.__paths |
|
89 | return self.__paths | |
90 | except AttributeError: |
|
90 | except AttributeError: | |
91 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] |
|
91 | self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] | |
92 | return self.__paths |
|
92 | return self.__paths | |
93 |
|
93 | |||
94 | p = paths = property(get_paths) |
|
94 | p = paths = property(get_paths) | |
95 |
|
95 | |||
96 | # FIXME: We need to reimplement type specific displayhook and then add this |
|
96 | # FIXME: We need to reimplement type specific displayhook and then add this | |
97 | # back as a custom printer. This should also be moved outside utils into the |
|
97 | # back as a custom printer. This should also be moved outside utils into the | |
98 | # core. |
|
98 | # core. | |
99 |
|
99 | |||
100 | # def print_lsstring(arg): |
|
100 | # def print_lsstring(arg): | |
101 | # """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
101 | # """ Prettier (non-repr-like) and more informative printer for LSString """ | |
102 | # print "LSString (.p, .n, .l, .s available). Value:" |
|
102 | # print "LSString (.p, .n, .l, .s available). Value:" | |
103 | # print arg |
|
103 | # print arg | |
104 | # |
|
104 | # | |
105 | # |
|
105 | # | |
106 | # print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
106 | # print_lsstring = result_display.when_type(LSString)(print_lsstring) | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | class SList(list): |
|
109 | class SList(list): | |
110 | """List derivative with a special access attributes. |
|
110 | """List derivative with a special access attributes. | |
111 |
|
111 | |||
112 | These are normal lists, but with the special attributes: |
|
112 | These are normal lists, but with the special attributes: | |
113 |
|
113 | |||
114 | .l (or .list) : value as list (the list itself). |
|
114 | .l (or .list) : value as list (the list itself). | |
115 | .n (or .nlstr): value as a string, joined on newlines. |
|
115 | .n (or .nlstr): value as a string, joined on newlines. | |
116 | .s (or .spstr): value as a string, joined on spaces. |
|
116 | .s (or .spstr): value as a string, joined on spaces. | |
117 | .p (or .paths): list of path objects |
|
117 | .p (or .paths): list of path objects | |
118 |
|
118 | |||
119 | Any values which require transformations are computed only once and |
|
119 | Any values which require transformations are computed only once and | |
120 | cached.""" |
|
120 | cached.""" | |
121 |
|
121 | |||
122 | def get_list(self): |
|
122 | def get_list(self): | |
123 | return self |
|
123 | return self | |
124 |
|
124 | |||
125 | l = list = property(get_list) |
|
125 | l = list = property(get_list) | |
126 |
|
126 | |||
127 | def get_spstr(self): |
|
127 | def get_spstr(self): | |
128 | try: |
|
128 | try: | |
129 | return self.__spstr |
|
129 | return self.__spstr | |
130 | except AttributeError: |
|
130 | except AttributeError: | |
131 | self.__spstr = ' '.join(self) |
|
131 | self.__spstr = ' '.join(self) | |
132 | return self.__spstr |
|
132 | return self.__spstr | |
133 |
|
133 | |||
134 | s = spstr = property(get_spstr) |
|
134 | s = spstr = property(get_spstr) | |
135 |
|
135 | |||
136 | def get_nlstr(self): |
|
136 | def get_nlstr(self): | |
137 | try: |
|
137 | try: | |
138 | return self.__nlstr |
|
138 | return self.__nlstr | |
139 | except AttributeError: |
|
139 | except AttributeError: | |
140 | self.__nlstr = '\n'.join(self) |
|
140 | self.__nlstr = '\n'.join(self) | |
141 | return self.__nlstr |
|
141 | return self.__nlstr | |
142 |
|
142 | |||
143 | n = nlstr = property(get_nlstr) |
|
143 | n = nlstr = property(get_nlstr) | |
144 |
|
144 | |||
145 | def get_paths(self): |
|
145 | def get_paths(self): | |
146 | try: |
|
146 | try: | |
147 | return self.__paths |
|
147 | return self.__paths | |
148 | except AttributeError: |
|
148 | except AttributeError: | |
149 | self.__paths = [path(p) for p in self if os.path.exists(p)] |
|
149 | self.__paths = [path(p) for p in self if os.path.exists(p)] | |
150 | return self.__paths |
|
150 | return self.__paths | |
151 |
|
151 | |||
152 | p = paths = property(get_paths) |
|
152 | p = paths = property(get_paths) | |
153 |
|
153 | |||
154 | def grep(self, pattern, prune = False, field = None): |
|
154 | def grep(self, pattern, prune = False, field = None): | |
155 | """ Return all strings matching 'pattern' (a regex or callable) |
|
155 | """ Return all strings matching 'pattern' (a regex or callable) | |
156 |
|
156 | |||
157 | This is case-insensitive. If prune is true, return all items |
|
157 | This is case-insensitive. If prune is true, return all items | |
158 | NOT matching the pattern. |
|
158 | NOT matching the pattern. | |
159 |
|
159 | |||
160 | If field is specified, the match must occur in the specified |
|
160 | If field is specified, the match must occur in the specified | |
161 | whitespace-separated field. |
|
161 | whitespace-separated field. | |
162 |
|
162 | |||
163 | Examples:: |
|
163 | Examples:: | |
164 |
|
164 | |||
165 | a.grep( lambda x: x.startswith('C') ) |
|
165 | a.grep( lambda x: x.startswith('C') ) | |
166 | a.grep('Cha.*log', prune=1) |
|
166 | a.grep('Cha.*log', prune=1) | |
167 | a.grep('chm', field=-1) |
|
167 | a.grep('chm', field=-1) | |
168 | """ |
|
168 | """ | |
169 |
|
169 | |||
170 | def match_target(s): |
|
170 | def match_target(s): | |
171 | if field is None: |
|
171 | if field is None: | |
172 | return s |
|
172 | return s | |
173 | parts = s.split() |
|
173 | parts = s.split() | |
174 | try: |
|
174 | try: | |
175 | tgt = parts[field] |
|
175 | tgt = parts[field] | |
176 | return tgt |
|
176 | return tgt | |
177 | except IndexError: |
|
177 | except IndexError: | |
178 | return "" |
|
178 | return "" | |
179 |
|
179 | |||
180 | if isinstance(pattern, basestring): |
|
180 | if isinstance(pattern, basestring): | |
181 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
|
181 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) | |
182 | else: |
|
182 | else: | |
183 | pred = pattern |
|
183 | pred = pattern | |
184 | if not prune: |
|
184 | if not prune: | |
185 | return SList([el for el in self if pred(match_target(el))]) |
|
185 | return SList([el for el in self if pred(match_target(el))]) | |
186 | else: |
|
186 | else: | |
187 | return SList([el for el in self if not pred(match_target(el))]) |
|
187 | return SList([el for el in self if not pred(match_target(el))]) | |
188 |
|
188 | |||
189 | def fields(self, *fields): |
|
189 | def fields(self, *fields): | |
190 | """ Collect whitespace-separated fields from string list |
|
190 | """ Collect whitespace-separated fields from string list | |
191 |
|
191 | |||
192 | Allows quick awk-like usage of string lists. |
|
192 | Allows quick awk-like usage of string lists. | |
193 |
|
193 | |||
194 | Example data (in var a, created by 'a = !ls -l'):: |
|
194 | Example data (in var a, created by 'a = !ls -l'):: | |
195 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog |
|
195 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog | |
196 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython |
|
196 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython | |
197 |
|
197 | |||
198 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] |
|
198 | a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] | |
199 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] |
|
199 | a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] | |
200 | (note the joining by space). |
|
200 | (note the joining by space). | |
201 | a.fields(-1) is ['ChangeLog', 'IPython'] |
|
201 | a.fields(-1) is ['ChangeLog', 'IPython'] | |
202 |
|
202 | |||
203 | IndexErrors are ignored. |
|
203 | IndexErrors are ignored. | |
204 |
|
204 | |||
205 | Without args, fields() just split()'s the strings. |
|
205 | Without args, fields() just split()'s the strings. | |
206 | """ |
|
206 | """ | |
207 | if len(fields) == 0: |
|
207 | if len(fields) == 0: | |
208 | return [el.split() for el in self] |
|
208 | return [el.split() for el in self] | |
209 |
|
209 | |||
210 | res = SList() |
|
210 | res = SList() | |
211 | for el in [f.split() for f in self]: |
|
211 | for el in [f.split() for f in self]: | |
212 | lineparts = [] |
|
212 | lineparts = [] | |
213 |
|
213 | |||
214 | for fd in fields: |
|
214 | for fd in fields: | |
215 | try: |
|
215 | try: | |
216 | lineparts.append(el[fd]) |
|
216 | lineparts.append(el[fd]) | |
217 | except IndexError: |
|
217 | except IndexError: | |
218 | pass |
|
218 | pass | |
219 | if lineparts: |
|
219 | if lineparts: | |
220 | res.append(" ".join(lineparts)) |
|
220 | res.append(" ".join(lineparts)) | |
221 |
|
221 | |||
222 | return res |
|
222 | return res | |
223 |
|
223 | |||
224 | def sort(self,field= None, nums = False): |
|
224 | def sort(self,field= None, nums = False): | |
225 | """ sort by specified fields (see fields()) |
|
225 | """ sort by specified fields (see fields()) | |
226 |
|
226 | |||
227 | Example:: |
|
227 | Example:: | |
228 | a.sort(1, nums = True) |
|
228 | a.sort(1, nums = True) | |
229 |
|
229 | |||
230 | Sorts a by second field, in numerical order (so that 21 > 3) |
|
230 | Sorts a by second field, in numerical order (so that 21 > 3) | |
231 |
|
231 | |||
232 | """ |
|
232 | """ | |
233 |
|
233 | |||
234 | #decorate, sort, undecorate |
|
234 | #decorate, sort, undecorate | |
235 | if field is not None: |
|
235 | if field is not None: | |
236 | dsu = [[SList([line]).fields(field), line] for line in self] |
|
236 | dsu = [[SList([line]).fields(field), line] for line in self] | |
237 | else: |
|
237 | else: | |
238 | dsu = [[line, line] for line in self] |
|
238 | dsu = [[line, line] for line in self] | |
239 | if nums: |
|
239 | if nums: | |
240 | for i in range(len(dsu)): |
|
240 | for i in range(len(dsu)): | |
241 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) |
|
241 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) | |
242 | try: |
|
242 | try: | |
243 | n = int(numstr) |
|
243 | n = int(numstr) | |
244 | except ValueError: |
|
244 | except ValueError: | |
245 | n = 0; |
|
245 | n = 0; | |
246 | dsu[i][0] = n |
|
246 | dsu[i][0] = n | |
247 |
|
247 | |||
248 |
|
248 | |||
249 | dsu.sort() |
|
249 | dsu.sort() | |
250 | return SList([t[1] for t in dsu]) |
|
250 | return SList([t[1] for t in dsu]) | |
251 |
|
251 | |||
252 |
|
252 | |||
253 | # FIXME: We need to reimplement type specific displayhook and then add this |
|
253 | # FIXME: We need to reimplement type specific displayhook and then add this | |
254 | # back as a custom printer. This should also be moved outside utils into the |
|
254 | # back as a custom printer. This should also be moved outside utils into the | |
255 | # core. |
|
255 | # core. | |
256 |
|
256 | |||
257 | # def print_slist(arg): |
|
257 | # def print_slist(arg): | |
258 | # """ Prettier (non-repr-like) and more informative printer for SList """ |
|
258 | # """ Prettier (non-repr-like) and more informative printer for SList """ | |
259 | # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" |
|
259 | # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" | |
260 | # if hasattr(arg, 'hideonce') and arg.hideonce: |
|
260 | # if hasattr(arg, 'hideonce') and arg.hideonce: | |
261 | # arg.hideonce = False |
|
261 | # arg.hideonce = False | |
262 | # return |
|
262 | # return | |
263 | # |
|
263 | # | |
264 | # nlprint(arg) |
|
264 | # nlprint(arg) | |
265 | # |
|
265 | # | |
266 | # print_slist = result_display.when_type(SList)(print_slist) |
|
266 | # print_slist = result_display.when_type(SList)(print_slist) | |
267 |
|
267 | |||
268 |
|
268 | |||
269 | def esc_quotes(strng): |
|
269 | def esc_quotes(strng): | |
270 | """Return the input string with single and double quotes escaped out""" |
|
270 | """Return the input string with single and double quotes escaped out""" | |
271 |
|
271 | |||
272 | return strng.replace('"','\\"').replace("'","\\'") |
|
272 | return strng.replace('"','\\"').replace("'","\\'") | |
273 |
|
273 | |||
274 |
|
274 | |||
275 | def make_quoted_expr(s): |
|
275 | def make_quoted_expr(s): | |
276 | """Return string s in appropriate quotes, using raw string if possible. |
|
276 | """Return string s in appropriate quotes, using raw string if possible. | |
277 |
|
277 | |||
278 | XXX - example removed because it caused encoding errors in documentation |
|
278 | XXX - example removed because it caused encoding errors in documentation | |
279 | generation. We need a new example that doesn't contain invalid chars. |
|
279 | generation. We need a new example that doesn't contain invalid chars. | |
280 |
|
280 | |||
281 | Note the use of raw string and padding at the end to allow trailing |
|
281 | Note the use of raw string and padding at the end to allow trailing | |
282 | backslash. |
|
282 | backslash. | |
283 | """ |
|
283 | """ | |
284 |
|
284 | |||
285 | tail = '' |
|
285 | tail = '' | |
286 | tailpadding = '' |
|
286 | tailpadding = '' | |
287 | raw = '' |
|
287 | raw = '' | |
288 | if "\\" in s: |
|
288 | if "\\" in s: | |
289 | raw = 'r' |
|
289 | raw = 'r' | |
290 | if s.endswith('\\'): |
|
290 | if s.endswith('\\'): | |
291 | tail = '[:-1]' |
|
291 | tail = '[:-1]' | |
292 | tailpadding = '_' |
|
292 | tailpadding = '_' | |
293 | if '"' not in s: |
|
293 | if '"' not in s: | |
294 | quote = '"' |
|
294 | quote = '"' | |
295 | elif "'" not in s: |
|
295 | elif "'" not in s: | |
296 | quote = "'" |
|
296 | quote = "'" | |
297 | elif '"""' not in s and not s.endswith('"'): |
|
297 | elif '"""' not in s and not s.endswith('"'): | |
298 | quote = '"""' |
|
298 | quote = '"""' | |
299 | elif "'''" not in s and not s.endswith("'"): |
|
299 | elif "'''" not in s and not s.endswith("'"): | |
300 | quote = "'''" |
|
300 | quote = "'''" | |
301 | else: |
|
301 | else: | |
302 | # give up, backslash-escaped string will do |
|
302 | # give up, backslash-escaped string will do | |
303 | return '"%s"' % esc_quotes(s) |
|
303 | return '"%s"' % esc_quotes(s) | |
304 | res = raw + quote + s + tailpadding + quote + tail |
|
304 | res = raw + quote + s + tailpadding + quote + tail | |
305 | return res |
|
305 | return res | |
306 |
|
306 | |||
307 |
|
307 | |||
308 | def qw(words,flat=0,sep=None,maxsplit=-1): |
|
308 | def qw(words,flat=0,sep=None,maxsplit=-1): | |
309 | """Similar to Perl's qw() operator, but with some more options. |
|
309 | """Similar to Perl's qw() operator, but with some more options. | |
310 |
|
310 | |||
311 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) |
|
311 | qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) | |
312 |
|
312 | |||
313 | words can also be a list itself, and with flat=1, the output will be |
|
313 | words can also be a list itself, and with flat=1, the output will be | |
314 | recursively flattened. |
|
314 | recursively flattened. | |
315 |
|
315 | |||
316 | Examples: |
|
316 | Examples: | |
317 |
|
317 | |||
318 | >>> qw('1 2') |
|
318 | >>> qw('1 2') | |
319 | ['1', '2'] |
|
319 | ['1', '2'] | |
320 |
|
320 | |||
321 | >>> qw(['a b','1 2',['m n','p q']]) |
|
321 | >>> qw(['a b','1 2',['m n','p q']]) | |
322 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] |
|
322 | [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] | |
323 |
|
323 | |||
324 | >>> qw(['a b','1 2',['m n','p q']],flat=1) |
|
324 | >>> qw(['a b','1 2',['m n','p q']],flat=1) | |
325 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] |
|
325 | ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] | |
326 | """ |
|
326 | """ | |
327 |
|
327 | |||
328 | if type(words) in StringTypes: |
|
328 | if type(words) in StringTypes: | |
329 | return [word.strip() for word in words.split(sep,maxsplit) |
|
329 | return [word.strip() for word in words.split(sep,maxsplit) | |
330 | if word and not word.isspace() ] |
|
330 | if word and not word.isspace() ] | |
331 | if flat: |
|
331 | if flat: | |
332 | return flatten(map(qw,words,[1]*len(words))) |
|
332 | return flatten(map(qw,words,[1]*len(words))) | |
333 | return map(qw,words) |
|
333 | return map(qw,words) | |
334 |
|
334 | |||
335 |
|
335 | |||
336 | def qwflat(words,sep=None,maxsplit=-1): |
|
336 | def qwflat(words,sep=None,maxsplit=-1): | |
337 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" |
|
337 | """Calls qw(words) in flat mode. It's just a convenient shorthand.""" | |
338 | return qw(words,1,sep,maxsplit) |
|
338 | return qw(words,1,sep,maxsplit) | |
339 |
|
339 | |||
340 |
|
340 | |||
341 | def qw_lol(indata): |
|
341 | def qw_lol(indata): | |
342 | """qw_lol('a b') -> [['a','b']], |
|
342 | """qw_lol('a b') -> [['a','b']], | |
343 | otherwise it's just a call to qw(). |
|
343 | otherwise it's just a call to qw(). | |
344 |
|
344 | |||
345 | We need this to make sure the modules_some keys *always* end up as a |
|
345 | We need this to make sure the modules_some keys *always* end up as a | |
346 | list of lists.""" |
|
346 | list of lists.""" | |
347 |
|
347 | |||
348 | if type(indata) in StringTypes: |
|
348 | if type(indata) in StringTypes: | |
349 | return [qw(indata)] |
|
349 | return [qw(indata)] | |
350 | else: |
|
350 | else: | |
351 | return qw(indata) |
|
351 | return qw(indata) | |
352 |
|
352 | |||
353 |
|
353 | |||
354 | def grep(pat,list,case=1): |
|
354 | def grep(pat,list,case=1): | |
355 | """Simple minded grep-like function. |
|
355 | """Simple minded grep-like function. | |
356 | grep(pat,list) returns occurrences of pat in list, None on failure. |
|
356 | grep(pat,list) returns occurrences of pat in list, None on failure. | |
357 |
|
357 | |||
358 | It only does simple string matching, with no support for regexps. Use the |
|
358 | It only does simple string matching, with no support for regexps. Use the | |
359 | option case=0 for case-insensitive matching.""" |
|
359 | option case=0 for case-insensitive matching.""" | |
360 |
|
360 | |||
361 | # This is pretty crude. At least it should implement copying only references |
|
361 | # This is pretty crude. At least it should implement copying only references | |
362 | # to the original data in case it's big. Now it copies the data for output. |
|
362 | # to the original data in case it's big. Now it copies the data for output. | |
363 | out=[] |
|
363 | out=[] | |
364 | if case: |
|
364 | if case: | |
365 | for term in list: |
|
365 | for term in list: | |
366 | if term.find(pat)>-1: out.append(term) |
|
366 | if term.find(pat)>-1: out.append(term) | |
367 | else: |
|
367 | else: | |
368 | lpat=pat.lower() |
|
368 | lpat=pat.lower() | |
369 | for term in list: |
|
369 | for term in list: | |
370 | if term.lower().find(lpat)>-1: out.append(term) |
|
370 | if term.lower().find(lpat)>-1: out.append(term) | |
371 |
|
371 | |||
372 | if len(out): return out |
|
372 | if len(out): return out | |
373 | else: return None |
|
373 | else: return None | |
374 |
|
374 | |||
375 |
|
375 | |||
376 | def dgrep(pat,*opts): |
|
376 | def dgrep(pat,*opts): | |
377 | """Return grep() on dir()+dir(__builtins__). |
|
377 | """Return grep() on dir()+dir(__builtins__). | |
378 |
|
378 | |||
379 | A very common use of grep() when working interactively.""" |
|
379 | A very common use of grep() when working interactively.""" | |
380 |
|
380 | |||
381 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) |
|
381 | return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) | |
382 |
|
382 | |||
383 |
|
383 | |||
384 | def idgrep(pat): |
|
384 | def idgrep(pat): | |
385 | """Case-insensitive dgrep()""" |
|
385 | """Case-insensitive dgrep()""" | |
386 |
|
386 | |||
387 | return dgrep(pat,0) |
|
387 | return dgrep(pat,0) | |
388 |
|
388 | |||
389 |
|
389 | |||
390 | def igrep(pat,list): |
|
390 | def igrep(pat,list): | |
391 | """Synonym for case-insensitive grep.""" |
|
391 | """Synonym for case-insensitive grep.""" | |
392 |
|
392 | |||
393 | return grep(pat,list,case=0) |
|
393 | return grep(pat,list,case=0) | |
394 |
|
394 | |||
395 |
|
395 | |||
396 | def indent(str,nspaces=4,ntabs=0): |
|
396 | def indent(str,nspaces=4,ntabs=0): | |
397 | """Indent a string a given number of spaces or tabstops. |
|
397 | """Indent a string a given number of spaces or tabstops. | |
398 |
|
398 | |||
399 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
399 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. | |
400 | """ |
|
400 | """ | |
401 | if str is None: |
|
401 | if str is None: | |
402 | return |
|
402 | return | |
403 | ind = '\t'*ntabs+' '*nspaces |
|
403 | ind = '\t'*ntabs+' '*nspaces | |
404 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) |
|
404 | outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind)) | |
405 | if outstr.endswith(os.linesep+ind): |
|
405 | if outstr.endswith(os.linesep+ind): | |
406 | return outstr[:-len(ind)] |
|
406 | return outstr[:-len(ind)] | |
407 | else: |
|
407 | else: | |
408 | return outstr |
|
408 | return outstr | |
409 |
|
409 | |||
410 | def native_line_ends(filename,backup=1): |
|
410 | def native_line_ends(filename,backup=1): | |
411 | """Convert (in-place) a file to line-ends native to the current OS. |
|
411 | """Convert (in-place) a file to line-ends native to the current OS. | |
412 |
|
412 | |||
413 | If the optional backup argument is given as false, no backup of the |
|
413 | If the optional backup argument is given as false, no backup of the | |
414 | original file is left. """ |
|
414 | original file is left. """ | |
415 |
|
415 | |||
416 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} |
|
416 | backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} | |
417 |
|
417 | |||
418 | bak_filename = filename + backup_suffixes[os.name] |
|
418 | bak_filename = filename + backup_suffixes[os.name] | |
419 |
|
419 | |||
420 | original = open(filename).read() |
|
420 | original = open(filename).read() | |
421 | shutil.copy2(filename,bak_filename) |
|
421 | shutil.copy2(filename,bak_filename) | |
422 | try: |
|
422 | try: | |
423 | new = open(filename,'wb') |
|
423 | new = open(filename,'wb') | |
424 | new.write(os.linesep.join(original.splitlines())) |
|
424 | new.write(os.linesep.join(original.splitlines())) | |
425 | new.write(os.linesep) # ALWAYS put an eol at the end of the file |
|
425 | new.write(os.linesep) # ALWAYS put an eol at the end of the file | |
426 | new.close() |
|
426 | new.close() | |
427 | except: |
|
427 | except: | |
428 | os.rename(bak_filename,filename) |
|
428 | os.rename(bak_filename,filename) | |
429 | if not backup: |
|
429 | if not backup: | |
430 | try: |
|
430 | try: | |
431 | os.remove(bak_filename) |
|
431 | os.remove(bak_filename) | |
432 | except: |
|
432 | except: | |
433 | pass |
|
433 | pass | |
434 |
|
434 | |||
435 |
|
435 | |||
436 | def list_strings(arg): |
|
436 | def list_strings(arg): | |
437 | """Always return a list of strings, given a string or list of strings |
|
437 | """Always return a list of strings, given a string or list of strings | |
438 | as input. |
|
438 | as input. | |
439 |
|
439 | |||
440 | :Examples: |
|
440 | :Examples: | |
441 |
|
441 | |||
442 | In [7]: list_strings('A single string') |
|
442 | In [7]: list_strings('A single string') | |
443 | Out[7]: ['A single string'] |
|
443 | Out[7]: ['A single string'] | |
444 |
|
444 | |||
445 | In [8]: list_strings(['A single string in a list']) |
|
445 | In [8]: list_strings(['A single string in a list']) | |
446 | Out[8]: ['A single string in a list'] |
|
446 | Out[8]: ['A single string in a list'] | |
447 |
|
447 | |||
448 | In [9]: list_strings(['A','list','of','strings']) |
|
448 | In [9]: list_strings(['A','list','of','strings']) | |
449 | Out[9]: ['A', 'list', 'of', 'strings'] |
|
449 | Out[9]: ['A', 'list', 'of', 'strings'] | |
450 | """ |
|
450 | """ | |
451 |
|
451 | |||
452 | if isinstance(arg,basestring): return [arg] |
|
452 | if isinstance(arg,basestring): return [arg] | |
453 | else: return arg |
|
453 | else: return arg | |
454 |
|
454 | |||
455 |
|
455 | |||
456 | def marquee(txt='',width=78,mark='*'): |
|
456 | def marquee(txt='',width=78,mark='*'): | |
457 | """Return the input string centered in a 'marquee'. |
|
457 | """Return the input string centered in a 'marquee'. | |
458 |
|
458 | |||
459 | :Examples: |
|
459 | :Examples: | |
460 |
|
460 | |||
461 | In [16]: marquee('A test',40) |
|
461 | In [16]: marquee('A test',40) | |
462 | Out[16]: '**************** A test ****************' |
|
462 | Out[16]: '**************** A test ****************' | |
463 |
|
463 | |||
464 | In [17]: marquee('A test',40,'-') |
|
464 | In [17]: marquee('A test',40,'-') | |
465 | Out[17]: '---------------- A test ----------------' |
|
465 | Out[17]: '---------------- A test ----------------' | |
466 |
|
466 | |||
467 | In [18]: marquee('A test',40,' ') |
|
467 | In [18]: marquee('A test',40,' ') | |
468 | Out[18]: ' A test ' |
|
468 | Out[18]: ' A test ' | |
469 |
|
469 | |||
470 | """ |
|
470 | """ | |
471 | if not txt: |
|
471 | if not txt: | |
472 | return (mark*width)[:width] |
|
472 | return (mark*width)[:width] | |
473 | nmark = (width-len(txt)-2)/len(mark)/2 |
|
473 | nmark = (width-len(txt)-2)/len(mark)/2 | |
474 | if nmark < 0: nmark =0 |
|
474 | if nmark < 0: nmark =0 | |
475 | marks = mark*nmark |
|
475 | marks = mark*nmark | |
476 | return '%s %s %s' % (marks,txt,marks) |
|
476 | return '%s %s %s' % (marks,txt,marks) | |
477 |
|
477 | |||
478 |
|
478 | |||
479 | ini_spaces_re = re.compile(r'^(\s+)') |
|
479 | ini_spaces_re = re.compile(r'^(\s+)') | |
480 |
|
480 | |||
481 | def num_ini_spaces(strng): |
|
481 | def num_ini_spaces(strng): | |
482 | """Return the number of initial spaces in a string""" |
|
482 | """Return the number of initial spaces in a string""" | |
483 |
|
483 | |||
484 | ini_spaces = ini_spaces_re.match(strng) |
|
484 | ini_spaces = ini_spaces_re.match(strng) | |
485 | if ini_spaces: |
|
485 | if ini_spaces: | |
486 | return ini_spaces.end() |
|
486 | return ini_spaces.end() | |
487 | else: |
|
487 | else: | |
488 | return 0 |
|
488 | return 0 | |
489 |
|
489 | |||
|
490 | ||||
|
491 | def format_screen(strng): | |||
|
492 | """Format a string for screen printing. | |||
|
493 | ||||
|
494 | This removes some latex-type format codes.""" | |||
|
495 | # Paragraph continue | |||
|
496 | par_re = re.compile(r'\\$',re.MULTILINE) | |||
|
497 | strng = par_re.sub('',strng) | |||
|
498 | return strng | |||
|
499 |
General Comments 0
You need to be logged in to leave comments.
Login now