Show More
@@ -1,45 +1,71 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | Autocall capabilities for IPython.core. |
|
4 | Autocall capabilities for IPython.core. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
|
10 | * Thomas Kluyver | |||
10 |
|
11 | |||
11 | Notes |
|
12 | Notes | |
12 | ----- |
|
13 | ----- | |
13 | """ |
|
14 | """ | |
14 |
|
15 | |||
15 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
17 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
18 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
20 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
21 |
|
22 | |||
22 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
24 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
25 |
|
26 | |||
26 |
|
27 | |||
27 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
28 | # Code |
|
29 | # Code | |
29 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
30 |
|
31 | |||
31 | class IPyAutocall(object): |
|
32 | class IPyAutocall(object): | |
32 | """ Instances of this class are always autocalled |
|
33 | """ Instances of this class are always autocalled | |
33 |
|
34 | |||
34 | This happens regardless of 'autocall' variable state. Use this to |
|
35 | This happens regardless of 'autocall' variable state. Use this to | |
35 | develop macro-like mechanisms. |
|
36 | develop macro-like mechanisms. | |
36 | """ |
|
37 | """ | |
|
38 | _ip = None | |||
|
39 | rewrite = True | |||
|
40 | def __init__(self, ip=None): | |||
|
41 | self._ip = ip | |||
37 |
|
42 | |||
38 | def set_ip(self,ip): |
|
43 | def set_ip(self, ip): | |
39 | """ Will be used to set _ip point to current ipython instance b/f call |
|
44 | """ Will be used to set _ip point to current ipython instance b/f call | |
40 |
|
45 | |||
41 | Override this method if you don't want this to happen. |
|
46 | Override this method if you don't want this to happen. | |
42 |
|
47 | |||
43 | """ |
|
48 | """ | |
44 | self._ip = ip |
|
49 | self._ip = ip | |
45 |
|
50 | |||
|
51 | ||||
|
52 | class ExitAutocall(IPyAutocall): | |||
|
53 | """An autocallable object which will be added to the user namespace so that | |||
|
54 | exit, exit(), quit or quit() are all valid ways to close the shell.""" | |||
|
55 | rewrite = False | |||
|
56 | ||||
|
57 | def __call__(self): | |||
|
58 | self._ip.ask_exit() | |||
|
59 | ||||
|
60 | class ZMQExitAutocall(ExitAutocall): | |||
|
61 | """Exit IPython. Autocallable, so it needn't be explicitly called. | |||
|
62 | ||||
|
63 | Parameters | |||
|
64 | ---------- | |||
|
65 | keep_kernel : bool | |||
|
66 | If True, leave the kernel alive. Otherwise, tell the kernel to exit too | |||
|
67 | (default). | |||
|
68 | """ | |||
|
69 | def __call__(self, keep_kernel=False): | |||
|
70 | self._ip.keepkernel_on_exit = keep_kernel | |||
|
71 | self._ip.ask_exit() |
@@ -1,2608 +1,2615 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
19 |
|
19 | |||
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import ast |
|
23 | import ast | |
24 | import atexit |
|
24 | import atexit | |
25 | import codeop |
|
25 | import codeop | |
26 | import inspect |
|
26 | import inspect | |
27 | import os |
|
27 | import os | |
28 | import re |
|
28 | import re | |
29 | import sys |
|
29 | import sys | |
30 | import tempfile |
|
30 | import tempfile | |
31 | import types |
|
31 | import types | |
32 | from contextlib import nested |
|
32 | from contextlib import nested | |
33 |
|
33 | |||
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.core import debugger, oinspect |
|
35 | from IPython.core import debugger, oinspect | |
36 | from IPython.core import history as ipcorehist |
|
36 | from IPython.core import history as ipcorehist | |
37 | from IPython.core import page |
|
37 | from IPython.core import page | |
38 | from IPython.core import prefilter |
|
38 | from IPython.core import prefilter | |
39 | from IPython.core import shadowns |
|
39 | from IPython.core import shadowns | |
40 | from IPython.core import ultratb |
|
40 | from IPython.core import ultratb | |
41 | from IPython.core.alias import AliasManager |
|
41 | from IPython.core.alias import AliasManager | |
|
42 | from IPython.core.autocall import ExitAutocall | |||
42 | from IPython.core.builtin_trap import BuiltinTrap |
|
43 | from IPython.core.builtin_trap import BuiltinTrap | |
43 | from IPython.core.compilerop import CachingCompiler |
|
44 | from IPython.core.compilerop import CachingCompiler | |
44 | from IPython.core.display_trap import DisplayTrap |
|
45 | from IPython.core.display_trap import DisplayTrap | |
45 | from IPython.core.displayhook import DisplayHook |
|
46 | from IPython.core.displayhook import DisplayHook | |
46 | from IPython.core.displaypub import DisplayPublisher |
|
47 | from IPython.core.displaypub import DisplayPublisher | |
47 | from IPython.core.error import TryNext, UsageError |
|
48 | from IPython.core.error import TryNext, UsageError | |
48 | from IPython.core.extensions import ExtensionManager |
|
49 | from IPython.core.extensions import ExtensionManager | |
49 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
50 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
50 | from IPython.core.formatters import DisplayFormatter |
|
51 | from IPython.core.formatters import DisplayFormatter | |
51 | from IPython.core.history import HistoryManager |
|
52 | from IPython.core.history import HistoryManager | |
52 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
53 | from IPython.core.inputsplitter import IPythonInputSplitter | |
53 | from IPython.core.logger import Logger |
|
54 | from IPython.core.logger import Logger | |
54 | from IPython.core.macro import Macro |
|
55 | from IPython.core.macro import Macro | |
55 | from IPython.core.magic import Magic |
|
56 | from IPython.core.magic import Magic | |
56 | from IPython.core.payload import PayloadManager |
|
57 | from IPython.core.payload import PayloadManager | |
57 | from IPython.core.plugin import PluginManager |
|
58 | from IPython.core.plugin import PluginManager | |
58 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
59 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
59 | from IPython.external.Itpl import ItplNS |
|
60 | from IPython.external.Itpl import ItplNS | |
60 | from IPython.utils import PyColorize |
|
61 | from IPython.utils import PyColorize | |
61 | from IPython.utils import io |
|
62 | from IPython.utils import io | |
62 | from IPython.utils.doctestreload import doctest_reload |
|
63 | from IPython.utils.doctestreload import doctest_reload | |
63 | from IPython.utils.io import ask_yes_no, rprint |
|
64 | from IPython.utils.io import ask_yes_no, rprint | |
64 | from IPython.utils.ipstruct import Struct |
|
65 | from IPython.utils.ipstruct import Struct | |
65 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
66 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
66 | from IPython.utils.pickleshare import PickleShareDB |
|
67 | from IPython.utils.pickleshare import PickleShareDB | |
67 | from IPython.utils.process import system, getoutput |
|
68 | from IPython.utils.process import system, getoutput | |
68 | from IPython.utils.strdispatch import StrDispatch |
|
69 | from IPython.utils.strdispatch import StrDispatch | |
69 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
70 | from IPython.utils.syspathcontext import prepended_to_syspath | |
70 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
71 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
71 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
72 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
72 | List, Unicode, Instance, Type) |
|
73 | List, Unicode, Instance, Type) | |
73 | from IPython.utils.warn import warn, error, fatal |
|
74 | from IPython.utils.warn import warn, error, fatal | |
74 | import IPython.core.hooks |
|
75 | import IPython.core.hooks | |
75 |
|
76 | |||
76 | #----------------------------------------------------------------------------- |
|
77 | #----------------------------------------------------------------------------- | |
77 | # Globals |
|
78 | # Globals | |
78 | #----------------------------------------------------------------------------- |
|
79 | #----------------------------------------------------------------------------- | |
79 |
|
80 | |||
80 | # compiled regexps for autoindent management |
|
81 | # compiled regexps for autoindent management | |
81 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
82 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
82 |
|
83 | |||
83 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
84 | # Utilities |
|
85 | # Utilities | |
85 | #----------------------------------------------------------------------------- |
|
86 | #----------------------------------------------------------------------------- | |
86 |
|
87 | |||
87 | # store the builtin raw_input globally, and use this always, in case user code |
|
88 | # store the builtin raw_input globally, and use this always, in case user code | |
88 | # overwrites it (like wx.py.PyShell does) |
|
89 | # overwrites it (like wx.py.PyShell does) | |
89 | raw_input_original = raw_input |
|
90 | raw_input_original = raw_input | |
90 |
|
91 | |||
91 | def softspace(file, newvalue): |
|
92 | def softspace(file, newvalue): | |
92 | """Copied from code.py, to remove the dependency""" |
|
93 | """Copied from code.py, to remove the dependency""" | |
93 |
|
94 | |||
94 | oldvalue = 0 |
|
95 | oldvalue = 0 | |
95 | try: |
|
96 | try: | |
96 | oldvalue = file.softspace |
|
97 | oldvalue = file.softspace | |
97 | except AttributeError: |
|
98 | except AttributeError: | |
98 | pass |
|
99 | pass | |
99 | try: |
|
100 | try: | |
100 | file.softspace = newvalue |
|
101 | file.softspace = newvalue | |
101 | except (AttributeError, TypeError): |
|
102 | except (AttributeError, TypeError): | |
102 | # "attribute-less object" or "read-only attributes" |
|
103 | # "attribute-less object" or "read-only attributes" | |
103 | pass |
|
104 | pass | |
104 | return oldvalue |
|
105 | return oldvalue | |
105 |
|
106 | |||
106 |
|
107 | |||
107 | def no_op(*a, **kw): pass |
|
108 | def no_op(*a, **kw): pass | |
108 |
|
109 | |||
109 | class SpaceInInput(Exception): pass |
|
110 | class SpaceInInput(Exception): pass | |
110 |
|
111 | |||
111 | class Bunch: pass |
|
112 | class Bunch: pass | |
112 |
|
113 | |||
113 |
|
114 | |||
114 | def get_default_colors(): |
|
115 | def get_default_colors(): | |
115 | if sys.platform=='darwin': |
|
116 | if sys.platform=='darwin': | |
116 | return "LightBG" |
|
117 | return "LightBG" | |
117 | elif os.name=='nt': |
|
118 | elif os.name=='nt': | |
118 | return 'Linux' |
|
119 | return 'Linux' | |
119 | else: |
|
120 | else: | |
120 | return 'Linux' |
|
121 | return 'Linux' | |
121 |
|
122 | |||
122 |
|
123 | |||
123 | class SeparateStr(Str): |
|
124 | class SeparateStr(Str): | |
124 | """A Str subclass to validate separate_in, separate_out, etc. |
|
125 | """A Str subclass to validate separate_in, separate_out, etc. | |
125 |
|
126 | |||
126 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
127 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
127 | """ |
|
128 | """ | |
128 |
|
129 | |||
129 | def validate(self, obj, value): |
|
130 | def validate(self, obj, value): | |
130 | if value == '0': value = '' |
|
131 | if value == '0': value = '' | |
131 | value = value.replace('\\n','\n') |
|
132 | value = value.replace('\\n','\n') | |
132 | return super(SeparateStr, self).validate(obj, value) |
|
133 | return super(SeparateStr, self).validate(obj, value) | |
133 |
|
134 | |||
134 | class MultipleInstanceError(Exception): |
|
135 | class MultipleInstanceError(Exception): | |
135 | pass |
|
136 | pass | |
136 |
|
137 | |||
137 | class ReadlineNoRecord(object): |
|
138 | class ReadlineNoRecord(object): | |
138 | """Context manager to execute some code, then reload readline history |
|
139 | """Context manager to execute some code, then reload readline history | |
139 | so that interactive input to the code doesn't appear when pressing up.""" |
|
140 | so that interactive input to the code doesn't appear when pressing up.""" | |
140 | def __init__(self, shell): |
|
141 | def __init__(self, shell): | |
141 | self.shell = shell |
|
142 | self.shell = shell | |
142 | self._nested_level = 0 |
|
143 | self._nested_level = 0 | |
143 |
|
144 | |||
144 | def __enter__(self): |
|
145 | def __enter__(self): | |
145 | if self._nested_level == 0: |
|
146 | if self._nested_level == 0: | |
146 | self.orig_length = self.current_length() |
|
147 | self.orig_length = self.current_length() | |
147 | self.readline_tail = self.get_readline_tail() |
|
148 | self.readline_tail = self.get_readline_tail() | |
148 | self._nested_level += 1 |
|
149 | self._nested_level += 1 | |
149 |
|
150 | |||
150 | def __exit__(self, type, value, traceback): |
|
151 | def __exit__(self, type, value, traceback): | |
151 | self._nested_level -= 1 |
|
152 | self._nested_level -= 1 | |
152 | if self._nested_level == 0: |
|
153 | if self._nested_level == 0: | |
153 | # Try clipping the end if it's got longer |
|
154 | # Try clipping the end if it's got longer | |
154 | e = self.current_length() - self.orig_length |
|
155 | e = self.current_length() - self.orig_length | |
155 | if e > 0: |
|
156 | if e > 0: | |
156 | for _ in range(e): |
|
157 | for _ in range(e): | |
157 | self.shell.readline.remove_history_item(self.orig_length) |
|
158 | self.shell.readline.remove_history_item(self.orig_length) | |
158 |
|
159 | |||
159 | # If it still doesn't match, just reload readline history. |
|
160 | # If it still doesn't match, just reload readline history. | |
160 | if self.current_length() != self.orig_length \ |
|
161 | if self.current_length() != self.orig_length \ | |
161 | or self.get_readline_tail() != self.readline_tail: |
|
162 | or self.get_readline_tail() != self.readline_tail: | |
162 | self.shell.refill_readline_hist() |
|
163 | self.shell.refill_readline_hist() | |
163 | # Returning False will cause exceptions to propagate |
|
164 | # Returning False will cause exceptions to propagate | |
164 | return False |
|
165 | return False | |
165 |
|
166 | |||
166 | def current_length(self): |
|
167 | def current_length(self): | |
167 | return self.shell.readline.get_current_history_length() |
|
168 | return self.shell.readline.get_current_history_length() | |
168 |
|
169 | |||
169 | def get_readline_tail(self, n=10): |
|
170 | def get_readline_tail(self, n=10): | |
170 | """Get the last n items in readline history.""" |
|
171 | """Get the last n items in readline history.""" | |
171 | end = self.shell.readline.get_current_history_length() + 1 |
|
172 | end = self.shell.readline.get_current_history_length() + 1 | |
172 | start = max(end-n, 1) |
|
173 | start = max(end-n, 1) | |
173 | ghi = self.shell.readline.get_history_item |
|
174 | ghi = self.shell.readline.get_history_item | |
174 | return [ghi(x) for x in range(start, end)] |
|
175 | return [ghi(x) for x in range(start, end)] | |
175 |
|
176 | |||
176 |
|
177 | |||
177 | #----------------------------------------------------------------------------- |
|
178 | #----------------------------------------------------------------------------- | |
178 | # Main IPython class |
|
179 | # Main IPython class | |
179 | #----------------------------------------------------------------------------- |
|
180 | #----------------------------------------------------------------------------- | |
180 |
|
181 | |||
181 | class InteractiveShell(Configurable, Magic): |
|
182 | class InteractiveShell(Configurable, Magic): | |
182 | """An enhanced, interactive shell for Python.""" |
|
183 | """An enhanced, interactive shell for Python.""" | |
183 |
|
184 | |||
184 | _instance = None |
|
185 | _instance = None | |
185 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
186 | autocall = Enum((0,1,2), default_value=1, config=True) | |
186 | # TODO: remove all autoindent logic and put into frontends. |
|
187 | # TODO: remove all autoindent logic and put into frontends. | |
187 | # We can't do this yet because even runlines uses the autoindent. |
|
188 | # We can't do this yet because even runlines uses the autoindent. | |
188 | autoindent = CBool(True, config=True) |
|
189 | autoindent = CBool(True, config=True) | |
189 | automagic = CBool(True, config=True) |
|
190 | automagic = CBool(True, config=True) | |
190 | cache_size = Int(1000, config=True) |
|
191 | cache_size = Int(1000, config=True) | |
191 | color_info = CBool(True, config=True) |
|
192 | color_info = CBool(True, config=True) | |
192 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
193 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
193 | default_value=get_default_colors(), config=True) |
|
194 | default_value=get_default_colors(), config=True) | |
194 | debug = CBool(False, config=True) |
|
195 | debug = CBool(False, config=True) | |
195 | deep_reload = CBool(False, config=True) |
|
196 | deep_reload = CBool(False, config=True) | |
196 | display_formatter = Instance(DisplayFormatter) |
|
197 | display_formatter = Instance(DisplayFormatter) | |
197 | displayhook_class = Type(DisplayHook) |
|
198 | displayhook_class = Type(DisplayHook) | |
198 | display_pub_class = Type(DisplayPublisher) |
|
199 | display_pub_class = Type(DisplayPublisher) | |
199 |
|
200 | |||
200 | exit_now = CBool(False) |
|
201 | exit_now = CBool(False) | |
|
202 | exiter = Instance(ExitAutocall) | |||
|
203 | def _exiter_default(self): | |||
|
204 | return ExitAutocall(self) | |||
201 | # Monotonically increasing execution counter |
|
205 | # Monotonically increasing execution counter | |
202 | execution_count = Int(1) |
|
206 | execution_count = Int(1) | |
203 | filename = Unicode("<ipython console>") |
|
207 | filename = Unicode("<ipython console>") | |
204 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
208 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
205 |
|
209 | |||
206 | # Input splitter, to split entire cells of input into either individual |
|
210 | # Input splitter, to split entire cells of input into either individual | |
207 | # interactive statements or whole blocks. |
|
211 | # interactive statements or whole blocks. | |
208 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
212 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
209 | (), {}) |
|
213 | (), {}) | |
210 | logstart = CBool(False, config=True) |
|
214 | logstart = CBool(False, config=True) | |
211 | logfile = Unicode('', config=True) |
|
215 | logfile = Unicode('', config=True) | |
212 | logappend = Unicode('', config=True) |
|
216 | logappend = Unicode('', config=True) | |
213 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
217 | object_info_string_level = Enum((0,1,2), default_value=0, | |
214 | config=True) |
|
218 | config=True) | |
215 | pdb = CBool(False, config=True) |
|
219 | pdb = CBool(False, config=True) | |
216 |
|
220 | |||
217 | profile = Unicode('', config=True) |
|
221 | profile = Unicode('', config=True) | |
218 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
222 | prompt_in1 = Str('In [\\#]: ', config=True) | |
219 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
223 | prompt_in2 = Str(' .\\D.: ', config=True) | |
220 | prompt_out = Str('Out[\\#]: ', config=True) |
|
224 | prompt_out = Str('Out[\\#]: ', config=True) | |
221 | prompts_pad_left = CBool(True, config=True) |
|
225 | prompts_pad_left = CBool(True, config=True) | |
222 | quiet = CBool(False, config=True) |
|
226 | quiet = CBool(False, config=True) | |
223 |
|
227 | |||
224 | history_length = Int(10000, config=True) |
|
228 | history_length = Int(10000, config=True) | |
225 |
|
229 | |||
226 | # The readline stuff will eventually be moved to the terminal subclass |
|
230 | # The readline stuff will eventually be moved to the terminal subclass | |
227 | # but for now, we can't do that as readline is welded in everywhere. |
|
231 | # but for now, we can't do that as readline is welded in everywhere. | |
228 | readline_use = CBool(True, config=True) |
|
232 | readline_use = CBool(True, config=True) | |
229 | readline_merge_completions = CBool(True, config=True) |
|
233 | readline_merge_completions = CBool(True, config=True) | |
230 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
234 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) | |
231 | readline_remove_delims = Str('-/~', config=True) |
|
235 | readline_remove_delims = Str('-/~', config=True) | |
232 | readline_parse_and_bind = List([ |
|
236 | readline_parse_and_bind = List([ | |
233 | 'tab: complete', |
|
237 | 'tab: complete', | |
234 | '"\C-l": clear-screen', |
|
238 | '"\C-l": clear-screen', | |
235 | 'set show-all-if-ambiguous on', |
|
239 | 'set show-all-if-ambiguous on', | |
236 | '"\C-o": tab-insert', |
|
240 | '"\C-o": tab-insert', | |
237 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff |
|
241 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff | |
238 | # crash IPython. |
|
242 | # crash IPython. | |
239 | '"\M-o": "\d\d\d\d"', |
|
243 | '"\M-o": "\d\d\d\d"', | |
240 | '"\M-I": "\d\d\d\d"', |
|
244 | '"\M-I": "\d\d\d\d"', | |
241 | '"\C-r": reverse-search-history', |
|
245 | '"\C-r": reverse-search-history', | |
242 | '"\C-s": forward-search-history', |
|
246 | '"\C-s": forward-search-history', | |
243 | '"\C-p": history-search-backward', |
|
247 | '"\C-p": history-search-backward', | |
244 | '"\C-n": history-search-forward', |
|
248 | '"\C-n": history-search-forward', | |
245 | '"\e[A": history-search-backward', |
|
249 | '"\e[A": history-search-backward', | |
246 | '"\e[B": history-search-forward', |
|
250 | '"\e[B": history-search-forward', | |
247 | '"\C-k": kill-line', |
|
251 | '"\C-k": kill-line', | |
248 | '"\C-u": unix-line-discard', |
|
252 | '"\C-u": unix-line-discard', | |
249 | ], allow_none=False, config=True) |
|
253 | ], allow_none=False, config=True) | |
250 |
|
254 | |||
251 | # TODO: this part of prompt management should be moved to the frontends. |
|
255 | # TODO: this part of prompt management should be moved to the frontends. | |
252 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
256 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
253 | separate_in = SeparateStr('\n', config=True) |
|
257 | separate_in = SeparateStr('\n', config=True) | |
254 | separate_out = SeparateStr('', config=True) |
|
258 | separate_out = SeparateStr('', config=True) | |
255 | separate_out2 = SeparateStr('', config=True) |
|
259 | separate_out2 = SeparateStr('', config=True) | |
256 | wildcards_case_sensitive = CBool(True, config=True) |
|
260 | wildcards_case_sensitive = CBool(True, config=True) | |
257 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
261 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
258 | default_value='Context', config=True) |
|
262 | default_value='Context', config=True) | |
259 |
|
263 | |||
260 | # Subcomponents of InteractiveShell |
|
264 | # Subcomponents of InteractiveShell | |
261 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
265 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
262 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
266 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
263 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
267 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
264 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
268 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
265 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
269 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
266 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
270 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
267 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
271 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
268 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
272 | history_manager = Instance('IPython.core.history.HistoryManager') | |
269 |
|
273 | |||
270 | # Private interface |
|
274 | # Private interface | |
271 | _post_execute = set() |
|
275 | _post_execute = set() | |
272 |
|
276 | |||
273 | def __init__(self, config=None, ipython_dir=None, |
|
277 | def __init__(self, config=None, ipython_dir=None, | |
274 | user_ns=None, user_global_ns=None, |
|
278 | user_ns=None, user_global_ns=None, | |
275 | custom_exceptions=((), None)): |
|
279 | custom_exceptions=((), None)): | |
276 |
|
280 | |||
277 | # This is where traits with a config_key argument are updated |
|
281 | # This is where traits with a config_key argument are updated | |
278 | # from the values on config. |
|
282 | # from the values on config. | |
279 | super(InteractiveShell, self).__init__(config=config) |
|
283 | super(InteractiveShell, self).__init__(config=config) | |
280 |
|
284 | |||
281 | # These are relatively independent and stateless |
|
285 | # These are relatively independent and stateless | |
282 | self.init_ipython_dir(ipython_dir) |
|
286 | self.init_ipython_dir(ipython_dir) | |
283 | self.init_instance_attrs() |
|
287 | self.init_instance_attrs() | |
284 | self.init_environment() |
|
288 | self.init_environment() | |
285 |
|
289 | |||
286 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
290 | # Create namespaces (user_ns, user_global_ns, etc.) | |
287 | self.init_create_namespaces(user_ns, user_global_ns) |
|
291 | self.init_create_namespaces(user_ns, user_global_ns) | |
288 | # This has to be done after init_create_namespaces because it uses |
|
292 | # This has to be done after init_create_namespaces because it uses | |
289 | # something in self.user_ns, but before init_sys_modules, which |
|
293 | # something in self.user_ns, but before init_sys_modules, which | |
290 | # is the first thing to modify sys. |
|
294 | # is the first thing to modify sys. | |
291 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
295 | # TODO: When we override sys.stdout and sys.stderr before this class | |
292 | # is created, we are saving the overridden ones here. Not sure if this |
|
296 | # is created, we are saving the overridden ones here. Not sure if this | |
293 | # is what we want to do. |
|
297 | # is what we want to do. | |
294 | self.save_sys_module_state() |
|
298 | self.save_sys_module_state() | |
295 | self.init_sys_modules() |
|
299 | self.init_sys_modules() | |
296 |
|
300 | |||
297 | # While we're trying to have each part of the code directly access what |
|
301 | # While we're trying to have each part of the code directly access what | |
298 | # it needs without keeping redundant references to objects, we have too |
|
302 | # it needs without keeping redundant references to objects, we have too | |
299 | # much legacy code that expects ip.db to exist. |
|
303 | # much legacy code that expects ip.db to exist. | |
300 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) |
|
304 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) | |
301 |
|
305 | |||
302 | self.init_history() |
|
306 | self.init_history() | |
303 | self.init_encoding() |
|
307 | self.init_encoding() | |
304 | self.init_prefilter() |
|
308 | self.init_prefilter() | |
305 |
|
309 | |||
306 | Magic.__init__(self, self) |
|
310 | Magic.__init__(self, self) | |
307 |
|
311 | |||
308 | self.init_syntax_highlighting() |
|
312 | self.init_syntax_highlighting() | |
309 | self.init_hooks() |
|
313 | self.init_hooks() | |
310 | self.init_pushd_popd_magic() |
|
314 | self.init_pushd_popd_magic() | |
311 | # self.init_traceback_handlers use to be here, but we moved it below |
|
315 | # self.init_traceback_handlers use to be here, but we moved it below | |
312 | # because it and init_io have to come after init_readline. |
|
316 | # because it and init_io have to come after init_readline. | |
313 | self.init_user_ns() |
|
317 | self.init_user_ns() | |
314 | self.init_logger() |
|
318 | self.init_logger() | |
315 | self.init_alias() |
|
319 | self.init_alias() | |
316 | self.init_builtins() |
|
320 | self.init_builtins() | |
317 |
|
321 | |||
318 | # pre_config_initialization |
|
322 | # pre_config_initialization | |
319 |
|
323 | |||
320 | # The next section should contain everything that was in ipmaker. |
|
324 | # The next section should contain everything that was in ipmaker. | |
321 | self.init_logstart() |
|
325 | self.init_logstart() | |
322 |
|
326 | |||
323 | # The following was in post_config_initialization |
|
327 | # The following was in post_config_initialization | |
324 | self.init_inspector() |
|
328 | self.init_inspector() | |
325 | # init_readline() must come before init_io(), because init_io uses |
|
329 | # init_readline() must come before init_io(), because init_io uses | |
326 | # readline related things. |
|
330 | # readline related things. | |
327 | self.init_readline() |
|
331 | self.init_readline() | |
328 | # init_completer must come after init_readline, because it needs to |
|
332 | # init_completer must come after init_readline, because it needs to | |
329 | # know whether readline is present or not system-wide to configure the |
|
333 | # know whether readline is present or not system-wide to configure the | |
330 | # completers, since the completion machinery can now operate |
|
334 | # completers, since the completion machinery can now operate | |
331 | # independently of readline (e.g. over the network) |
|
335 | # independently of readline (e.g. over the network) | |
332 | self.init_completer() |
|
336 | self.init_completer() | |
333 | # TODO: init_io() needs to happen before init_traceback handlers |
|
337 | # TODO: init_io() needs to happen before init_traceback handlers | |
334 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
338 | # because the traceback handlers hardcode the stdout/stderr streams. | |
335 | # This logic in in debugger.Pdb and should eventually be changed. |
|
339 | # This logic in in debugger.Pdb and should eventually be changed. | |
336 | self.init_io() |
|
340 | self.init_io() | |
337 | self.init_traceback_handlers(custom_exceptions) |
|
341 | self.init_traceback_handlers(custom_exceptions) | |
338 | self.init_prompts() |
|
342 | self.init_prompts() | |
339 | self.init_display_formatter() |
|
343 | self.init_display_formatter() | |
340 | self.init_display_pub() |
|
344 | self.init_display_pub() | |
341 | self.init_displayhook() |
|
345 | self.init_displayhook() | |
342 | self.init_reload_doctest() |
|
346 | self.init_reload_doctest() | |
343 | self.init_magics() |
|
347 | self.init_magics() | |
344 | self.init_pdb() |
|
348 | self.init_pdb() | |
345 | self.init_extension_manager() |
|
349 | self.init_extension_manager() | |
346 | self.init_plugin_manager() |
|
350 | self.init_plugin_manager() | |
347 | self.init_payload() |
|
351 | self.init_payload() | |
348 | self.hooks.late_startup_hook() |
|
352 | self.hooks.late_startup_hook() | |
349 | atexit.register(self.atexit_operations) |
|
353 | atexit.register(self.atexit_operations) | |
350 |
|
354 | |||
351 | @classmethod |
|
355 | @classmethod | |
352 | def instance(cls, *args, **kwargs): |
|
356 | def instance(cls, *args, **kwargs): | |
353 | """Returns a global InteractiveShell instance.""" |
|
357 | """Returns a global InteractiveShell instance.""" | |
354 | if cls._instance is None: |
|
358 | if cls._instance is None: | |
355 | inst = cls(*args, **kwargs) |
|
359 | inst = cls(*args, **kwargs) | |
356 | # Now make sure that the instance will also be returned by |
|
360 | # Now make sure that the instance will also be returned by | |
357 | # the subclasses instance attribute. |
|
361 | # the subclasses instance attribute. | |
358 | for subclass in cls.mro(): |
|
362 | for subclass in cls.mro(): | |
359 | if issubclass(cls, subclass) and \ |
|
363 | if issubclass(cls, subclass) and \ | |
360 | issubclass(subclass, InteractiveShell): |
|
364 | issubclass(subclass, InteractiveShell): | |
361 | subclass._instance = inst |
|
365 | subclass._instance = inst | |
362 | else: |
|
366 | else: | |
363 | break |
|
367 | break | |
364 | if isinstance(cls._instance, cls): |
|
368 | if isinstance(cls._instance, cls): | |
365 | return cls._instance |
|
369 | return cls._instance | |
366 | else: |
|
370 | else: | |
367 | raise MultipleInstanceError( |
|
371 | raise MultipleInstanceError( | |
368 | 'Multiple incompatible subclass instances of ' |
|
372 | 'Multiple incompatible subclass instances of ' | |
369 | 'InteractiveShell are being created.' |
|
373 | 'InteractiveShell are being created.' | |
370 | ) |
|
374 | ) | |
371 |
|
375 | |||
372 | @classmethod |
|
376 | @classmethod | |
373 | def initialized(cls): |
|
377 | def initialized(cls): | |
374 | return hasattr(cls, "_instance") |
|
378 | return hasattr(cls, "_instance") | |
375 |
|
379 | |||
376 | def get_ipython(self): |
|
380 | def get_ipython(self): | |
377 | """Return the currently running IPython instance.""" |
|
381 | """Return the currently running IPython instance.""" | |
378 | return self |
|
382 | return self | |
379 |
|
383 | |||
380 | #------------------------------------------------------------------------- |
|
384 | #------------------------------------------------------------------------- | |
381 | # Trait changed handlers |
|
385 | # Trait changed handlers | |
382 | #------------------------------------------------------------------------- |
|
386 | #------------------------------------------------------------------------- | |
383 |
|
387 | |||
384 | def _ipython_dir_changed(self, name, new): |
|
388 | def _ipython_dir_changed(self, name, new): | |
385 | if not os.path.isdir(new): |
|
389 | if not os.path.isdir(new): | |
386 | os.makedirs(new, mode = 0777) |
|
390 | os.makedirs(new, mode = 0777) | |
387 |
|
391 | |||
388 | def set_autoindent(self,value=None): |
|
392 | def set_autoindent(self,value=None): | |
389 | """Set the autoindent flag, checking for readline support. |
|
393 | """Set the autoindent flag, checking for readline support. | |
390 |
|
394 | |||
391 | If called with no arguments, it acts as a toggle.""" |
|
395 | If called with no arguments, it acts as a toggle.""" | |
392 |
|
396 | |||
393 | if not self.has_readline: |
|
397 | if not self.has_readline: | |
394 | if os.name == 'posix': |
|
398 | if os.name == 'posix': | |
395 | warn("The auto-indent feature requires the readline library") |
|
399 | warn("The auto-indent feature requires the readline library") | |
396 | self.autoindent = 0 |
|
400 | self.autoindent = 0 | |
397 | return |
|
401 | return | |
398 | if value is None: |
|
402 | if value is None: | |
399 | self.autoindent = not self.autoindent |
|
403 | self.autoindent = not self.autoindent | |
400 | else: |
|
404 | else: | |
401 | self.autoindent = value |
|
405 | self.autoindent = value | |
402 |
|
406 | |||
403 | #------------------------------------------------------------------------- |
|
407 | #------------------------------------------------------------------------- | |
404 | # init_* methods called by __init__ |
|
408 | # init_* methods called by __init__ | |
405 | #------------------------------------------------------------------------- |
|
409 | #------------------------------------------------------------------------- | |
406 |
|
410 | |||
407 | def init_ipython_dir(self, ipython_dir): |
|
411 | def init_ipython_dir(self, ipython_dir): | |
408 | if ipython_dir is not None: |
|
412 | if ipython_dir is not None: | |
409 | self.ipython_dir = ipython_dir |
|
413 | self.ipython_dir = ipython_dir | |
410 | self.config.Global.ipython_dir = self.ipython_dir |
|
414 | self.config.Global.ipython_dir = self.ipython_dir | |
411 | return |
|
415 | return | |
412 |
|
416 | |||
413 | if hasattr(self.config.Global, 'ipython_dir'): |
|
417 | if hasattr(self.config.Global, 'ipython_dir'): | |
414 | self.ipython_dir = self.config.Global.ipython_dir |
|
418 | self.ipython_dir = self.config.Global.ipython_dir | |
415 | else: |
|
419 | else: | |
416 | self.ipython_dir = get_ipython_dir() |
|
420 | self.ipython_dir = get_ipython_dir() | |
417 |
|
421 | |||
418 | # All children can just read this |
|
422 | # All children can just read this | |
419 | self.config.Global.ipython_dir = self.ipython_dir |
|
423 | self.config.Global.ipython_dir = self.ipython_dir | |
420 |
|
424 | |||
421 | def init_instance_attrs(self): |
|
425 | def init_instance_attrs(self): | |
422 | self.more = False |
|
426 | self.more = False | |
423 |
|
427 | |||
424 | # command compiler |
|
428 | # command compiler | |
425 | self.compile = CachingCompiler() |
|
429 | self.compile = CachingCompiler() | |
426 |
|
430 | |||
427 | # User input buffers |
|
431 | # User input buffers | |
428 | # NOTE: these variables are slated for full removal, once we are 100% |
|
432 | # NOTE: these variables are slated for full removal, once we are 100% | |
429 | # sure that the new execution logic is solid. We will delte runlines, |
|
433 | # sure that the new execution logic is solid. We will delte runlines, | |
430 | # push_line and these buffers, as all input will be managed by the |
|
434 | # push_line and these buffers, as all input will be managed by the | |
431 | # frontends via an inputsplitter instance. |
|
435 | # frontends via an inputsplitter instance. | |
432 | self.buffer = [] |
|
436 | self.buffer = [] | |
433 | self.buffer_raw = [] |
|
437 | self.buffer_raw = [] | |
434 |
|
438 | |||
435 | # Make an empty namespace, which extension writers can rely on both |
|
439 | # Make an empty namespace, which extension writers can rely on both | |
436 | # existing and NEVER being used by ipython itself. This gives them a |
|
440 | # existing and NEVER being used by ipython itself. This gives them a | |
437 | # convenient location for storing additional information and state |
|
441 | # convenient location for storing additional information and state | |
438 | # their extensions may require, without fear of collisions with other |
|
442 | # their extensions may require, without fear of collisions with other | |
439 | # ipython names that may develop later. |
|
443 | # ipython names that may develop later. | |
440 | self.meta = Struct() |
|
444 | self.meta = Struct() | |
441 |
|
445 | |||
442 | # Object variable to store code object waiting execution. This is |
|
446 | # Object variable to store code object waiting execution. This is | |
443 | # used mainly by the multithreaded shells, but it can come in handy in |
|
447 | # used mainly by the multithreaded shells, but it can come in handy in | |
444 | # other situations. No need to use a Queue here, since it's a single |
|
448 | # other situations. No need to use a Queue here, since it's a single | |
445 | # item which gets cleared once run. |
|
449 | # item which gets cleared once run. | |
446 | self.code_to_run = None |
|
450 | self.code_to_run = None | |
447 |
|
451 | |||
448 | # Temporary files used for various purposes. Deleted at exit. |
|
452 | # Temporary files used for various purposes. Deleted at exit. | |
449 | self.tempfiles = [] |
|
453 | self.tempfiles = [] | |
450 |
|
454 | |||
451 | # Keep track of readline usage (later set by init_readline) |
|
455 | # Keep track of readline usage (later set by init_readline) | |
452 | self.has_readline = False |
|
456 | self.has_readline = False | |
453 |
|
457 | |||
454 | # keep track of where we started running (mainly for crash post-mortem) |
|
458 | # keep track of where we started running (mainly for crash post-mortem) | |
455 | # This is not being used anywhere currently. |
|
459 | # This is not being used anywhere currently. | |
456 | self.starting_dir = os.getcwd() |
|
460 | self.starting_dir = os.getcwd() | |
457 |
|
461 | |||
458 | # Indentation management |
|
462 | # Indentation management | |
459 | self.indent_current_nsp = 0 |
|
463 | self.indent_current_nsp = 0 | |
460 |
|
464 | |||
461 | def init_environment(self): |
|
465 | def init_environment(self): | |
462 | """Any changes we need to make to the user's environment.""" |
|
466 | """Any changes we need to make to the user's environment.""" | |
463 | pass |
|
467 | pass | |
464 |
|
468 | |||
465 | def init_encoding(self): |
|
469 | def init_encoding(self): | |
466 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
470 | # Get system encoding at startup time. Certain terminals (like Emacs | |
467 | # under Win32 have it set to None, and we need to have a known valid |
|
471 | # under Win32 have it set to None, and we need to have a known valid | |
468 | # encoding to use in the raw_input() method |
|
472 | # encoding to use in the raw_input() method | |
469 | try: |
|
473 | try: | |
470 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
474 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
471 | except AttributeError: |
|
475 | except AttributeError: | |
472 | self.stdin_encoding = 'ascii' |
|
476 | self.stdin_encoding = 'ascii' | |
473 |
|
477 | |||
474 | def init_syntax_highlighting(self): |
|
478 | def init_syntax_highlighting(self): | |
475 | # Python source parser/formatter for syntax highlighting |
|
479 | # Python source parser/formatter for syntax highlighting | |
476 | pyformat = PyColorize.Parser().format |
|
480 | pyformat = PyColorize.Parser().format | |
477 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
481 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
478 |
|
482 | |||
479 | def init_pushd_popd_magic(self): |
|
483 | def init_pushd_popd_magic(self): | |
480 | # for pushd/popd management |
|
484 | # for pushd/popd management | |
481 | try: |
|
485 | try: | |
482 | self.home_dir = get_home_dir() |
|
486 | self.home_dir = get_home_dir() | |
483 | except HomeDirError, msg: |
|
487 | except HomeDirError, msg: | |
484 | fatal(msg) |
|
488 | fatal(msg) | |
485 |
|
489 | |||
486 | self.dir_stack = [] |
|
490 | self.dir_stack = [] | |
487 |
|
491 | |||
488 | def init_logger(self): |
|
492 | def init_logger(self): | |
489 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
493 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
490 | logmode='rotate') |
|
494 | logmode='rotate') | |
491 |
|
495 | |||
492 | def init_logstart(self): |
|
496 | def init_logstart(self): | |
493 | """Initialize logging in case it was requested at the command line. |
|
497 | """Initialize logging in case it was requested at the command line. | |
494 | """ |
|
498 | """ | |
495 | if self.logappend: |
|
499 | if self.logappend: | |
496 | self.magic_logstart(self.logappend + ' append') |
|
500 | self.magic_logstart(self.logappend + ' append') | |
497 | elif self.logfile: |
|
501 | elif self.logfile: | |
498 | self.magic_logstart(self.logfile) |
|
502 | self.magic_logstart(self.logfile) | |
499 | elif self.logstart: |
|
503 | elif self.logstart: | |
500 | self.magic_logstart() |
|
504 | self.magic_logstart() | |
501 |
|
505 | |||
502 | def init_builtins(self): |
|
506 | def init_builtins(self): | |
503 | self.builtin_trap = BuiltinTrap(shell=self) |
|
507 | self.builtin_trap = BuiltinTrap(shell=self) | |
504 |
|
508 | |||
505 | def init_inspector(self): |
|
509 | def init_inspector(self): | |
506 | # Object inspector |
|
510 | # Object inspector | |
507 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
511 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
508 | PyColorize.ANSICodeColors, |
|
512 | PyColorize.ANSICodeColors, | |
509 | 'NoColor', |
|
513 | 'NoColor', | |
510 | self.object_info_string_level) |
|
514 | self.object_info_string_level) | |
511 |
|
515 | |||
512 | def init_io(self): |
|
516 | def init_io(self): | |
513 | # This will just use sys.stdout and sys.stderr. If you want to |
|
517 | # This will just use sys.stdout and sys.stderr. If you want to | |
514 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
518 | # override sys.stdout and sys.stderr themselves, you need to do that | |
515 | # *before* instantiating this class, because Term holds onto |
|
519 | # *before* instantiating this class, because Term holds onto | |
516 | # references to the underlying streams. |
|
520 | # references to the underlying streams. | |
517 | if sys.platform == 'win32' and self.has_readline: |
|
521 | if sys.platform == 'win32' and self.has_readline: | |
518 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
522 | Term = io.IOTerm(cout=self.readline._outputfile, | |
519 | cerr=self.readline._outputfile) |
|
523 | cerr=self.readline._outputfile) | |
520 | else: |
|
524 | else: | |
521 | Term = io.IOTerm() |
|
525 | Term = io.IOTerm() | |
522 | io.Term = Term |
|
526 | io.Term = Term | |
523 |
|
527 | |||
524 | def init_prompts(self): |
|
528 | def init_prompts(self): | |
525 | # TODO: This is a pass for now because the prompts are managed inside |
|
529 | # TODO: This is a pass for now because the prompts are managed inside | |
526 | # the DisplayHook. Once there is a separate prompt manager, this |
|
530 | # the DisplayHook. Once there is a separate prompt manager, this | |
527 | # will initialize that object and all prompt related information. |
|
531 | # will initialize that object and all prompt related information. | |
528 | pass |
|
532 | pass | |
529 |
|
533 | |||
530 | def init_display_formatter(self): |
|
534 | def init_display_formatter(self): | |
531 | self.display_formatter = DisplayFormatter(config=self.config) |
|
535 | self.display_formatter = DisplayFormatter(config=self.config) | |
532 |
|
536 | |||
533 | def init_display_pub(self): |
|
537 | def init_display_pub(self): | |
534 | self.display_pub = self.display_pub_class(config=self.config) |
|
538 | self.display_pub = self.display_pub_class(config=self.config) | |
535 |
|
539 | |||
536 | def init_displayhook(self): |
|
540 | def init_displayhook(self): | |
537 | # Initialize displayhook, set in/out prompts and printing system |
|
541 | # Initialize displayhook, set in/out prompts and printing system | |
538 | self.displayhook = self.displayhook_class( |
|
542 | self.displayhook = self.displayhook_class( | |
539 | config=self.config, |
|
543 | config=self.config, | |
540 | shell=self, |
|
544 | shell=self, | |
541 | cache_size=self.cache_size, |
|
545 | cache_size=self.cache_size, | |
542 | input_sep = self.separate_in, |
|
546 | input_sep = self.separate_in, | |
543 | output_sep = self.separate_out, |
|
547 | output_sep = self.separate_out, | |
544 | output_sep2 = self.separate_out2, |
|
548 | output_sep2 = self.separate_out2, | |
545 | ps1 = self.prompt_in1, |
|
549 | ps1 = self.prompt_in1, | |
546 | ps2 = self.prompt_in2, |
|
550 | ps2 = self.prompt_in2, | |
547 | ps_out = self.prompt_out, |
|
551 | ps_out = self.prompt_out, | |
548 | pad_left = self.prompts_pad_left |
|
552 | pad_left = self.prompts_pad_left | |
549 | ) |
|
553 | ) | |
550 | # This is a context manager that installs/revmoes the displayhook at |
|
554 | # This is a context manager that installs/revmoes the displayhook at | |
551 | # the appropriate time. |
|
555 | # the appropriate time. | |
552 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
556 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
553 |
|
557 | |||
554 | def init_reload_doctest(self): |
|
558 | def init_reload_doctest(self): | |
555 | # Do a proper resetting of doctest, including the necessary displayhook |
|
559 | # Do a proper resetting of doctest, including the necessary displayhook | |
556 | # monkeypatching |
|
560 | # monkeypatching | |
557 | try: |
|
561 | try: | |
558 | doctest_reload() |
|
562 | doctest_reload() | |
559 | except ImportError: |
|
563 | except ImportError: | |
560 | warn("doctest module does not exist.") |
|
564 | warn("doctest module does not exist.") | |
561 |
|
565 | |||
562 | #------------------------------------------------------------------------- |
|
566 | #------------------------------------------------------------------------- | |
563 | # Things related to injections into the sys module |
|
567 | # Things related to injections into the sys module | |
564 | #------------------------------------------------------------------------- |
|
568 | #------------------------------------------------------------------------- | |
565 |
|
569 | |||
566 | def save_sys_module_state(self): |
|
570 | def save_sys_module_state(self): | |
567 | """Save the state of hooks in the sys module. |
|
571 | """Save the state of hooks in the sys module. | |
568 |
|
572 | |||
569 | This has to be called after self.user_ns is created. |
|
573 | This has to be called after self.user_ns is created. | |
570 | """ |
|
574 | """ | |
571 | self._orig_sys_module_state = {} |
|
575 | self._orig_sys_module_state = {} | |
572 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
576 | self._orig_sys_module_state['stdin'] = sys.stdin | |
573 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
577 | self._orig_sys_module_state['stdout'] = sys.stdout | |
574 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
578 | self._orig_sys_module_state['stderr'] = sys.stderr | |
575 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
579 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
576 | try: |
|
580 | try: | |
577 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
581 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
578 | except KeyError: |
|
582 | except KeyError: | |
579 | pass |
|
583 | pass | |
580 |
|
584 | |||
581 | def restore_sys_module_state(self): |
|
585 | def restore_sys_module_state(self): | |
582 | """Restore the state of the sys module.""" |
|
586 | """Restore the state of the sys module.""" | |
583 | try: |
|
587 | try: | |
584 | for k, v in self._orig_sys_module_state.iteritems(): |
|
588 | for k, v in self._orig_sys_module_state.iteritems(): | |
585 | setattr(sys, k, v) |
|
589 | setattr(sys, k, v) | |
586 | except AttributeError: |
|
590 | except AttributeError: | |
587 | pass |
|
591 | pass | |
588 | # Reset what what done in self.init_sys_modules |
|
592 | # Reset what what done in self.init_sys_modules | |
589 | try: |
|
593 | try: | |
590 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
594 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
591 | except (AttributeError, KeyError): |
|
595 | except (AttributeError, KeyError): | |
592 | pass |
|
596 | pass | |
593 |
|
597 | |||
594 | #------------------------------------------------------------------------- |
|
598 | #------------------------------------------------------------------------- | |
595 | # Things related to hooks |
|
599 | # Things related to hooks | |
596 | #------------------------------------------------------------------------- |
|
600 | #------------------------------------------------------------------------- | |
597 |
|
601 | |||
598 | def init_hooks(self): |
|
602 | def init_hooks(self): | |
599 | # hooks holds pointers used for user-side customizations |
|
603 | # hooks holds pointers used for user-side customizations | |
600 | self.hooks = Struct() |
|
604 | self.hooks = Struct() | |
601 |
|
605 | |||
602 | self.strdispatchers = {} |
|
606 | self.strdispatchers = {} | |
603 |
|
607 | |||
604 | # Set all default hooks, defined in the IPython.hooks module. |
|
608 | # Set all default hooks, defined in the IPython.hooks module. | |
605 | hooks = IPython.core.hooks |
|
609 | hooks = IPython.core.hooks | |
606 | for hook_name in hooks.__all__: |
|
610 | for hook_name in hooks.__all__: | |
607 | # default hooks have priority 100, i.e. low; user hooks should have |
|
611 | # default hooks have priority 100, i.e. low; user hooks should have | |
608 | # 0-100 priority |
|
612 | # 0-100 priority | |
609 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
613 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
610 |
|
614 | |||
611 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
615 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
612 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
616 | """set_hook(name,hook) -> sets an internal IPython hook. | |
613 |
|
617 | |||
614 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
618 | IPython exposes some of its internal API as user-modifiable hooks. By | |
615 | adding your function to one of these hooks, you can modify IPython's |
|
619 | adding your function to one of these hooks, you can modify IPython's | |
616 | behavior to call at runtime your own routines.""" |
|
620 | behavior to call at runtime your own routines.""" | |
617 |
|
621 | |||
618 | # At some point in the future, this should validate the hook before it |
|
622 | # At some point in the future, this should validate the hook before it | |
619 | # accepts it. Probably at least check that the hook takes the number |
|
623 | # accepts it. Probably at least check that the hook takes the number | |
620 | # of args it's supposed to. |
|
624 | # of args it's supposed to. | |
621 |
|
625 | |||
622 | f = types.MethodType(hook,self) |
|
626 | f = types.MethodType(hook,self) | |
623 |
|
627 | |||
624 | # check if the hook is for strdispatcher first |
|
628 | # check if the hook is for strdispatcher first | |
625 | if str_key is not None: |
|
629 | if str_key is not None: | |
626 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
630 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
627 | sdp.add_s(str_key, f, priority ) |
|
631 | sdp.add_s(str_key, f, priority ) | |
628 | self.strdispatchers[name] = sdp |
|
632 | self.strdispatchers[name] = sdp | |
629 | return |
|
633 | return | |
630 | if re_key is not None: |
|
634 | if re_key is not None: | |
631 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
635 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
632 | sdp.add_re(re.compile(re_key), f, priority ) |
|
636 | sdp.add_re(re.compile(re_key), f, priority ) | |
633 | self.strdispatchers[name] = sdp |
|
637 | self.strdispatchers[name] = sdp | |
634 | return |
|
638 | return | |
635 |
|
639 | |||
636 | dp = getattr(self.hooks, name, None) |
|
640 | dp = getattr(self.hooks, name, None) | |
637 | if name not in IPython.core.hooks.__all__: |
|
641 | if name not in IPython.core.hooks.__all__: | |
638 | print "Warning! Hook '%s' is not one of %s" % \ |
|
642 | print "Warning! Hook '%s' is not one of %s" % \ | |
639 | (name, IPython.core.hooks.__all__ ) |
|
643 | (name, IPython.core.hooks.__all__ ) | |
640 | if not dp: |
|
644 | if not dp: | |
641 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
645 | dp = IPython.core.hooks.CommandChainDispatcher() | |
642 |
|
646 | |||
643 | try: |
|
647 | try: | |
644 | dp.add(f,priority) |
|
648 | dp.add(f,priority) | |
645 | except AttributeError: |
|
649 | except AttributeError: | |
646 | # it was not commandchain, plain old func - replace |
|
650 | # it was not commandchain, plain old func - replace | |
647 | dp = f |
|
651 | dp = f | |
648 |
|
652 | |||
649 | setattr(self.hooks,name, dp) |
|
653 | setattr(self.hooks,name, dp) | |
650 |
|
654 | |||
651 | def register_post_execute(self, func): |
|
655 | def register_post_execute(self, func): | |
652 | """Register a function for calling after code execution. |
|
656 | """Register a function for calling after code execution. | |
653 | """ |
|
657 | """ | |
654 | if not callable(func): |
|
658 | if not callable(func): | |
655 | raise ValueError('argument %s must be callable' % func) |
|
659 | raise ValueError('argument %s must be callable' % func) | |
656 | self._post_execute.add(func) |
|
660 | self._post_execute.add(func) | |
657 |
|
661 | |||
658 | #------------------------------------------------------------------------- |
|
662 | #------------------------------------------------------------------------- | |
659 | # Things related to the "main" module |
|
663 | # Things related to the "main" module | |
660 | #------------------------------------------------------------------------- |
|
664 | #------------------------------------------------------------------------- | |
661 |
|
665 | |||
662 | def new_main_mod(self,ns=None): |
|
666 | def new_main_mod(self,ns=None): | |
663 | """Return a new 'main' module object for user code execution. |
|
667 | """Return a new 'main' module object for user code execution. | |
664 | """ |
|
668 | """ | |
665 | main_mod = self._user_main_module |
|
669 | main_mod = self._user_main_module | |
666 | init_fakemod_dict(main_mod,ns) |
|
670 | init_fakemod_dict(main_mod,ns) | |
667 | return main_mod |
|
671 | return main_mod | |
668 |
|
672 | |||
669 | def cache_main_mod(self,ns,fname): |
|
673 | def cache_main_mod(self,ns,fname): | |
670 | """Cache a main module's namespace. |
|
674 | """Cache a main module's namespace. | |
671 |
|
675 | |||
672 | When scripts are executed via %run, we must keep a reference to the |
|
676 | When scripts are executed via %run, we must keep a reference to the | |
673 | namespace of their __main__ module (a FakeModule instance) around so |
|
677 | namespace of their __main__ module (a FakeModule instance) around so | |
674 | that Python doesn't clear it, rendering objects defined therein |
|
678 | that Python doesn't clear it, rendering objects defined therein | |
675 | useless. |
|
679 | useless. | |
676 |
|
680 | |||
677 | This method keeps said reference in a private dict, keyed by the |
|
681 | This method keeps said reference in a private dict, keyed by the | |
678 | absolute path of the module object (which corresponds to the script |
|
682 | absolute path of the module object (which corresponds to the script | |
679 | path). This way, for multiple executions of the same script we only |
|
683 | path). This way, for multiple executions of the same script we only | |
680 | keep one copy of the namespace (the last one), thus preventing memory |
|
684 | keep one copy of the namespace (the last one), thus preventing memory | |
681 | leaks from old references while allowing the objects from the last |
|
685 | leaks from old references while allowing the objects from the last | |
682 | execution to be accessible. |
|
686 | execution to be accessible. | |
683 |
|
687 | |||
684 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
688 | Note: we can not allow the actual FakeModule instances to be deleted, | |
685 | because of how Python tears down modules (it hard-sets all their |
|
689 | because of how Python tears down modules (it hard-sets all their | |
686 | references to None without regard for reference counts). This method |
|
690 | references to None without regard for reference counts). This method | |
687 | must therefore make a *copy* of the given namespace, to allow the |
|
691 | must therefore make a *copy* of the given namespace, to allow the | |
688 | original module's __dict__ to be cleared and reused. |
|
692 | original module's __dict__ to be cleared and reused. | |
689 |
|
693 | |||
690 |
|
694 | |||
691 | Parameters |
|
695 | Parameters | |
692 | ---------- |
|
696 | ---------- | |
693 | ns : a namespace (a dict, typically) |
|
697 | ns : a namespace (a dict, typically) | |
694 |
|
698 | |||
695 | fname : str |
|
699 | fname : str | |
696 | Filename associated with the namespace. |
|
700 | Filename associated with the namespace. | |
697 |
|
701 | |||
698 | Examples |
|
702 | Examples | |
699 | -------- |
|
703 | -------- | |
700 |
|
704 | |||
701 | In [10]: import IPython |
|
705 | In [10]: import IPython | |
702 |
|
706 | |||
703 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
707 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
704 |
|
708 | |||
705 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
709 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
706 | Out[12]: True |
|
710 | Out[12]: True | |
707 | """ |
|
711 | """ | |
708 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
712 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
709 |
|
713 | |||
710 | def clear_main_mod_cache(self): |
|
714 | def clear_main_mod_cache(self): | |
711 | """Clear the cache of main modules. |
|
715 | """Clear the cache of main modules. | |
712 |
|
716 | |||
713 | Mainly for use by utilities like %reset. |
|
717 | Mainly for use by utilities like %reset. | |
714 |
|
718 | |||
715 | Examples |
|
719 | Examples | |
716 | -------- |
|
720 | -------- | |
717 |
|
721 | |||
718 | In [15]: import IPython |
|
722 | In [15]: import IPython | |
719 |
|
723 | |||
720 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
724 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
721 |
|
725 | |||
722 | In [17]: len(_ip._main_ns_cache) > 0 |
|
726 | In [17]: len(_ip._main_ns_cache) > 0 | |
723 | Out[17]: True |
|
727 | Out[17]: True | |
724 |
|
728 | |||
725 | In [18]: _ip.clear_main_mod_cache() |
|
729 | In [18]: _ip.clear_main_mod_cache() | |
726 |
|
730 | |||
727 | In [19]: len(_ip._main_ns_cache) == 0 |
|
731 | In [19]: len(_ip._main_ns_cache) == 0 | |
728 | Out[19]: True |
|
732 | Out[19]: True | |
729 | """ |
|
733 | """ | |
730 | self._main_ns_cache.clear() |
|
734 | self._main_ns_cache.clear() | |
731 |
|
735 | |||
732 | #------------------------------------------------------------------------- |
|
736 | #------------------------------------------------------------------------- | |
733 | # Things related to debugging |
|
737 | # Things related to debugging | |
734 | #------------------------------------------------------------------------- |
|
738 | #------------------------------------------------------------------------- | |
735 |
|
739 | |||
736 | def init_pdb(self): |
|
740 | def init_pdb(self): | |
737 | # Set calling of pdb on exceptions |
|
741 | # Set calling of pdb on exceptions | |
738 | # self.call_pdb is a property |
|
742 | # self.call_pdb is a property | |
739 | self.call_pdb = self.pdb |
|
743 | self.call_pdb = self.pdb | |
740 |
|
744 | |||
741 | def _get_call_pdb(self): |
|
745 | def _get_call_pdb(self): | |
742 | return self._call_pdb |
|
746 | return self._call_pdb | |
743 |
|
747 | |||
744 | def _set_call_pdb(self,val): |
|
748 | def _set_call_pdb(self,val): | |
745 |
|
749 | |||
746 | if val not in (0,1,False,True): |
|
750 | if val not in (0,1,False,True): | |
747 | raise ValueError,'new call_pdb value must be boolean' |
|
751 | raise ValueError,'new call_pdb value must be boolean' | |
748 |
|
752 | |||
749 | # store value in instance |
|
753 | # store value in instance | |
750 | self._call_pdb = val |
|
754 | self._call_pdb = val | |
751 |
|
755 | |||
752 | # notify the actual exception handlers |
|
756 | # notify the actual exception handlers | |
753 | self.InteractiveTB.call_pdb = val |
|
757 | self.InteractiveTB.call_pdb = val | |
754 |
|
758 | |||
755 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
759 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
756 | 'Control auto-activation of pdb at exceptions') |
|
760 | 'Control auto-activation of pdb at exceptions') | |
757 |
|
761 | |||
758 | def debugger(self,force=False): |
|
762 | def debugger(self,force=False): | |
759 | """Call the pydb/pdb debugger. |
|
763 | """Call the pydb/pdb debugger. | |
760 |
|
764 | |||
761 | Keywords: |
|
765 | Keywords: | |
762 |
|
766 | |||
763 | - force(False): by default, this routine checks the instance call_pdb |
|
767 | - force(False): by default, this routine checks the instance call_pdb | |
764 | flag and does not actually invoke the debugger if the flag is false. |
|
768 | flag and does not actually invoke the debugger if the flag is false. | |
765 | The 'force' option forces the debugger to activate even if the flag |
|
769 | The 'force' option forces the debugger to activate even if the flag | |
766 | is false. |
|
770 | is false. | |
767 | """ |
|
771 | """ | |
768 |
|
772 | |||
769 | if not (force or self.call_pdb): |
|
773 | if not (force or self.call_pdb): | |
770 | return |
|
774 | return | |
771 |
|
775 | |||
772 | if not hasattr(sys,'last_traceback'): |
|
776 | if not hasattr(sys,'last_traceback'): | |
773 | error('No traceback has been produced, nothing to debug.') |
|
777 | error('No traceback has been produced, nothing to debug.') | |
774 | return |
|
778 | return | |
775 |
|
779 | |||
776 | # use pydb if available |
|
780 | # use pydb if available | |
777 | if debugger.has_pydb: |
|
781 | if debugger.has_pydb: | |
778 | from pydb import pm |
|
782 | from pydb import pm | |
779 | else: |
|
783 | else: | |
780 | # fallback to our internal debugger |
|
784 | # fallback to our internal debugger | |
781 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
785 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
782 |
|
786 | |||
783 | with self.readline_no_record: |
|
787 | with self.readline_no_record: | |
784 | pm() |
|
788 | pm() | |
785 |
|
789 | |||
786 | #------------------------------------------------------------------------- |
|
790 | #------------------------------------------------------------------------- | |
787 | # Things related to IPython's various namespaces |
|
791 | # Things related to IPython's various namespaces | |
788 | #------------------------------------------------------------------------- |
|
792 | #------------------------------------------------------------------------- | |
789 |
|
793 | |||
790 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
794 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
791 | # Create the namespace where the user will operate. user_ns is |
|
795 | # Create the namespace where the user will operate. user_ns is | |
792 | # normally the only one used, and it is passed to the exec calls as |
|
796 | # normally the only one used, and it is passed to the exec calls as | |
793 | # the locals argument. But we do carry a user_global_ns namespace |
|
797 | # the locals argument. But we do carry a user_global_ns namespace | |
794 | # given as the exec 'globals' argument, This is useful in embedding |
|
798 | # given as the exec 'globals' argument, This is useful in embedding | |
795 | # situations where the ipython shell opens in a context where the |
|
799 | # situations where the ipython shell opens in a context where the | |
796 | # distinction between locals and globals is meaningful. For |
|
800 | # distinction between locals and globals is meaningful. For | |
797 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
801 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
798 |
|
802 | |||
799 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
803 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
800 | # level as a dict instead of a module. This is a manual fix, but I |
|
804 | # level as a dict instead of a module. This is a manual fix, but I | |
801 | # should really track down where the problem is coming from. Alex |
|
805 | # should really track down where the problem is coming from. Alex | |
802 | # Schmolck reported this problem first. |
|
806 | # Schmolck reported this problem first. | |
803 |
|
807 | |||
804 | # A useful post by Alex Martelli on this topic: |
|
808 | # A useful post by Alex Martelli on this topic: | |
805 | # Re: inconsistent value from __builtins__ |
|
809 | # Re: inconsistent value from __builtins__ | |
806 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
810 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
807 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
811 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
808 | # Gruppen: comp.lang.python |
|
812 | # Gruppen: comp.lang.python | |
809 |
|
813 | |||
810 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
814 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
811 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
815 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
812 | # > <type 'dict'> |
|
816 | # > <type 'dict'> | |
813 | # > >>> print type(__builtins__) |
|
817 | # > >>> print type(__builtins__) | |
814 | # > <type 'module'> |
|
818 | # > <type 'module'> | |
815 | # > Is this difference in return value intentional? |
|
819 | # > Is this difference in return value intentional? | |
816 |
|
820 | |||
817 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
821 | # Well, it's documented that '__builtins__' can be either a dictionary | |
818 | # or a module, and it's been that way for a long time. Whether it's |
|
822 | # or a module, and it's been that way for a long time. Whether it's | |
819 | # intentional (or sensible), I don't know. In any case, the idea is |
|
823 | # intentional (or sensible), I don't know. In any case, the idea is | |
820 | # that if you need to access the built-in namespace directly, you |
|
824 | # that if you need to access the built-in namespace directly, you | |
821 | # should start with "import __builtin__" (note, no 's') which will |
|
825 | # should start with "import __builtin__" (note, no 's') which will | |
822 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
826 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
823 |
|
827 | |||
824 | # These routines return properly built dicts as needed by the rest of |
|
828 | # These routines return properly built dicts as needed by the rest of | |
825 | # the code, and can also be used by extension writers to generate |
|
829 | # the code, and can also be used by extension writers to generate | |
826 | # properly initialized namespaces. |
|
830 | # properly initialized namespaces. | |
827 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
831 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
828 | user_global_ns) |
|
832 | user_global_ns) | |
829 |
|
833 | |||
830 | # Assign namespaces |
|
834 | # Assign namespaces | |
831 | # This is the namespace where all normal user variables live |
|
835 | # This is the namespace where all normal user variables live | |
832 | self.user_ns = user_ns |
|
836 | self.user_ns = user_ns | |
833 | self.user_global_ns = user_global_ns |
|
837 | self.user_global_ns = user_global_ns | |
834 |
|
838 | |||
835 | # An auxiliary namespace that checks what parts of the user_ns were |
|
839 | # An auxiliary namespace that checks what parts of the user_ns were | |
836 | # loaded at startup, so we can list later only variables defined in |
|
840 | # loaded at startup, so we can list later only variables defined in | |
837 | # actual interactive use. Since it is always a subset of user_ns, it |
|
841 | # actual interactive use. Since it is always a subset of user_ns, it | |
838 | # doesn't need to be separately tracked in the ns_table. |
|
842 | # doesn't need to be separately tracked in the ns_table. | |
839 | self.user_ns_hidden = {} |
|
843 | self.user_ns_hidden = {} | |
840 |
|
844 | |||
841 | # A namespace to keep track of internal data structures to prevent |
|
845 | # A namespace to keep track of internal data structures to prevent | |
842 | # them from cluttering user-visible stuff. Will be updated later |
|
846 | # them from cluttering user-visible stuff. Will be updated later | |
843 | self.internal_ns = {} |
|
847 | self.internal_ns = {} | |
844 |
|
848 | |||
845 | # Now that FakeModule produces a real module, we've run into a nasty |
|
849 | # Now that FakeModule produces a real module, we've run into a nasty | |
846 | # problem: after script execution (via %run), the module where the user |
|
850 | # problem: after script execution (via %run), the module where the user | |
847 | # code ran is deleted. Now that this object is a true module (needed |
|
851 | # code ran is deleted. Now that this object is a true module (needed | |
848 | # so docetst and other tools work correctly), the Python module |
|
852 | # so docetst and other tools work correctly), the Python module | |
849 | # teardown mechanism runs over it, and sets to None every variable |
|
853 | # teardown mechanism runs over it, and sets to None every variable | |
850 | # present in that module. Top-level references to objects from the |
|
854 | # present in that module. Top-level references to objects from the | |
851 | # script survive, because the user_ns is updated with them. However, |
|
855 | # script survive, because the user_ns is updated with them. However, | |
852 | # calling functions defined in the script that use other things from |
|
856 | # calling functions defined in the script that use other things from | |
853 | # the script will fail, because the function's closure had references |
|
857 | # the script will fail, because the function's closure had references | |
854 | # to the original objects, which are now all None. So we must protect |
|
858 | # to the original objects, which are now all None. So we must protect | |
855 | # these modules from deletion by keeping a cache. |
|
859 | # these modules from deletion by keeping a cache. | |
856 | # |
|
860 | # | |
857 | # To avoid keeping stale modules around (we only need the one from the |
|
861 | # To avoid keeping stale modules around (we only need the one from the | |
858 | # last run), we use a dict keyed with the full path to the script, so |
|
862 | # last run), we use a dict keyed with the full path to the script, so | |
859 | # only the last version of the module is held in the cache. Note, |
|
863 | # only the last version of the module is held in the cache. Note, | |
860 | # however, that we must cache the module *namespace contents* (their |
|
864 | # however, that we must cache the module *namespace contents* (their | |
861 | # __dict__). Because if we try to cache the actual modules, old ones |
|
865 | # __dict__). Because if we try to cache the actual modules, old ones | |
862 | # (uncached) could be destroyed while still holding references (such as |
|
866 | # (uncached) could be destroyed while still holding references (such as | |
863 | # those held by GUI objects that tend to be long-lived)> |
|
867 | # those held by GUI objects that tend to be long-lived)> | |
864 | # |
|
868 | # | |
865 | # The %reset command will flush this cache. See the cache_main_mod() |
|
869 | # The %reset command will flush this cache. See the cache_main_mod() | |
866 | # and clear_main_mod_cache() methods for details on use. |
|
870 | # and clear_main_mod_cache() methods for details on use. | |
867 |
|
871 | |||
868 | # This is the cache used for 'main' namespaces |
|
872 | # This is the cache used for 'main' namespaces | |
869 | self._main_ns_cache = {} |
|
873 | self._main_ns_cache = {} | |
870 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
874 | # And this is the single instance of FakeModule whose __dict__ we keep | |
871 | # copying and clearing for reuse on each %run |
|
875 | # copying and clearing for reuse on each %run | |
872 | self._user_main_module = FakeModule() |
|
876 | self._user_main_module = FakeModule() | |
873 |
|
877 | |||
874 | # A table holding all the namespaces IPython deals with, so that |
|
878 | # A table holding all the namespaces IPython deals with, so that | |
875 | # introspection facilities can search easily. |
|
879 | # introspection facilities can search easily. | |
876 | self.ns_table = {'user':user_ns, |
|
880 | self.ns_table = {'user':user_ns, | |
877 | 'user_global':user_global_ns, |
|
881 | 'user_global':user_global_ns, | |
878 | 'internal':self.internal_ns, |
|
882 | 'internal':self.internal_ns, | |
879 | 'builtin':__builtin__.__dict__ |
|
883 | 'builtin':__builtin__.__dict__ | |
880 | } |
|
884 | } | |
881 |
|
885 | |||
882 | # Similarly, track all namespaces where references can be held and that |
|
886 | # Similarly, track all namespaces where references can be held and that | |
883 | # we can safely clear (so it can NOT include builtin). This one can be |
|
887 | # we can safely clear (so it can NOT include builtin). This one can be | |
884 | # a simple list. Note that the main execution namespaces, user_ns and |
|
888 | # a simple list. Note that the main execution namespaces, user_ns and | |
885 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
889 | # user_global_ns, can NOT be listed here, as clearing them blindly | |
886 | # causes errors in object __del__ methods. Instead, the reset() method |
|
890 | # causes errors in object __del__ methods. Instead, the reset() method | |
887 | # clears them manually and carefully. |
|
891 | # clears them manually and carefully. | |
888 | self.ns_refs_table = [ self.user_ns_hidden, |
|
892 | self.ns_refs_table = [ self.user_ns_hidden, | |
889 | self.internal_ns, self._main_ns_cache ] |
|
893 | self.internal_ns, self._main_ns_cache ] | |
890 |
|
894 | |||
891 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
895 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
892 | """Return a valid local and global user interactive namespaces. |
|
896 | """Return a valid local and global user interactive namespaces. | |
893 |
|
897 | |||
894 | This builds a dict with the minimal information needed to operate as a |
|
898 | This builds a dict with the minimal information needed to operate as a | |
895 | valid IPython user namespace, which you can pass to the various |
|
899 | valid IPython user namespace, which you can pass to the various | |
896 | embedding classes in ipython. The default implementation returns the |
|
900 | embedding classes in ipython. The default implementation returns the | |
897 | same dict for both the locals and the globals to allow functions to |
|
901 | same dict for both the locals and the globals to allow functions to | |
898 | refer to variables in the namespace. Customized implementations can |
|
902 | refer to variables in the namespace. Customized implementations can | |
899 | return different dicts. The locals dictionary can actually be anything |
|
903 | return different dicts. The locals dictionary can actually be anything | |
900 | following the basic mapping protocol of a dict, but the globals dict |
|
904 | following the basic mapping protocol of a dict, but the globals dict | |
901 | must be a true dict, not even a subclass. It is recommended that any |
|
905 | must be a true dict, not even a subclass. It is recommended that any | |
902 | custom object for the locals namespace synchronize with the globals |
|
906 | custom object for the locals namespace synchronize with the globals | |
903 | dict somehow. |
|
907 | dict somehow. | |
904 |
|
908 | |||
905 | Raises TypeError if the provided globals namespace is not a true dict. |
|
909 | Raises TypeError if the provided globals namespace is not a true dict. | |
906 |
|
910 | |||
907 | Parameters |
|
911 | Parameters | |
908 | ---------- |
|
912 | ---------- | |
909 | user_ns : dict-like, optional |
|
913 | user_ns : dict-like, optional | |
910 | The current user namespace. The items in this namespace should |
|
914 | The current user namespace. The items in this namespace should | |
911 | be included in the output. If None, an appropriate blank |
|
915 | be included in the output. If None, an appropriate blank | |
912 | namespace should be created. |
|
916 | namespace should be created. | |
913 | user_global_ns : dict, optional |
|
917 | user_global_ns : dict, optional | |
914 | The current user global namespace. The items in this namespace |
|
918 | The current user global namespace. The items in this namespace | |
915 | should be included in the output. If None, an appropriate |
|
919 | should be included in the output. If None, an appropriate | |
916 | blank namespace should be created. |
|
920 | blank namespace should be created. | |
917 |
|
921 | |||
918 | Returns |
|
922 | Returns | |
919 | ------- |
|
923 | ------- | |
920 | A pair of dictionary-like object to be used as the local namespace |
|
924 | A pair of dictionary-like object to be used as the local namespace | |
921 | of the interpreter and a dict to be used as the global namespace. |
|
925 | of the interpreter and a dict to be used as the global namespace. | |
922 | """ |
|
926 | """ | |
923 |
|
927 | |||
924 |
|
928 | |||
925 | # We must ensure that __builtin__ (without the final 's') is always |
|
929 | # We must ensure that __builtin__ (without the final 's') is always | |
926 | # available and pointing to the __builtin__ *module*. For more details: |
|
930 | # available and pointing to the __builtin__ *module*. For more details: | |
927 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
931 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
928 |
|
932 | |||
929 | if user_ns is None: |
|
933 | if user_ns is None: | |
930 | # Set __name__ to __main__ to better match the behavior of the |
|
934 | # Set __name__ to __main__ to better match the behavior of the | |
931 | # normal interpreter. |
|
935 | # normal interpreter. | |
932 | user_ns = {'__name__' :'__main__', |
|
936 | user_ns = {'__name__' :'__main__', | |
933 | '__builtin__' : __builtin__, |
|
937 | '__builtin__' : __builtin__, | |
934 | '__builtins__' : __builtin__, |
|
938 | '__builtins__' : __builtin__, | |
935 | } |
|
939 | } | |
936 | else: |
|
940 | else: | |
937 | user_ns.setdefault('__name__','__main__') |
|
941 | user_ns.setdefault('__name__','__main__') | |
938 | user_ns.setdefault('__builtin__',__builtin__) |
|
942 | user_ns.setdefault('__builtin__',__builtin__) | |
939 | user_ns.setdefault('__builtins__',__builtin__) |
|
943 | user_ns.setdefault('__builtins__',__builtin__) | |
940 |
|
944 | |||
941 | if user_global_ns is None: |
|
945 | if user_global_ns is None: | |
942 | user_global_ns = user_ns |
|
946 | user_global_ns = user_ns | |
943 | if type(user_global_ns) is not dict: |
|
947 | if type(user_global_ns) is not dict: | |
944 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
948 | raise TypeError("user_global_ns must be a true dict; got %r" | |
945 | % type(user_global_ns)) |
|
949 | % type(user_global_ns)) | |
946 |
|
950 | |||
947 | return user_ns, user_global_ns |
|
951 | return user_ns, user_global_ns | |
948 |
|
952 | |||
949 | def init_sys_modules(self): |
|
953 | def init_sys_modules(self): | |
950 | # We need to insert into sys.modules something that looks like a |
|
954 | # We need to insert into sys.modules something that looks like a | |
951 | # module but which accesses the IPython namespace, for shelve and |
|
955 | # module but which accesses the IPython namespace, for shelve and | |
952 | # pickle to work interactively. Normally they rely on getting |
|
956 | # pickle to work interactively. Normally they rely on getting | |
953 | # everything out of __main__, but for embedding purposes each IPython |
|
957 | # everything out of __main__, but for embedding purposes each IPython | |
954 | # instance has its own private namespace, so we can't go shoving |
|
958 | # instance has its own private namespace, so we can't go shoving | |
955 | # everything into __main__. |
|
959 | # everything into __main__. | |
956 |
|
960 | |||
957 | # note, however, that we should only do this for non-embedded |
|
961 | # note, however, that we should only do this for non-embedded | |
958 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
962 | # ipythons, which really mimic the __main__.__dict__ with their own | |
959 | # namespace. Embedded instances, on the other hand, should not do |
|
963 | # namespace. Embedded instances, on the other hand, should not do | |
960 | # this because they need to manage the user local/global namespaces |
|
964 | # this because they need to manage the user local/global namespaces | |
961 | # only, but they live within a 'normal' __main__ (meaning, they |
|
965 | # only, but they live within a 'normal' __main__ (meaning, they | |
962 | # shouldn't overtake the execution environment of the script they're |
|
966 | # shouldn't overtake the execution environment of the script they're | |
963 | # embedded in). |
|
967 | # embedded in). | |
964 |
|
968 | |||
965 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
969 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
966 |
|
970 | |||
967 | try: |
|
971 | try: | |
968 | main_name = self.user_ns['__name__'] |
|
972 | main_name = self.user_ns['__name__'] | |
969 | except KeyError: |
|
973 | except KeyError: | |
970 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
974 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
971 | else: |
|
975 | else: | |
972 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
976 | sys.modules[main_name] = FakeModule(self.user_ns) | |
973 |
|
977 | |||
974 | def init_user_ns(self): |
|
978 | def init_user_ns(self): | |
975 | """Initialize all user-visible namespaces to their minimum defaults. |
|
979 | """Initialize all user-visible namespaces to their minimum defaults. | |
976 |
|
980 | |||
977 | Certain history lists are also initialized here, as they effectively |
|
981 | Certain history lists are also initialized here, as they effectively | |
978 | act as user namespaces. |
|
982 | act as user namespaces. | |
979 |
|
983 | |||
980 | Notes |
|
984 | Notes | |
981 | ----- |
|
985 | ----- | |
982 | All data structures here are only filled in, they are NOT reset by this |
|
986 | All data structures here are only filled in, they are NOT reset by this | |
983 | method. If they were not empty before, data will simply be added to |
|
987 | method. If they were not empty before, data will simply be added to | |
984 | therm. |
|
988 | therm. | |
985 | """ |
|
989 | """ | |
986 | # This function works in two parts: first we put a few things in |
|
990 | # This function works in two parts: first we put a few things in | |
987 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
991 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
988 | # initial variables aren't shown by %who. After the sync, we add the |
|
992 | # initial variables aren't shown by %who. After the sync, we add the | |
989 | # rest of what we *do* want the user to see with %who even on a new |
|
993 | # rest of what we *do* want the user to see with %who even on a new | |
990 | # session (probably nothing, so theye really only see their own stuff) |
|
994 | # session (probably nothing, so theye really only see their own stuff) | |
991 |
|
995 | |||
992 | # The user dict must *always* have a __builtin__ reference to the |
|
996 | # The user dict must *always* have a __builtin__ reference to the | |
993 | # Python standard __builtin__ namespace, which must be imported. |
|
997 | # Python standard __builtin__ namespace, which must be imported. | |
994 | # This is so that certain operations in prompt evaluation can be |
|
998 | # This is so that certain operations in prompt evaluation can be | |
995 | # reliably executed with builtins. Note that we can NOT use |
|
999 | # reliably executed with builtins. Note that we can NOT use | |
996 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1000 | # __builtins__ (note the 's'), because that can either be a dict or a | |
997 | # module, and can even mutate at runtime, depending on the context |
|
1001 | # module, and can even mutate at runtime, depending on the context | |
998 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1002 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
999 | # always a module object, though it must be explicitly imported. |
|
1003 | # always a module object, though it must be explicitly imported. | |
1000 |
|
1004 | |||
1001 | # For more details: |
|
1005 | # For more details: | |
1002 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1006 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1003 | ns = dict(__builtin__ = __builtin__) |
|
1007 | ns = dict(__builtin__ = __builtin__) | |
1004 |
|
1008 | |||
1005 | # Put 'help' in the user namespace |
|
1009 | # Put 'help' in the user namespace | |
1006 | try: |
|
1010 | try: | |
1007 | from site import _Helper |
|
1011 | from site import _Helper | |
1008 | ns['help'] = _Helper() |
|
1012 | ns['help'] = _Helper() | |
1009 | except ImportError: |
|
1013 | except ImportError: | |
1010 | warn('help() not available - check site.py') |
|
1014 | warn('help() not available - check site.py') | |
1011 |
|
1015 | |||
1012 | # make global variables for user access to the histories |
|
1016 | # make global variables for user access to the histories | |
1013 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1017 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1014 | ns['_oh'] = self.history_manager.output_hist |
|
1018 | ns['_oh'] = self.history_manager.output_hist | |
1015 | ns['_dh'] = self.history_manager.dir_hist |
|
1019 | ns['_dh'] = self.history_manager.dir_hist | |
1016 |
|
1020 | |||
1017 | ns['_sh'] = shadowns |
|
1021 | ns['_sh'] = shadowns | |
1018 |
|
1022 | |||
1019 | # user aliases to input and output histories. These shouldn't show up |
|
1023 | # user aliases to input and output histories. These shouldn't show up | |
1020 | # in %who, as they can have very large reprs. |
|
1024 | # in %who, as they can have very large reprs. | |
1021 | ns['In'] = self.history_manager.input_hist_parsed |
|
1025 | ns['In'] = self.history_manager.input_hist_parsed | |
1022 | ns['Out'] = self.history_manager.output_hist |
|
1026 | ns['Out'] = self.history_manager.output_hist | |
1023 |
|
1027 | |||
1024 | # Store myself as the public api!!! |
|
1028 | # Store myself as the public api!!! | |
1025 | ns['get_ipython'] = self.get_ipython |
|
1029 | ns['get_ipython'] = self.get_ipython | |
|
1030 | ||||
|
1031 | ns['exit'] = self.exiter | |||
|
1032 | ns['quit'] = self.exiter | |||
1026 |
|
1033 | |||
1027 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1034 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1028 | # by %who |
|
1035 | # by %who | |
1029 | self.user_ns_hidden.update(ns) |
|
1036 | self.user_ns_hidden.update(ns) | |
1030 |
|
1037 | |||
1031 | # Anything put into ns now would show up in %who. Think twice before |
|
1038 | # Anything put into ns now would show up in %who. Think twice before | |
1032 | # putting anything here, as we really want %who to show the user their |
|
1039 | # putting anything here, as we really want %who to show the user their | |
1033 | # stuff, not our variables. |
|
1040 | # stuff, not our variables. | |
1034 |
|
1041 | |||
1035 | # Finally, update the real user's namespace |
|
1042 | # Finally, update the real user's namespace | |
1036 | self.user_ns.update(ns) |
|
1043 | self.user_ns.update(ns) | |
1037 |
|
1044 | |||
1038 | def reset(self, new_session=True): |
|
1045 | def reset(self, new_session=True): | |
1039 | """Clear all internal namespaces. |
|
1046 | """Clear all internal namespaces. | |
1040 |
|
1047 | |||
1041 | Note that this is much more aggressive than %reset, since it clears |
|
1048 | Note that this is much more aggressive than %reset, since it clears | |
1042 | fully all namespaces, as well as all input/output lists. |
|
1049 | fully all namespaces, as well as all input/output lists. | |
1043 |
|
1050 | |||
1044 | If new_session is True, a new history session will be opened. |
|
1051 | If new_session is True, a new history session will be opened. | |
1045 | """ |
|
1052 | """ | |
1046 | # Clear histories |
|
1053 | # Clear histories | |
1047 | self.history_manager.reset(new_session) |
|
1054 | self.history_manager.reset(new_session) | |
1048 | # Reset counter used to index all histories |
|
1055 | # Reset counter used to index all histories | |
1049 | if new_session: |
|
1056 | if new_session: | |
1050 | self.execution_count = 1 |
|
1057 | self.execution_count = 1 | |
1051 |
|
1058 | |||
1052 | # Flush cached output items |
|
1059 | # Flush cached output items | |
1053 | self.displayhook.flush() |
|
1060 | self.displayhook.flush() | |
1054 |
|
1061 | |||
1055 | # Restore the user namespaces to minimal usability |
|
1062 | # Restore the user namespaces to minimal usability | |
1056 | for ns in self.ns_refs_table: |
|
1063 | for ns in self.ns_refs_table: | |
1057 | ns.clear() |
|
1064 | ns.clear() | |
1058 |
|
1065 | |||
1059 | # The main execution namespaces must be cleared very carefully, |
|
1066 | # The main execution namespaces must be cleared very carefully, | |
1060 | # skipping the deletion of the builtin-related keys, because doing so |
|
1067 | # skipping the deletion of the builtin-related keys, because doing so | |
1061 | # would cause errors in many object's __del__ methods. |
|
1068 | # would cause errors in many object's __del__ methods. | |
1062 | for ns in [self.user_ns, self.user_global_ns]: |
|
1069 | for ns in [self.user_ns, self.user_global_ns]: | |
1063 | drop_keys = set(ns.keys()) |
|
1070 | drop_keys = set(ns.keys()) | |
1064 | drop_keys.discard('__builtin__') |
|
1071 | drop_keys.discard('__builtin__') | |
1065 | drop_keys.discard('__builtins__') |
|
1072 | drop_keys.discard('__builtins__') | |
1066 | for k in drop_keys: |
|
1073 | for k in drop_keys: | |
1067 | del ns[k] |
|
1074 | del ns[k] | |
1068 |
|
1075 | |||
1069 | # Restore the user namespaces to minimal usability |
|
1076 | # Restore the user namespaces to minimal usability | |
1070 | self.init_user_ns() |
|
1077 | self.init_user_ns() | |
1071 |
|
1078 | |||
1072 | # Restore the default and user aliases |
|
1079 | # Restore the default and user aliases | |
1073 | self.alias_manager.clear_aliases() |
|
1080 | self.alias_manager.clear_aliases() | |
1074 | self.alias_manager.init_aliases() |
|
1081 | self.alias_manager.init_aliases() | |
1075 |
|
1082 | |||
1076 | # Flush the private list of module references kept for script |
|
1083 | # Flush the private list of module references kept for script | |
1077 | # execution protection |
|
1084 | # execution protection | |
1078 | self.clear_main_mod_cache() |
|
1085 | self.clear_main_mod_cache() | |
1079 |
|
1086 | |||
1080 | def reset_selective(self, regex=None): |
|
1087 | def reset_selective(self, regex=None): | |
1081 | """Clear selective variables from internal namespaces based on a |
|
1088 | """Clear selective variables from internal namespaces based on a | |
1082 | specified regular expression. |
|
1089 | specified regular expression. | |
1083 |
|
1090 | |||
1084 | Parameters |
|
1091 | Parameters | |
1085 | ---------- |
|
1092 | ---------- | |
1086 | regex : string or compiled pattern, optional |
|
1093 | regex : string or compiled pattern, optional | |
1087 | A regular expression pattern that will be used in searching |
|
1094 | A regular expression pattern that will be used in searching | |
1088 | variable names in the users namespaces. |
|
1095 | variable names in the users namespaces. | |
1089 | """ |
|
1096 | """ | |
1090 | if regex is not None: |
|
1097 | if regex is not None: | |
1091 | try: |
|
1098 | try: | |
1092 | m = re.compile(regex) |
|
1099 | m = re.compile(regex) | |
1093 | except TypeError: |
|
1100 | except TypeError: | |
1094 | raise TypeError('regex must be a string or compiled pattern') |
|
1101 | raise TypeError('regex must be a string or compiled pattern') | |
1095 | # Search for keys in each namespace that match the given regex |
|
1102 | # Search for keys in each namespace that match the given regex | |
1096 | # If a match is found, delete the key/value pair. |
|
1103 | # If a match is found, delete the key/value pair. | |
1097 | for ns in self.ns_refs_table: |
|
1104 | for ns in self.ns_refs_table: | |
1098 | for var in ns: |
|
1105 | for var in ns: | |
1099 | if m.search(var): |
|
1106 | if m.search(var): | |
1100 | del ns[var] |
|
1107 | del ns[var] | |
1101 |
|
1108 | |||
1102 | def push(self, variables, interactive=True): |
|
1109 | def push(self, variables, interactive=True): | |
1103 | """Inject a group of variables into the IPython user namespace. |
|
1110 | """Inject a group of variables into the IPython user namespace. | |
1104 |
|
1111 | |||
1105 | Parameters |
|
1112 | Parameters | |
1106 | ---------- |
|
1113 | ---------- | |
1107 | variables : dict, str or list/tuple of str |
|
1114 | variables : dict, str or list/tuple of str | |
1108 | The variables to inject into the user's namespace. If a dict, a |
|
1115 | The variables to inject into the user's namespace. If a dict, a | |
1109 | simple update is done. If a str, the string is assumed to have |
|
1116 | simple update is done. If a str, the string is assumed to have | |
1110 | variable names separated by spaces. A list/tuple of str can also |
|
1117 | variable names separated by spaces. A list/tuple of str can also | |
1111 | be used to give the variable names. If just the variable names are |
|
1118 | be used to give the variable names. If just the variable names are | |
1112 | give (list/tuple/str) then the variable values looked up in the |
|
1119 | give (list/tuple/str) then the variable values looked up in the | |
1113 | callers frame. |
|
1120 | callers frame. | |
1114 | interactive : bool |
|
1121 | interactive : bool | |
1115 | If True (default), the variables will be listed with the ``who`` |
|
1122 | If True (default), the variables will be listed with the ``who`` | |
1116 | magic. |
|
1123 | magic. | |
1117 | """ |
|
1124 | """ | |
1118 | vdict = None |
|
1125 | vdict = None | |
1119 |
|
1126 | |||
1120 | # We need a dict of name/value pairs to do namespace updates. |
|
1127 | # We need a dict of name/value pairs to do namespace updates. | |
1121 | if isinstance(variables, dict): |
|
1128 | if isinstance(variables, dict): | |
1122 | vdict = variables |
|
1129 | vdict = variables | |
1123 | elif isinstance(variables, (basestring, list, tuple)): |
|
1130 | elif isinstance(variables, (basestring, list, tuple)): | |
1124 | if isinstance(variables, basestring): |
|
1131 | if isinstance(variables, basestring): | |
1125 | vlist = variables.split() |
|
1132 | vlist = variables.split() | |
1126 | else: |
|
1133 | else: | |
1127 | vlist = variables |
|
1134 | vlist = variables | |
1128 | vdict = {} |
|
1135 | vdict = {} | |
1129 | cf = sys._getframe(1) |
|
1136 | cf = sys._getframe(1) | |
1130 | for name in vlist: |
|
1137 | for name in vlist: | |
1131 | try: |
|
1138 | try: | |
1132 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1139 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1133 | except: |
|
1140 | except: | |
1134 | print ('Could not get variable %s from %s' % |
|
1141 | print ('Could not get variable %s from %s' % | |
1135 | (name,cf.f_code.co_name)) |
|
1142 | (name,cf.f_code.co_name)) | |
1136 | else: |
|
1143 | else: | |
1137 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1144 | raise ValueError('variables must be a dict/str/list/tuple') | |
1138 |
|
1145 | |||
1139 | # Propagate variables to user namespace |
|
1146 | # Propagate variables to user namespace | |
1140 | self.user_ns.update(vdict) |
|
1147 | self.user_ns.update(vdict) | |
1141 |
|
1148 | |||
1142 | # And configure interactive visibility |
|
1149 | # And configure interactive visibility | |
1143 | config_ns = self.user_ns_hidden |
|
1150 | config_ns = self.user_ns_hidden | |
1144 | if interactive: |
|
1151 | if interactive: | |
1145 | for name, val in vdict.iteritems(): |
|
1152 | for name, val in vdict.iteritems(): | |
1146 | config_ns.pop(name, None) |
|
1153 | config_ns.pop(name, None) | |
1147 | else: |
|
1154 | else: | |
1148 | for name,val in vdict.iteritems(): |
|
1155 | for name,val in vdict.iteritems(): | |
1149 | config_ns[name] = val |
|
1156 | config_ns[name] = val | |
1150 |
|
1157 | |||
1151 | #------------------------------------------------------------------------- |
|
1158 | #------------------------------------------------------------------------- | |
1152 | # Things related to object introspection |
|
1159 | # Things related to object introspection | |
1153 | #------------------------------------------------------------------------- |
|
1160 | #------------------------------------------------------------------------- | |
1154 |
|
1161 | |||
1155 | def _ofind(self, oname, namespaces=None): |
|
1162 | def _ofind(self, oname, namespaces=None): | |
1156 | """Find an object in the available namespaces. |
|
1163 | """Find an object in the available namespaces. | |
1157 |
|
1164 | |||
1158 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1165 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1159 |
|
1166 | |||
1160 | Has special code to detect magic functions. |
|
1167 | Has special code to detect magic functions. | |
1161 | """ |
|
1168 | """ | |
1162 | #oname = oname.strip() |
|
1169 | #oname = oname.strip() | |
1163 | #print '1- oname: <%r>' % oname # dbg |
|
1170 | #print '1- oname: <%r>' % oname # dbg | |
1164 | try: |
|
1171 | try: | |
1165 | oname = oname.strip().encode('ascii') |
|
1172 | oname = oname.strip().encode('ascii') | |
1166 | #print '2- oname: <%r>' % oname # dbg |
|
1173 | #print '2- oname: <%r>' % oname # dbg | |
1167 | except UnicodeEncodeError: |
|
1174 | except UnicodeEncodeError: | |
1168 | print 'Python identifiers can only contain ascii characters.' |
|
1175 | print 'Python identifiers can only contain ascii characters.' | |
1169 | return dict(found=False) |
|
1176 | return dict(found=False) | |
1170 |
|
1177 | |||
1171 | alias_ns = None |
|
1178 | alias_ns = None | |
1172 | if namespaces is None: |
|
1179 | if namespaces is None: | |
1173 | # Namespaces to search in: |
|
1180 | # Namespaces to search in: | |
1174 | # Put them in a list. The order is important so that we |
|
1181 | # Put them in a list. The order is important so that we | |
1175 | # find things in the same order that Python finds them. |
|
1182 | # find things in the same order that Python finds them. | |
1176 | namespaces = [ ('Interactive', self.user_ns), |
|
1183 | namespaces = [ ('Interactive', self.user_ns), | |
1177 | ('IPython internal', self.internal_ns), |
|
1184 | ('IPython internal', self.internal_ns), | |
1178 | ('Python builtin', __builtin__.__dict__), |
|
1185 | ('Python builtin', __builtin__.__dict__), | |
1179 | ('Alias', self.alias_manager.alias_table), |
|
1186 | ('Alias', self.alias_manager.alias_table), | |
1180 | ] |
|
1187 | ] | |
1181 | alias_ns = self.alias_manager.alias_table |
|
1188 | alias_ns = self.alias_manager.alias_table | |
1182 |
|
1189 | |||
1183 | # initialize results to 'null' |
|
1190 | # initialize results to 'null' | |
1184 | found = False; obj = None; ospace = None; ds = None; |
|
1191 | found = False; obj = None; ospace = None; ds = None; | |
1185 | ismagic = False; isalias = False; parent = None |
|
1192 | ismagic = False; isalias = False; parent = None | |
1186 |
|
1193 | |||
1187 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1194 | # We need to special-case 'print', which as of python2.6 registers as a | |
1188 | # function but should only be treated as one if print_function was |
|
1195 | # function but should only be treated as one if print_function was | |
1189 | # loaded with a future import. In this case, just bail. |
|
1196 | # loaded with a future import. In this case, just bail. | |
1190 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1197 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1191 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1198 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1192 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1199 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1193 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1200 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1194 |
|
1201 | |||
1195 | # Look for the given name by splitting it in parts. If the head is |
|
1202 | # Look for the given name by splitting it in parts. If the head is | |
1196 | # found, then we look for all the remaining parts as members, and only |
|
1203 | # found, then we look for all the remaining parts as members, and only | |
1197 | # declare success if we can find them all. |
|
1204 | # declare success if we can find them all. | |
1198 | oname_parts = oname.split('.') |
|
1205 | oname_parts = oname.split('.') | |
1199 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1206 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1200 | for nsname,ns in namespaces: |
|
1207 | for nsname,ns in namespaces: | |
1201 | try: |
|
1208 | try: | |
1202 | obj = ns[oname_head] |
|
1209 | obj = ns[oname_head] | |
1203 | except KeyError: |
|
1210 | except KeyError: | |
1204 | continue |
|
1211 | continue | |
1205 | else: |
|
1212 | else: | |
1206 | #print 'oname_rest:', oname_rest # dbg |
|
1213 | #print 'oname_rest:', oname_rest # dbg | |
1207 | for part in oname_rest: |
|
1214 | for part in oname_rest: | |
1208 | try: |
|
1215 | try: | |
1209 | parent = obj |
|
1216 | parent = obj | |
1210 | obj = getattr(obj,part) |
|
1217 | obj = getattr(obj,part) | |
1211 | except: |
|
1218 | except: | |
1212 | # Blanket except b/c some badly implemented objects |
|
1219 | # Blanket except b/c some badly implemented objects | |
1213 | # allow __getattr__ to raise exceptions other than |
|
1220 | # allow __getattr__ to raise exceptions other than | |
1214 | # AttributeError, which then crashes IPython. |
|
1221 | # AttributeError, which then crashes IPython. | |
1215 | break |
|
1222 | break | |
1216 | else: |
|
1223 | else: | |
1217 | # If we finish the for loop (no break), we got all members |
|
1224 | # If we finish the for loop (no break), we got all members | |
1218 | found = True |
|
1225 | found = True | |
1219 | ospace = nsname |
|
1226 | ospace = nsname | |
1220 | if ns == alias_ns: |
|
1227 | if ns == alias_ns: | |
1221 | isalias = True |
|
1228 | isalias = True | |
1222 | break # namespace loop |
|
1229 | break # namespace loop | |
1223 |
|
1230 | |||
1224 | # Try to see if it's magic |
|
1231 | # Try to see if it's magic | |
1225 | if not found: |
|
1232 | if not found: | |
1226 | if oname.startswith(ESC_MAGIC): |
|
1233 | if oname.startswith(ESC_MAGIC): | |
1227 | oname = oname[1:] |
|
1234 | oname = oname[1:] | |
1228 | obj = getattr(self,'magic_'+oname,None) |
|
1235 | obj = getattr(self,'magic_'+oname,None) | |
1229 | if obj is not None: |
|
1236 | if obj is not None: | |
1230 | found = True |
|
1237 | found = True | |
1231 | ospace = 'IPython internal' |
|
1238 | ospace = 'IPython internal' | |
1232 | ismagic = True |
|
1239 | ismagic = True | |
1233 |
|
1240 | |||
1234 | # Last try: special-case some literals like '', [], {}, etc: |
|
1241 | # Last try: special-case some literals like '', [], {}, etc: | |
1235 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1242 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1236 | obj = eval(oname_head) |
|
1243 | obj = eval(oname_head) | |
1237 | found = True |
|
1244 | found = True | |
1238 | ospace = 'Interactive' |
|
1245 | ospace = 'Interactive' | |
1239 |
|
1246 | |||
1240 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1247 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1241 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1248 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1242 |
|
1249 | |||
1243 | def _ofind_property(self, oname, info): |
|
1250 | def _ofind_property(self, oname, info): | |
1244 | """Second part of object finding, to look for property details.""" |
|
1251 | """Second part of object finding, to look for property details.""" | |
1245 | if info.found: |
|
1252 | if info.found: | |
1246 | # Get the docstring of the class property if it exists. |
|
1253 | # Get the docstring of the class property if it exists. | |
1247 | path = oname.split('.') |
|
1254 | path = oname.split('.') | |
1248 | root = '.'.join(path[:-1]) |
|
1255 | root = '.'.join(path[:-1]) | |
1249 | if info.parent is not None: |
|
1256 | if info.parent is not None: | |
1250 | try: |
|
1257 | try: | |
1251 | target = getattr(info.parent, '__class__') |
|
1258 | target = getattr(info.parent, '__class__') | |
1252 | # The object belongs to a class instance. |
|
1259 | # The object belongs to a class instance. | |
1253 | try: |
|
1260 | try: | |
1254 | target = getattr(target, path[-1]) |
|
1261 | target = getattr(target, path[-1]) | |
1255 | # The class defines the object. |
|
1262 | # The class defines the object. | |
1256 | if isinstance(target, property): |
|
1263 | if isinstance(target, property): | |
1257 | oname = root + '.__class__.' + path[-1] |
|
1264 | oname = root + '.__class__.' + path[-1] | |
1258 | info = Struct(self._ofind(oname)) |
|
1265 | info = Struct(self._ofind(oname)) | |
1259 | except AttributeError: pass |
|
1266 | except AttributeError: pass | |
1260 | except AttributeError: pass |
|
1267 | except AttributeError: pass | |
1261 |
|
1268 | |||
1262 | # We return either the new info or the unmodified input if the object |
|
1269 | # We return either the new info or the unmodified input if the object | |
1263 | # hadn't been found |
|
1270 | # hadn't been found | |
1264 | return info |
|
1271 | return info | |
1265 |
|
1272 | |||
1266 | def _object_find(self, oname, namespaces=None): |
|
1273 | def _object_find(self, oname, namespaces=None): | |
1267 | """Find an object and return a struct with info about it.""" |
|
1274 | """Find an object and return a struct with info about it.""" | |
1268 | inf = Struct(self._ofind(oname, namespaces)) |
|
1275 | inf = Struct(self._ofind(oname, namespaces)) | |
1269 | return Struct(self._ofind_property(oname, inf)) |
|
1276 | return Struct(self._ofind_property(oname, inf)) | |
1270 |
|
1277 | |||
1271 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1278 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1272 | """Generic interface to the inspector system. |
|
1279 | """Generic interface to the inspector system. | |
1273 |
|
1280 | |||
1274 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1281 | This function is meant to be called by pdef, pdoc & friends.""" | |
1275 | info = self._object_find(oname) |
|
1282 | info = self._object_find(oname) | |
1276 | if info.found: |
|
1283 | if info.found: | |
1277 | pmethod = getattr(self.inspector, meth) |
|
1284 | pmethod = getattr(self.inspector, meth) | |
1278 | formatter = format_screen if info.ismagic else None |
|
1285 | formatter = format_screen if info.ismagic else None | |
1279 | if meth == 'pdoc': |
|
1286 | if meth == 'pdoc': | |
1280 | pmethod(info.obj, oname, formatter) |
|
1287 | pmethod(info.obj, oname, formatter) | |
1281 | elif meth == 'pinfo': |
|
1288 | elif meth == 'pinfo': | |
1282 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1289 | pmethod(info.obj, oname, formatter, info, **kw) | |
1283 | else: |
|
1290 | else: | |
1284 | pmethod(info.obj, oname) |
|
1291 | pmethod(info.obj, oname) | |
1285 | else: |
|
1292 | else: | |
1286 | print 'Object `%s` not found.' % oname |
|
1293 | print 'Object `%s` not found.' % oname | |
1287 | return 'not found' # so callers can take other action |
|
1294 | return 'not found' # so callers can take other action | |
1288 |
|
1295 | |||
1289 | def object_inspect(self, oname): |
|
1296 | def object_inspect(self, oname): | |
1290 | with self.builtin_trap: |
|
1297 | with self.builtin_trap: | |
1291 | info = self._object_find(oname) |
|
1298 | info = self._object_find(oname) | |
1292 | if info.found: |
|
1299 | if info.found: | |
1293 | return self.inspector.info(info.obj, oname, info=info) |
|
1300 | return self.inspector.info(info.obj, oname, info=info) | |
1294 | else: |
|
1301 | else: | |
1295 | return oinspect.object_info(name=oname, found=False) |
|
1302 | return oinspect.object_info(name=oname, found=False) | |
1296 |
|
1303 | |||
1297 | #------------------------------------------------------------------------- |
|
1304 | #------------------------------------------------------------------------- | |
1298 | # Things related to history management |
|
1305 | # Things related to history management | |
1299 | #------------------------------------------------------------------------- |
|
1306 | #------------------------------------------------------------------------- | |
1300 |
|
1307 | |||
1301 | def init_history(self): |
|
1308 | def init_history(self): | |
1302 | """Sets up the command history, and starts regular autosaves.""" |
|
1309 | """Sets up the command history, and starts regular autosaves.""" | |
1303 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1310 | self.history_manager = HistoryManager(shell=self, config=self.config) | |
1304 |
|
1311 | |||
1305 | #------------------------------------------------------------------------- |
|
1312 | #------------------------------------------------------------------------- | |
1306 | # Things related to exception handling and tracebacks (not debugging) |
|
1313 | # Things related to exception handling and tracebacks (not debugging) | |
1307 | #------------------------------------------------------------------------- |
|
1314 | #------------------------------------------------------------------------- | |
1308 |
|
1315 | |||
1309 | def init_traceback_handlers(self, custom_exceptions): |
|
1316 | def init_traceback_handlers(self, custom_exceptions): | |
1310 | # Syntax error handler. |
|
1317 | # Syntax error handler. | |
1311 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1318 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1312 |
|
1319 | |||
1313 | # The interactive one is initialized with an offset, meaning we always |
|
1320 | # The interactive one is initialized with an offset, meaning we always | |
1314 | # want to remove the topmost item in the traceback, which is our own |
|
1321 | # want to remove the topmost item in the traceback, which is our own | |
1315 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1322 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1316 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1323 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1317 | color_scheme='NoColor', |
|
1324 | color_scheme='NoColor', | |
1318 | tb_offset = 1, |
|
1325 | tb_offset = 1, | |
1319 | check_cache=self.compile.check_cache) |
|
1326 | check_cache=self.compile.check_cache) | |
1320 |
|
1327 | |||
1321 | # The instance will store a pointer to the system-wide exception hook, |
|
1328 | # The instance will store a pointer to the system-wide exception hook, | |
1322 | # so that runtime code (such as magics) can access it. This is because |
|
1329 | # so that runtime code (such as magics) can access it. This is because | |
1323 | # during the read-eval loop, it may get temporarily overwritten. |
|
1330 | # during the read-eval loop, it may get temporarily overwritten. | |
1324 | self.sys_excepthook = sys.excepthook |
|
1331 | self.sys_excepthook = sys.excepthook | |
1325 |
|
1332 | |||
1326 | # and add any custom exception handlers the user may have specified |
|
1333 | # and add any custom exception handlers the user may have specified | |
1327 | self.set_custom_exc(*custom_exceptions) |
|
1334 | self.set_custom_exc(*custom_exceptions) | |
1328 |
|
1335 | |||
1329 | # Set the exception mode |
|
1336 | # Set the exception mode | |
1330 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1337 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1331 |
|
1338 | |||
1332 | def set_custom_exc(self, exc_tuple, handler): |
|
1339 | def set_custom_exc(self, exc_tuple, handler): | |
1333 | """set_custom_exc(exc_tuple,handler) |
|
1340 | """set_custom_exc(exc_tuple,handler) | |
1334 |
|
1341 | |||
1335 | Set a custom exception handler, which will be called if any of the |
|
1342 | Set a custom exception handler, which will be called if any of the | |
1336 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1343 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1337 | run_code() method. |
|
1344 | run_code() method. | |
1338 |
|
1345 | |||
1339 | Inputs: |
|
1346 | Inputs: | |
1340 |
|
1347 | |||
1341 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1348 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1342 | handler for. It is very important that you use a tuple, and NOT A |
|
1349 | handler for. It is very important that you use a tuple, and NOT A | |
1343 | LIST here, because of the way Python's except statement works. If |
|
1350 | LIST here, because of the way Python's except statement works. If | |
1344 | you only want to trap a single exception, use a singleton tuple: |
|
1351 | you only want to trap a single exception, use a singleton tuple: | |
1345 |
|
1352 | |||
1346 | exc_tuple == (MyCustomException,) |
|
1353 | exc_tuple == (MyCustomException,) | |
1347 |
|
1354 | |||
1348 | - handler: this must be defined as a function with the following |
|
1355 | - handler: this must be defined as a function with the following | |
1349 | basic interface:: |
|
1356 | basic interface:: | |
1350 |
|
1357 | |||
1351 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1358 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1352 | ... |
|
1359 | ... | |
1353 | # The return value must be |
|
1360 | # The return value must be | |
1354 | return structured_traceback |
|
1361 | return structured_traceback | |
1355 |
|
1362 | |||
1356 | This will be made into an instance method (via types.MethodType) |
|
1363 | This will be made into an instance method (via types.MethodType) | |
1357 | of IPython itself, and it will be called if any of the exceptions |
|
1364 | of IPython itself, and it will be called if any of the exceptions | |
1358 | listed in the exc_tuple are caught. If the handler is None, an |
|
1365 | listed in the exc_tuple are caught. If the handler is None, an | |
1359 | internal basic one is used, which just prints basic info. |
|
1366 | internal basic one is used, which just prints basic info. | |
1360 |
|
1367 | |||
1361 | WARNING: by putting in your own exception handler into IPython's main |
|
1368 | WARNING: by putting in your own exception handler into IPython's main | |
1362 | execution loop, you run a very good chance of nasty crashes. This |
|
1369 | execution loop, you run a very good chance of nasty crashes. This | |
1363 | facility should only be used if you really know what you are doing.""" |
|
1370 | facility should only be used if you really know what you are doing.""" | |
1364 |
|
1371 | |||
1365 | assert type(exc_tuple)==type(()) , \ |
|
1372 | assert type(exc_tuple)==type(()) , \ | |
1366 | "The custom exceptions must be given AS A TUPLE." |
|
1373 | "The custom exceptions must be given AS A TUPLE." | |
1367 |
|
1374 | |||
1368 | def dummy_handler(self,etype,value,tb): |
|
1375 | def dummy_handler(self,etype,value,tb): | |
1369 | print '*** Simple custom exception handler ***' |
|
1376 | print '*** Simple custom exception handler ***' | |
1370 | print 'Exception type :',etype |
|
1377 | print 'Exception type :',etype | |
1371 | print 'Exception value:',value |
|
1378 | print 'Exception value:',value | |
1372 | print 'Traceback :',tb |
|
1379 | print 'Traceback :',tb | |
1373 | print 'Source code :','\n'.join(self.buffer) |
|
1380 | print 'Source code :','\n'.join(self.buffer) | |
1374 |
|
1381 | |||
1375 | if handler is None: handler = dummy_handler |
|
1382 | if handler is None: handler = dummy_handler | |
1376 |
|
1383 | |||
1377 | self.CustomTB = types.MethodType(handler,self) |
|
1384 | self.CustomTB = types.MethodType(handler,self) | |
1378 | self.custom_exceptions = exc_tuple |
|
1385 | self.custom_exceptions = exc_tuple | |
1379 |
|
1386 | |||
1380 | def excepthook(self, etype, value, tb): |
|
1387 | def excepthook(self, etype, value, tb): | |
1381 | """One more defense for GUI apps that call sys.excepthook. |
|
1388 | """One more defense for GUI apps that call sys.excepthook. | |
1382 |
|
1389 | |||
1383 | GUI frameworks like wxPython trap exceptions and call |
|
1390 | GUI frameworks like wxPython trap exceptions and call | |
1384 | sys.excepthook themselves. I guess this is a feature that |
|
1391 | sys.excepthook themselves. I guess this is a feature that | |
1385 | enables them to keep running after exceptions that would |
|
1392 | enables them to keep running after exceptions that would | |
1386 | otherwise kill their mainloop. This is a bother for IPython |
|
1393 | otherwise kill their mainloop. This is a bother for IPython | |
1387 | which excepts to catch all of the program exceptions with a try: |
|
1394 | which excepts to catch all of the program exceptions with a try: | |
1388 | except: statement. |
|
1395 | except: statement. | |
1389 |
|
1396 | |||
1390 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1397 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1391 | any app directly invokes sys.excepthook, it will look to the user like |
|
1398 | any app directly invokes sys.excepthook, it will look to the user like | |
1392 | IPython crashed. In order to work around this, we can disable the |
|
1399 | IPython crashed. In order to work around this, we can disable the | |
1393 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1400 | CrashHandler and replace it with this excepthook instead, which prints a | |
1394 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1401 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1395 | call sys.excepthook will generate a regular-looking exception from |
|
1402 | call sys.excepthook will generate a regular-looking exception from | |
1396 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1403 | IPython, and the CrashHandler will only be triggered by real IPython | |
1397 | crashes. |
|
1404 | crashes. | |
1398 |
|
1405 | |||
1399 | This hook should be used sparingly, only in places which are not likely |
|
1406 | This hook should be used sparingly, only in places which are not likely | |
1400 | to be true IPython errors. |
|
1407 | to be true IPython errors. | |
1401 | """ |
|
1408 | """ | |
1402 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1409 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1403 |
|
1410 | |||
1404 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1411 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1405 | exception_only=False): |
|
1412 | exception_only=False): | |
1406 | """Display the exception that just occurred. |
|
1413 | """Display the exception that just occurred. | |
1407 |
|
1414 | |||
1408 | If nothing is known about the exception, this is the method which |
|
1415 | If nothing is known about the exception, this is the method which | |
1409 | should be used throughout the code for presenting user tracebacks, |
|
1416 | should be used throughout the code for presenting user tracebacks, | |
1410 | rather than directly invoking the InteractiveTB object. |
|
1417 | rather than directly invoking the InteractiveTB object. | |
1411 |
|
1418 | |||
1412 | A specific showsyntaxerror() also exists, but this method can take |
|
1419 | A specific showsyntaxerror() also exists, but this method can take | |
1413 | care of calling it if needed, so unless you are explicitly catching a |
|
1420 | care of calling it if needed, so unless you are explicitly catching a | |
1414 | SyntaxError exception, don't try to analyze the stack manually and |
|
1421 | SyntaxError exception, don't try to analyze the stack manually and | |
1415 | simply call this method.""" |
|
1422 | simply call this method.""" | |
1416 |
|
1423 | |||
1417 | try: |
|
1424 | try: | |
1418 | if exc_tuple is None: |
|
1425 | if exc_tuple is None: | |
1419 | etype, value, tb = sys.exc_info() |
|
1426 | etype, value, tb = sys.exc_info() | |
1420 | else: |
|
1427 | else: | |
1421 | etype, value, tb = exc_tuple |
|
1428 | etype, value, tb = exc_tuple | |
1422 |
|
1429 | |||
1423 | if etype is None: |
|
1430 | if etype is None: | |
1424 | if hasattr(sys, 'last_type'): |
|
1431 | if hasattr(sys, 'last_type'): | |
1425 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1432 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1426 | sys.last_traceback |
|
1433 | sys.last_traceback | |
1427 | else: |
|
1434 | else: | |
1428 | self.write_err('No traceback available to show.\n') |
|
1435 | self.write_err('No traceback available to show.\n') | |
1429 | return |
|
1436 | return | |
1430 |
|
1437 | |||
1431 | if etype is SyntaxError: |
|
1438 | if etype is SyntaxError: | |
1432 | # Though this won't be called by syntax errors in the input |
|
1439 | # Though this won't be called by syntax errors in the input | |
1433 | # line, there may be SyntaxError cases whith imported code. |
|
1440 | # line, there may be SyntaxError cases whith imported code. | |
1434 | self.showsyntaxerror(filename) |
|
1441 | self.showsyntaxerror(filename) | |
1435 | elif etype is UsageError: |
|
1442 | elif etype is UsageError: | |
1436 | print "UsageError:", value |
|
1443 | print "UsageError:", value | |
1437 | else: |
|
1444 | else: | |
1438 | # WARNING: these variables are somewhat deprecated and not |
|
1445 | # WARNING: these variables are somewhat deprecated and not | |
1439 | # necessarily safe to use in a threaded environment, but tools |
|
1446 | # necessarily safe to use in a threaded environment, but tools | |
1440 | # like pdb depend on their existence, so let's set them. If we |
|
1447 | # like pdb depend on their existence, so let's set them. If we | |
1441 | # find problems in the field, we'll need to revisit their use. |
|
1448 | # find problems in the field, we'll need to revisit their use. | |
1442 | sys.last_type = etype |
|
1449 | sys.last_type = etype | |
1443 | sys.last_value = value |
|
1450 | sys.last_value = value | |
1444 | sys.last_traceback = tb |
|
1451 | sys.last_traceback = tb | |
1445 | if etype in self.custom_exceptions: |
|
1452 | if etype in self.custom_exceptions: | |
1446 | # FIXME: Old custom traceback objects may just return a |
|
1453 | # FIXME: Old custom traceback objects may just return a | |
1447 | # string, in that case we just put it into a list |
|
1454 | # string, in that case we just put it into a list | |
1448 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1455 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1449 | if isinstance(ctb, basestring): |
|
1456 | if isinstance(ctb, basestring): | |
1450 | stb = [stb] |
|
1457 | stb = [stb] | |
1451 | else: |
|
1458 | else: | |
1452 | if exception_only: |
|
1459 | if exception_only: | |
1453 | stb = ['An exception has occurred, use %tb to see ' |
|
1460 | stb = ['An exception has occurred, use %tb to see ' | |
1454 | 'the full traceback.\n'] |
|
1461 | 'the full traceback.\n'] | |
1455 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1462 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1456 | value)) |
|
1463 | value)) | |
1457 | else: |
|
1464 | else: | |
1458 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1465 | stb = self.InteractiveTB.structured_traceback(etype, | |
1459 | value, tb, tb_offset=tb_offset) |
|
1466 | value, tb, tb_offset=tb_offset) | |
1460 |
|
1467 | |||
1461 | if self.call_pdb: |
|
1468 | if self.call_pdb: | |
1462 | # drop into debugger |
|
1469 | # drop into debugger | |
1463 | self.debugger(force=True) |
|
1470 | self.debugger(force=True) | |
1464 |
|
1471 | |||
1465 | # Actually show the traceback |
|
1472 | # Actually show the traceback | |
1466 | self._showtraceback(etype, value, stb) |
|
1473 | self._showtraceback(etype, value, stb) | |
1467 |
|
1474 | |||
1468 | except KeyboardInterrupt: |
|
1475 | except KeyboardInterrupt: | |
1469 | self.write_err("\nKeyboardInterrupt\n") |
|
1476 | self.write_err("\nKeyboardInterrupt\n") | |
1470 |
|
1477 | |||
1471 | def _showtraceback(self, etype, evalue, stb): |
|
1478 | def _showtraceback(self, etype, evalue, stb): | |
1472 | """Actually show a traceback. |
|
1479 | """Actually show a traceback. | |
1473 |
|
1480 | |||
1474 | Subclasses may override this method to put the traceback on a different |
|
1481 | Subclasses may override this method to put the traceback on a different | |
1475 | place, like a side channel. |
|
1482 | place, like a side channel. | |
1476 | """ |
|
1483 | """ | |
1477 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1484 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1478 |
|
1485 | |||
1479 | def showsyntaxerror(self, filename=None): |
|
1486 | def showsyntaxerror(self, filename=None): | |
1480 | """Display the syntax error that just occurred. |
|
1487 | """Display the syntax error that just occurred. | |
1481 |
|
1488 | |||
1482 | This doesn't display a stack trace because there isn't one. |
|
1489 | This doesn't display a stack trace because there isn't one. | |
1483 |
|
1490 | |||
1484 | If a filename is given, it is stuffed in the exception instead |
|
1491 | If a filename is given, it is stuffed in the exception instead | |
1485 | of what was there before (because Python's parser always uses |
|
1492 | of what was there before (because Python's parser always uses | |
1486 | "<string>" when reading from a string). |
|
1493 | "<string>" when reading from a string). | |
1487 | """ |
|
1494 | """ | |
1488 | etype, value, last_traceback = sys.exc_info() |
|
1495 | etype, value, last_traceback = sys.exc_info() | |
1489 |
|
1496 | |||
1490 | # See note about these variables in showtraceback() above |
|
1497 | # See note about these variables in showtraceback() above | |
1491 | sys.last_type = etype |
|
1498 | sys.last_type = etype | |
1492 | sys.last_value = value |
|
1499 | sys.last_value = value | |
1493 | sys.last_traceback = last_traceback |
|
1500 | sys.last_traceback = last_traceback | |
1494 |
|
1501 | |||
1495 | if filename and etype is SyntaxError: |
|
1502 | if filename and etype is SyntaxError: | |
1496 | # Work hard to stuff the correct filename in the exception |
|
1503 | # Work hard to stuff the correct filename in the exception | |
1497 | try: |
|
1504 | try: | |
1498 | msg, (dummy_filename, lineno, offset, line) = value |
|
1505 | msg, (dummy_filename, lineno, offset, line) = value | |
1499 | except: |
|
1506 | except: | |
1500 | # Not the format we expect; leave it alone |
|
1507 | # Not the format we expect; leave it alone | |
1501 | pass |
|
1508 | pass | |
1502 | else: |
|
1509 | else: | |
1503 | # Stuff in the right filename |
|
1510 | # Stuff in the right filename | |
1504 | try: |
|
1511 | try: | |
1505 | # Assume SyntaxError is a class exception |
|
1512 | # Assume SyntaxError is a class exception | |
1506 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1513 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1507 | except: |
|
1514 | except: | |
1508 | # If that failed, assume SyntaxError is a string |
|
1515 | # If that failed, assume SyntaxError is a string | |
1509 | value = msg, (filename, lineno, offset, line) |
|
1516 | value = msg, (filename, lineno, offset, line) | |
1510 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1517 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1511 | self._showtraceback(etype, value, stb) |
|
1518 | self._showtraceback(etype, value, stb) | |
1512 |
|
1519 | |||
1513 | #------------------------------------------------------------------------- |
|
1520 | #------------------------------------------------------------------------- | |
1514 | # Things related to readline |
|
1521 | # Things related to readline | |
1515 | #------------------------------------------------------------------------- |
|
1522 | #------------------------------------------------------------------------- | |
1516 |
|
1523 | |||
1517 | def init_readline(self): |
|
1524 | def init_readline(self): | |
1518 | """Command history completion/saving/reloading.""" |
|
1525 | """Command history completion/saving/reloading.""" | |
1519 |
|
1526 | |||
1520 | if self.readline_use: |
|
1527 | if self.readline_use: | |
1521 | import IPython.utils.rlineimpl as readline |
|
1528 | import IPython.utils.rlineimpl as readline | |
1522 |
|
1529 | |||
1523 | self.rl_next_input = None |
|
1530 | self.rl_next_input = None | |
1524 | self.rl_do_indent = False |
|
1531 | self.rl_do_indent = False | |
1525 |
|
1532 | |||
1526 | if not self.readline_use or not readline.have_readline: |
|
1533 | if not self.readline_use or not readline.have_readline: | |
1527 | self.has_readline = False |
|
1534 | self.has_readline = False | |
1528 | self.readline = None |
|
1535 | self.readline = None | |
1529 | # Set a number of methods that depend on readline to be no-op |
|
1536 | # Set a number of methods that depend on readline to be no-op | |
1530 | self.set_readline_completer = no_op |
|
1537 | self.set_readline_completer = no_op | |
1531 | self.set_custom_completer = no_op |
|
1538 | self.set_custom_completer = no_op | |
1532 | self.set_completer_frame = no_op |
|
1539 | self.set_completer_frame = no_op | |
1533 | warn('Readline services not available or not loaded.') |
|
1540 | warn('Readline services not available or not loaded.') | |
1534 | else: |
|
1541 | else: | |
1535 | self.has_readline = True |
|
1542 | self.has_readline = True | |
1536 | self.readline = readline |
|
1543 | self.readline = readline | |
1537 | sys.modules['readline'] = readline |
|
1544 | sys.modules['readline'] = readline | |
1538 |
|
1545 | |||
1539 | # Platform-specific configuration |
|
1546 | # Platform-specific configuration | |
1540 | if os.name == 'nt': |
|
1547 | if os.name == 'nt': | |
1541 | # FIXME - check with Frederick to see if we can harmonize |
|
1548 | # FIXME - check with Frederick to see if we can harmonize | |
1542 | # naming conventions with pyreadline to avoid this |
|
1549 | # naming conventions with pyreadline to avoid this | |
1543 | # platform-dependent check |
|
1550 | # platform-dependent check | |
1544 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1551 | self.readline_startup_hook = readline.set_pre_input_hook | |
1545 | else: |
|
1552 | else: | |
1546 | self.readline_startup_hook = readline.set_startup_hook |
|
1553 | self.readline_startup_hook = readline.set_startup_hook | |
1547 |
|
1554 | |||
1548 | # Load user's initrc file (readline config) |
|
1555 | # Load user's initrc file (readline config) | |
1549 | # Or if libedit is used, load editrc. |
|
1556 | # Or if libedit is used, load editrc. | |
1550 | inputrc_name = os.environ.get('INPUTRC') |
|
1557 | inputrc_name = os.environ.get('INPUTRC') | |
1551 | if inputrc_name is None: |
|
1558 | if inputrc_name is None: | |
1552 | home_dir = get_home_dir() |
|
1559 | home_dir = get_home_dir() | |
1553 | if home_dir is not None: |
|
1560 | if home_dir is not None: | |
1554 | inputrc_name = '.inputrc' |
|
1561 | inputrc_name = '.inputrc' | |
1555 | if readline.uses_libedit: |
|
1562 | if readline.uses_libedit: | |
1556 | inputrc_name = '.editrc' |
|
1563 | inputrc_name = '.editrc' | |
1557 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1564 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1558 | if os.path.isfile(inputrc_name): |
|
1565 | if os.path.isfile(inputrc_name): | |
1559 | try: |
|
1566 | try: | |
1560 | readline.read_init_file(inputrc_name) |
|
1567 | readline.read_init_file(inputrc_name) | |
1561 | except: |
|
1568 | except: | |
1562 | warn('Problems reading readline initialization file <%s>' |
|
1569 | warn('Problems reading readline initialization file <%s>' | |
1563 | % inputrc_name) |
|
1570 | % inputrc_name) | |
1564 |
|
1571 | |||
1565 | # Configure readline according to user's prefs |
|
1572 | # Configure readline according to user's prefs | |
1566 | # This is only done if GNU readline is being used. If libedit |
|
1573 | # This is only done if GNU readline is being used. If libedit | |
1567 | # is being used (as on Leopard) the readline config is |
|
1574 | # is being used (as on Leopard) the readline config is | |
1568 | # not run as the syntax for libedit is different. |
|
1575 | # not run as the syntax for libedit is different. | |
1569 | if not readline.uses_libedit: |
|
1576 | if not readline.uses_libedit: | |
1570 | for rlcommand in self.readline_parse_and_bind: |
|
1577 | for rlcommand in self.readline_parse_and_bind: | |
1571 | #print "loading rl:",rlcommand # dbg |
|
1578 | #print "loading rl:",rlcommand # dbg | |
1572 | readline.parse_and_bind(rlcommand) |
|
1579 | readline.parse_and_bind(rlcommand) | |
1573 |
|
1580 | |||
1574 | # Remove some chars from the delimiters list. If we encounter |
|
1581 | # Remove some chars from the delimiters list. If we encounter | |
1575 | # unicode chars, discard them. |
|
1582 | # unicode chars, discard them. | |
1576 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1583 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1577 | delims = delims.translate(None, self.readline_remove_delims) |
|
1584 | delims = delims.translate(None, self.readline_remove_delims) | |
1578 | delims = delims.replace(ESC_MAGIC, '') |
|
1585 | delims = delims.replace(ESC_MAGIC, '') | |
1579 | readline.set_completer_delims(delims) |
|
1586 | readline.set_completer_delims(delims) | |
1580 | # otherwise we end up with a monster history after a while: |
|
1587 | # otherwise we end up with a monster history after a while: | |
1581 | readline.set_history_length(self.history_length) |
|
1588 | readline.set_history_length(self.history_length) | |
1582 |
|
1589 | |||
1583 | self.refill_readline_hist() |
|
1590 | self.refill_readline_hist() | |
1584 | self.readline_no_record = ReadlineNoRecord(self) |
|
1591 | self.readline_no_record = ReadlineNoRecord(self) | |
1585 |
|
1592 | |||
1586 | # Configure auto-indent for all platforms |
|
1593 | # Configure auto-indent for all platforms | |
1587 | self.set_autoindent(self.autoindent) |
|
1594 | self.set_autoindent(self.autoindent) | |
1588 |
|
1595 | |||
1589 | def refill_readline_hist(self): |
|
1596 | def refill_readline_hist(self): | |
1590 | # Load the last 1000 lines from history |
|
1597 | # Load the last 1000 lines from history | |
1591 | self.readline.clear_history() |
|
1598 | self.readline.clear_history() | |
1592 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1599 | stdin_encoding = sys.stdin.encoding or "utf-8" | |
1593 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1600 | for _, _, cell in self.history_manager.get_tail(1000, | |
1594 | include_latest=True): |
|
1601 | include_latest=True): | |
1595 | if cell.strip(): # Ignore blank lines |
|
1602 | if cell.strip(): # Ignore blank lines | |
1596 | for line in cell.splitlines(): |
|
1603 | for line in cell.splitlines(): | |
1597 | self.readline.add_history(line.encode(stdin_encoding)) |
|
1604 | self.readline.add_history(line.encode(stdin_encoding)) | |
1598 |
|
1605 | |||
1599 | def set_next_input(self, s): |
|
1606 | def set_next_input(self, s): | |
1600 | """ Sets the 'default' input string for the next command line. |
|
1607 | """ Sets the 'default' input string for the next command line. | |
1601 |
|
1608 | |||
1602 | Requires readline. |
|
1609 | Requires readline. | |
1603 |
|
1610 | |||
1604 | Example: |
|
1611 | Example: | |
1605 |
|
1612 | |||
1606 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1613 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1607 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1614 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1608 | """ |
|
1615 | """ | |
1609 |
|
1616 | |||
1610 | self.rl_next_input = s |
|
1617 | self.rl_next_input = s | |
1611 |
|
1618 | |||
1612 | # Maybe move this to the terminal subclass? |
|
1619 | # Maybe move this to the terminal subclass? | |
1613 | def pre_readline(self): |
|
1620 | def pre_readline(self): | |
1614 | """readline hook to be used at the start of each line. |
|
1621 | """readline hook to be used at the start of each line. | |
1615 |
|
1622 | |||
1616 | Currently it handles auto-indent only.""" |
|
1623 | Currently it handles auto-indent only.""" | |
1617 |
|
1624 | |||
1618 | if self.rl_do_indent: |
|
1625 | if self.rl_do_indent: | |
1619 | self.readline.insert_text(self._indent_current_str()) |
|
1626 | self.readline.insert_text(self._indent_current_str()) | |
1620 | if self.rl_next_input is not None: |
|
1627 | if self.rl_next_input is not None: | |
1621 | self.readline.insert_text(self.rl_next_input) |
|
1628 | self.readline.insert_text(self.rl_next_input) | |
1622 | self.rl_next_input = None |
|
1629 | self.rl_next_input = None | |
1623 |
|
1630 | |||
1624 | def _indent_current_str(self): |
|
1631 | def _indent_current_str(self): | |
1625 | """return the current level of indentation as a string""" |
|
1632 | """return the current level of indentation as a string""" | |
1626 | return self.input_splitter.indent_spaces * ' ' |
|
1633 | return self.input_splitter.indent_spaces * ' ' | |
1627 |
|
1634 | |||
1628 | #------------------------------------------------------------------------- |
|
1635 | #------------------------------------------------------------------------- | |
1629 | # Things related to text completion |
|
1636 | # Things related to text completion | |
1630 | #------------------------------------------------------------------------- |
|
1637 | #------------------------------------------------------------------------- | |
1631 |
|
1638 | |||
1632 | def init_completer(self): |
|
1639 | def init_completer(self): | |
1633 | """Initialize the completion machinery. |
|
1640 | """Initialize the completion machinery. | |
1634 |
|
1641 | |||
1635 | This creates completion machinery that can be used by client code, |
|
1642 | This creates completion machinery that can be used by client code, | |
1636 | either interactively in-process (typically triggered by the readline |
|
1643 | either interactively in-process (typically triggered by the readline | |
1637 | library), programatically (such as in test suites) or out-of-prcess |
|
1644 | library), programatically (such as in test suites) or out-of-prcess | |
1638 | (typically over the network by remote frontends). |
|
1645 | (typically over the network by remote frontends). | |
1639 | """ |
|
1646 | """ | |
1640 | from IPython.core.completer import IPCompleter |
|
1647 | from IPython.core.completer import IPCompleter | |
1641 | from IPython.core.completerlib import (module_completer, |
|
1648 | from IPython.core.completerlib import (module_completer, | |
1642 | magic_run_completer, cd_completer) |
|
1649 | magic_run_completer, cd_completer) | |
1643 |
|
1650 | |||
1644 | self.Completer = IPCompleter(self, |
|
1651 | self.Completer = IPCompleter(self, | |
1645 | self.user_ns, |
|
1652 | self.user_ns, | |
1646 | self.user_global_ns, |
|
1653 | self.user_global_ns, | |
1647 | self.readline_omit__names, |
|
1654 | self.readline_omit__names, | |
1648 | self.alias_manager.alias_table, |
|
1655 | self.alias_manager.alias_table, | |
1649 | self.has_readline) |
|
1656 | self.has_readline) | |
1650 |
|
1657 | |||
1651 | # Add custom completers to the basic ones built into IPCompleter |
|
1658 | # Add custom completers to the basic ones built into IPCompleter | |
1652 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1659 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1653 | self.strdispatchers['complete_command'] = sdisp |
|
1660 | self.strdispatchers['complete_command'] = sdisp | |
1654 | self.Completer.custom_completers = sdisp |
|
1661 | self.Completer.custom_completers = sdisp | |
1655 |
|
1662 | |||
1656 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1663 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1657 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1664 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1658 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1665 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1659 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1666 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1660 |
|
1667 | |||
1661 | # Only configure readline if we truly are using readline. IPython can |
|
1668 | # Only configure readline if we truly are using readline. IPython can | |
1662 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1669 | # do tab-completion over the network, in GUIs, etc, where readline | |
1663 | # itself may be absent |
|
1670 | # itself may be absent | |
1664 | if self.has_readline: |
|
1671 | if self.has_readline: | |
1665 | self.set_readline_completer() |
|
1672 | self.set_readline_completer() | |
1666 |
|
1673 | |||
1667 | def complete(self, text, line=None, cursor_pos=None): |
|
1674 | def complete(self, text, line=None, cursor_pos=None): | |
1668 | """Return the completed text and a list of completions. |
|
1675 | """Return the completed text and a list of completions. | |
1669 |
|
1676 | |||
1670 | Parameters |
|
1677 | Parameters | |
1671 | ---------- |
|
1678 | ---------- | |
1672 |
|
1679 | |||
1673 | text : string |
|
1680 | text : string | |
1674 | A string of text to be completed on. It can be given as empty and |
|
1681 | A string of text to be completed on. It can be given as empty and | |
1675 | instead a line/position pair are given. In this case, the |
|
1682 | instead a line/position pair are given. In this case, the | |
1676 | completer itself will split the line like readline does. |
|
1683 | completer itself will split the line like readline does. | |
1677 |
|
1684 | |||
1678 | line : string, optional |
|
1685 | line : string, optional | |
1679 | The complete line that text is part of. |
|
1686 | The complete line that text is part of. | |
1680 |
|
1687 | |||
1681 | cursor_pos : int, optional |
|
1688 | cursor_pos : int, optional | |
1682 | The position of the cursor on the input line. |
|
1689 | The position of the cursor on the input line. | |
1683 |
|
1690 | |||
1684 | Returns |
|
1691 | Returns | |
1685 | ------- |
|
1692 | ------- | |
1686 | text : string |
|
1693 | text : string | |
1687 | The actual text that was completed. |
|
1694 | The actual text that was completed. | |
1688 |
|
1695 | |||
1689 | matches : list |
|
1696 | matches : list | |
1690 | A sorted list with all possible completions. |
|
1697 | A sorted list with all possible completions. | |
1691 |
|
1698 | |||
1692 | The optional arguments allow the completion to take more context into |
|
1699 | The optional arguments allow the completion to take more context into | |
1693 | account, and are part of the low-level completion API. |
|
1700 | account, and are part of the low-level completion API. | |
1694 |
|
1701 | |||
1695 | This is a wrapper around the completion mechanism, similar to what |
|
1702 | This is a wrapper around the completion mechanism, similar to what | |
1696 | readline does at the command line when the TAB key is hit. By |
|
1703 | readline does at the command line when the TAB key is hit. By | |
1697 | exposing it as a method, it can be used by other non-readline |
|
1704 | exposing it as a method, it can be used by other non-readline | |
1698 | environments (such as GUIs) for text completion. |
|
1705 | environments (such as GUIs) for text completion. | |
1699 |
|
1706 | |||
1700 | Simple usage example: |
|
1707 | Simple usage example: | |
1701 |
|
1708 | |||
1702 | In [1]: x = 'hello' |
|
1709 | In [1]: x = 'hello' | |
1703 |
|
1710 | |||
1704 | In [2]: _ip.complete('x.l') |
|
1711 | In [2]: _ip.complete('x.l') | |
1705 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1712 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1706 | """ |
|
1713 | """ | |
1707 |
|
1714 | |||
1708 | # Inject names into __builtin__ so we can complete on the added names. |
|
1715 | # Inject names into __builtin__ so we can complete on the added names. | |
1709 | with self.builtin_trap: |
|
1716 | with self.builtin_trap: | |
1710 | return self.Completer.complete(text, line, cursor_pos) |
|
1717 | return self.Completer.complete(text, line, cursor_pos) | |
1711 |
|
1718 | |||
1712 | def set_custom_completer(self, completer, pos=0): |
|
1719 | def set_custom_completer(self, completer, pos=0): | |
1713 | """Adds a new custom completer function. |
|
1720 | """Adds a new custom completer function. | |
1714 |
|
1721 | |||
1715 | The position argument (defaults to 0) is the index in the completers |
|
1722 | The position argument (defaults to 0) is the index in the completers | |
1716 | list where you want the completer to be inserted.""" |
|
1723 | list where you want the completer to be inserted.""" | |
1717 |
|
1724 | |||
1718 | newcomp = types.MethodType(completer,self.Completer) |
|
1725 | newcomp = types.MethodType(completer,self.Completer) | |
1719 | self.Completer.matchers.insert(pos,newcomp) |
|
1726 | self.Completer.matchers.insert(pos,newcomp) | |
1720 |
|
1727 | |||
1721 | def set_readline_completer(self): |
|
1728 | def set_readline_completer(self): | |
1722 | """Reset readline's completer to be our own.""" |
|
1729 | """Reset readline's completer to be our own.""" | |
1723 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1730 | self.readline.set_completer(self.Completer.rlcomplete) | |
1724 |
|
1731 | |||
1725 | def set_completer_frame(self, frame=None): |
|
1732 | def set_completer_frame(self, frame=None): | |
1726 | """Set the frame of the completer.""" |
|
1733 | """Set the frame of the completer.""" | |
1727 | if frame: |
|
1734 | if frame: | |
1728 | self.Completer.namespace = frame.f_locals |
|
1735 | self.Completer.namespace = frame.f_locals | |
1729 | self.Completer.global_namespace = frame.f_globals |
|
1736 | self.Completer.global_namespace = frame.f_globals | |
1730 | else: |
|
1737 | else: | |
1731 | self.Completer.namespace = self.user_ns |
|
1738 | self.Completer.namespace = self.user_ns | |
1732 | self.Completer.global_namespace = self.user_global_ns |
|
1739 | self.Completer.global_namespace = self.user_global_ns | |
1733 |
|
1740 | |||
1734 | #------------------------------------------------------------------------- |
|
1741 | #------------------------------------------------------------------------- | |
1735 | # Things related to magics |
|
1742 | # Things related to magics | |
1736 | #------------------------------------------------------------------------- |
|
1743 | #------------------------------------------------------------------------- | |
1737 |
|
1744 | |||
1738 | def init_magics(self): |
|
1745 | def init_magics(self): | |
1739 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1746 | # FIXME: Move the color initialization to the DisplayHook, which | |
1740 | # should be split into a prompt manager and displayhook. We probably |
|
1747 | # should be split into a prompt manager and displayhook. We probably | |
1741 | # even need a centralize colors management object. |
|
1748 | # even need a centralize colors management object. | |
1742 | self.magic_colors(self.colors) |
|
1749 | self.magic_colors(self.colors) | |
1743 | # History was moved to a separate module |
|
1750 | # History was moved to a separate module | |
1744 | from . import history |
|
1751 | from . import history | |
1745 | history.init_ipython(self) |
|
1752 | history.init_ipython(self) | |
1746 |
|
1753 | |||
1747 | def magic(self,arg_s): |
|
1754 | def magic(self,arg_s): | |
1748 | """Call a magic function by name. |
|
1755 | """Call a magic function by name. | |
1749 |
|
1756 | |||
1750 | Input: a string containing the name of the magic function to call and |
|
1757 | Input: a string containing the name of the magic function to call and | |
1751 | any additional arguments to be passed to the magic. |
|
1758 | any additional arguments to be passed to the magic. | |
1752 |
|
1759 | |||
1753 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1760 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1754 | prompt: |
|
1761 | prompt: | |
1755 |
|
1762 | |||
1756 | In[1]: %name -opt foo bar |
|
1763 | In[1]: %name -opt foo bar | |
1757 |
|
1764 | |||
1758 | To call a magic without arguments, simply use magic('name'). |
|
1765 | To call a magic without arguments, simply use magic('name'). | |
1759 |
|
1766 | |||
1760 | This provides a proper Python function to call IPython's magics in any |
|
1767 | This provides a proper Python function to call IPython's magics in any | |
1761 | valid Python code you can type at the interpreter, including loops and |
|
1768 | valid Python code you can type at the interpreter, including loops and | |
1762 | compound statements. |
|
1769 | compound statements. | |
1763 | """ |
|
1770 | """ | |
1764 | args = arg_s.split(' ',1) |
|
1771 | args = arg_s.split(' ',1) | |
1765 | magic_name = args[0] |
|
1772 | magic_name = args[0] | |
1766 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1773 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1767 |
|
1774 | |||
1768 | try: |
|
1775 | try: | |
1769 | magic_args = args[1] |
|
1776 | magic_args = args[1] | |
1770 | except IndexError: |
|
1777 | except IndexError: | |
1771 | magic_args = '' |
|
1778 | magic_args = '' | |
1772 | fn = getattr(self,'magic_'+magic_name,None) |
|
1779 | fn = getattr(self,'magic_'+magic_name,None) | |
1773 | if fn is None: |
|
1780 | if fn is None: | |
1774 | error("Magic function `%s` not found." % magic_name) |
|
1781 | error("Magic function `%s` not found." % magic_name) | |
1775 | else: |
|
1782 | else: | |
1776 | magic_args = self.var_expand(magic_args,1) |
|
1783 | magic_args = self.var_expand(magic_args,1) | |
1777 | # Grab local namespace if we need it: |
|
1784 | # Grab local namespace if we need it: | |
1778 | if getattr(fn, "needs_local_scope", False): |
|
1785 | if getattr(fn, "needs_local_scope", False): | |
1779 | self._magic_locals = sys._getframe(1).f_locals |
|
1786 | self._magic_locals = sys._getframe(1).f_locals | |
1780 | with nested(self.builtin_trap,): |
|
1787 | with nested(self.builtin_trap,): | |
1781 | result = fn(magic_args) |
|
1788 | result = fn(magic_args) | |
1782 | # Ensure we're not keeping object references around: |
|
1789 | # Ensure we're not keeping object references around: | |
1783 | self._magic_locals = {} |
|
1790 | self._magic_locals = {} | |
1784 | return result |
|
1791 | return result | |
1785 |
|
1792 | |||
1786 | def define_magic(self, magicname, func): |
|
1793 | def define_magic(self, magicname, func): | |
1787 | """Expose own function as magic function for ipython |
|
1794 | """Expose own function as magic function for ipython | |
1788 |
|
1795 | |||
1789 | def foo_impl(self,parameter_s=''): |
|
1796 | def foo_impl(self,parameter_s=''): | |
1790 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1797 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1791 | print 'Magic function. Passed parameter is between < >:' |
|
1798 | print 'Magic function. Passed parameter is between < >:' | |
1792 | print '<%s>' % parameter_s |
|
1799 | print '<%s>' % parameter_s | |
1793 | print 'The self object is:',self |
|
1800 | print 'The self object is:',self | |
1794 |
|
1801 | |||
1795 | self.define_magic('foo',foo_impl) |
|
1802 | self.define_magic('foo',foo_impl) | |
1796 | """ |
|
1803 | """ | |
1797 |
|
1804 | |||
1798 | import new |
|
1805 | import new | |
1799 | im = types.MethodType(func,self) |
|
1806 | im = types.MethodType(func,self) | |
1800 | old = getattr(self, "magic_" + magicname, None) |
|
1807 | old = getattr(self, "magic_" + magicname, None) | |
1801 | setattr(self, "magic_" + magicname, im) |
|
1808 | setattr(self, "magic_" + magicname, im) | |
1802 | return old |
|
1809 | return old | |
1803 |
|
1810 | |||
1804 | #------------------------------------------------------------------------- |
|
1811 | #------------------------------------------------------------------------- | |
1805 | # Things related to macros |
|
1812 | # Things related to macros | |
1806 | #------------------------------------------------------------------------- |
|
1813 | #------------------------------------------------------------------------- | |
1807 |
|
1814 | |||
1808 | def define_macro(self, name, themacro): |
|
1815 | def define_macro(self, name, themacro): | |
1809 | """Define a new macro |
|
1816 | """Define a new macro | |
1810 |
|
1817 | |||
1811 | Parameters |
|
1818 | Parameters | |
1812 | ---------- |
|
1819 | ---------- | |
1813 | name : str |
|
1820 | name : str | |
1814 | The name of the macro. |
|
1821 | The name of the macro. | |
1815 | themacro : str or Macro |
|
1822 | themacro : str or Macro | |
1816 | The action to do upon invoking the macro. If a string, a new |
|
1823 | The action to do upon invoking the macro. If a string, a new | |
1817 | Macro object is created by passing the string to it. |
|
1824 | Macro object is created by passing the string to it. | |
1818 | """ |
|
1825 | """ | |
1819 |
|
1826 | |||
1820 | from IPython.core import macro |
|
1827 | from IPython.core import macro | |
1821 |
|
1828 | |||
1822 | if isinstance(themacro, basestring): |
|
1829 | if isinstance(themacro, basestring): | |
1823 | themacro = macro.Macro(themacro) |
|
1830 | themacro = macro.Macro(themacro) | |
1824 | if not isinstance(themacro, macro.Macro): |
|
1831 | if not isinstance(themacro, macro.Macro): | |
1825 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1832 | raise ValueError('A macro must be a string or a Macro instance.') | |
1826 | self.user_ns[name] = themacro |
|
1833 | self.user_ns[name] = themacro | |
1827 |
|
1834 | |||
1828 | #------------------------------------------------------------------------- |
|
1835 | #------------------------------------------------------------------------- | |
1829 | # Things related to the running of system commands |
|
1836 | # Things related to the running of system commands | |
1830 | #------------------------------------------------------------------------- |
|
1837 | #------------------------------------------------------------------------- | |
1831 |
|
1838 | |||
1832 | def system(self, cmd): |
|
1839 | def system(self, cmd): | |
1833 | """Call the given cmd in a subprocess. |
|
1840 | """Call the given cmd in a subprocess. | |
1834 |
|
1841 | |||
1835 | Parameters |
|
1842 | Parameters | |
1836 | ---------- |
|
1843 | ---------- | |
1837 | cmd : str |
|
1844 | cmd : str | |
1838 | Command to execute (can not end in '&', as bacground processes are |
|
1845 | Command to execute (can not end in '&', as bacground processes are | |
1839 | not supported. |
|
1846 | not supported. | |
1840 | """ |
|
1847 | """ | |
1841 | # We do not support backgrounding processes because we either use |
|
1848 | # We do not support backgrounding processes because we either use | |
1842 | # pexpect or pipes to read from. Users can always just call |
|
1849 | # pexpect or pipes to read from. Users can always just call | |
1843 | # os.system() if they really want a background process. |
|
1850 | # os.system() if they really want a background process. | |
1844 | if cmd.endswith('&'): |
|
1851 | if cmd.endswith('&'): | |
1845 | raise OSError("Background processes not supported.") |
|
1852 | raise OSError("Background processes not supported.") | |
1846 |
|
1853 | |||
1847 | return system(self.var_expand(cmd, depth=2)) |
|
1854 | return system(self.var_expand(cmd, depth=2)) | |
1848 |
|
1855 | |||
1849 | def getoutput(self, cmd, split=True): |
|
1856 | def getoutput(self, cmd, split=True): | |
1850 | """Get output (possibly including stderr) from a subprocess. |
|
1857 | """Get output (possibly including stderr) from a subprocess. | |
1851 |
|
1858 | |||
1852 | Parameters |
|
1859 | Parameters | |
1853 | ---------- |
|
1860 | ---------- | |
1854 | cmd : str |
|
1861 | cmd : str | |
1855 | Command to execute (can not end in '&', as background processes are |
|
1862 | Command to execute (can not end in '&', as background processes are | |
1856 | not supported. |
|
1863 | not supported. | |
1857 | split : bool, optional |
|
1864 | split : bool, optional | |
1858 |
|
1865 | |||
1859 | If True, split the output into an IPython SList. Otherwise, an |
|
1866 | If True, split the output into an IPython SList. Otherwise, an | |
1860 | IPython LSString is returned. These are objects similar to normal |
|
1867 | IPython LSString is returned. These are objects similar to normal | |
1861 | lists and strings, with a few convenience attributes for easier |
|
1868 | lists and strings, with a few convenience attributes for easier | |
1862 | manipulation of line-based output. You can use '?' on them for |
|
1869 | manipulation of line-based output. You can use '?' on them for | |
1863 | details. |
|
1870 | details. | |
1864 | """ |
|
1871 | """ | |
1865 | if cmd.endswith('&'): |
|
1872 | if cmd.endswith('&'): | |
1866 | raise OSError("Background processes not supported.") |
|
1873 | raise OSError("Background processes not supported.") | |
1867 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1874 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1868 | if split: |
|
1875 | if split: | |
1869 | out = SList(out.splitlines()) |
|
1876 | out = SList(out.splitlines()) | |
1870 | else: |
|
1877 | else: | |
1871 | out = LSString(out) |
|
1878 | out = LSString(out) | |
1872 | return out |
|
1879 | return out | |
1873 |
|
1880 | |||
1874 | #------------------------------------------------------------------------- |
|
1881 | #------------------------------------------------------------------------- | |
1875 | # Things related to aliases |
|
1882 | # Things related to aliases | |
1876 | #------------------------------------------------------------------------- |
|
1883 | #------------------------------------------------------------------------- | |
1877 |
|
1884 | |||
1878 | def init_alias(self): |
|
1885 | def init_alias(self): | |
1879 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1886 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1880 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1887 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1881 |
|
1888 | |||
1882 | #------------------------------------------------------------------------- |
|
1889 | #------------------------------------------------------------------------- | |
1883 | # Things related to extensions and plugins |
|
1890 | # Things related to extensions and plugins | |
1884 | #------------------------------------------------------------------------- |
|
1891 | #------------------------------------------------------------------------- | |
1885 |
|
1892 | |||
1886 | def init_extension_manager(self): |
|
1893 | def init_extension_manager(self): | |
1887 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1894 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1888 |
|
1895 | |||
1889 | def init_plugin_manager(self): |
|
1896 | def init_plugin_manager(self): | |
1890 | self.plugin_manager = PluginManager(config=self.config) |
|
1897 | self.plugin_manager = PluginManager(config=self.config) | |
1891 |
|
1898 | |||
1892 | #------------------------------------------------------------------------- |
|
1899 | #------------------------------------------------------------------------- | |
1893 | # Things related to payloads |
|
1900 | # Things related to payloads | |
1894 | #------------------------------------------------------------------------- |
|
1901 | #------------------------------------------------------------------------- | |
1895 |
|
1902 | |||
1896 | def init_payload(self): |
|
1903 | def init_payload(self): | |
1897 | self.payload_manager = PayloadManager(config=self.config) |
|
1904 | self.payload_manager = PayloadManager(config=self.config) | |
1898 |
|
1905 | |||
1899 | #------------------------------------------------------------------------- |
|
1906 | #------------------------------------------------------------------------- | |
1900 | # Things related to the prefilter |
|
1907 | # Things related to the prefilter | |
1901 | #------------------------------------------------------------------------- |
|
1908 | #------------------------------------------------------------------------- | |
1902 |
|
1909 | |||
1903 | def init_prefilter(self): |
|
1910 | def init_prefilter(self): | |
1904 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1911 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1905 | # Ultimately this will be refactored in the new interpreter code, but |
|
1912 | # Ultimately this will be refactored in the new interpreter code, but | |
1906 | # for now, we should expose the main prefilter method (there's legacy |
|
1913 | # for now, we should expose the main prefilter method (there's legacy | |
1907 | # code out there that may rely on this). |
|
1914 | # code out there that may rely on this). | |
1908 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1915 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1909 |
|
1916 | |||
1910 | def auto_rewrite_input(self, cmd): |
|
1917 | def auto_rewrite_input(self, cmd): | |
1911 | """Print to the screen the rewritten form of the user's command. |
|
1918 | """Print to the screen the rewritten form of the user's command. | |
1912 |
|
1919 | |||
1913 | This shows visual feedback by rewriting input lines that cause |
|
1920 | This shows visual feedback by rewriting input lines that cause | |
1914 | automatic calling to kick in, like:: |
|
1921 | automatic calling to kick in, like:: | |
1915 |
|
1922 | |||
1916 | /f x |
|
1923 | /f x | |
1917 |
|
1924 | |||
1918 | into:: |
|
1925 | into:: | |
1919 |
|
1926 | |||
1920 | ------> f(x) |
|
1927 | ------> f(x) | |
1921 |
|
1928 | |||
1922 | after the user's input prompt. This helps the user understand that the |
|
1929 | after the user's input prompt. This helps the user understand that the | |
1923 | input line was transformed automatically by IPython. |
|
1930 | input line was transformed automatically by IPython. | |
1924 | """ |
|
1931 | """ | |
1925 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1932 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1926 |
|
1933 | |||
1927 | try: |
|
1934 | try: | |
1928 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1935 | # plain ascii works better w/ pyreadline, on some machines, so | |
1929 | # we use it and only print uncolored rewrite if we have unicode |
|
1936 | # we use it and only print uncolored rewrite if we have unicode | |
1930 | rw = str(rw) |
|
1937 | rw = str(rw) | |
1931 | print >> IPython.utils.io.Term.cout, rw |
|
1938 | print >> IPython.utils.io.Term.cout, rw | |
1932 | except UnicodeEncodeError: |
|
1939 | except UnicodeEncodeError: | |
1933 | print "------> " + cmd |
|
1940 | print "------> " + cmd | |
1934 |
|
1941 | |||
1935 | #------------------------------------------------------------------------- |
|
1942 | #------------------------------------------------------------------------- | |
1936 | # Things related to extracting values/expressions from kernel and user_ns |
|
1943 | # Things related to extracting values/expressions from kernel and user_ns | |
1937 | #------------------------------------------------------------------------- |
|
1944 | #------------------------------------------------------------------------- | |
1938 |
|
1945 | |||
1939 | def _simple_error(self): |
|
1946 | def _simple_error(self): | |
1940 | etype, value = sys.exc_info()[:2] |
|
1947 | etype, value = sys.exc_info()[:2] | |
1941 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1948 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1942 |
|
1949 | |||
1943 | def user_variables(self, names): |
|
1950 | def user_variables(self, names): | |
1944 | """Get a list of variable names from the user's namespace. |
|
1951 | """Get a list of variable names from the user's namespace. | |
1945 |
|
1952 | |||
1946 | Parameters |
|
1953 | Parameters | |
1947 | ---------- |
|
1954 | ---------- | |
1948 | names : list of strings |
|
1955 | names : list of strings | |
1949 | A list of names of variables to be read from the user namespace. |
|
1956 | A list of names of variables to be read from the user namespace. | |
1950 |
|
1957 | |||
1951 | Returns |
|
1958 | Returns | |
1952 | ------- |
|
1959 | ------- | |
1953 | A dict, keyed by the input names and with the repr() of each value. |
|
1960 | A dict, keyed by the input names and with the repr() of each value. | |
1954 | """ |
|
1961 | """ | |
1955 | out = {} |
|
1962 | out = {} | |
1956 | user_ns = self.user_ns |
|
1963 | user_ns = self.user_ns | |
1957 | for varname in names: |
|
1964 | for varname in names: | |
1958 | try: |
|
1965 | try: | |
1959 | value = repr(user_ns[varname]) |
|
1966 | value = repr(user_ns[varname]) | |
1960 | except: |
|
1967 | except: | |
1961 | value = self._simple_error() |
|
1968 | value = self._simple_error() | |
1962 | out[varname] = value |
|
1969 | out[varname] = value | |
1963 | return out |
|
1970 | return out | |
1964 |
|
1971 | |||
1965 | def user_expressions(self, expressions): |
|
1972 | def user_expressions(self, expressions): | |
1966 | """Evaluate a dict of expressions in the user's namespace. |
|
1973 | """Evaluate a dict of expressions in the user's namespace. | |
1967 |
|
1974 | |||
1968 | Parameters |
|
1975 | Parameters | |
1969 | ---------- |
|
1976 | ---------- | |
1970 | expressions : dict |
|
1977 | expressions : dict | |
1971 | A dict with string keys and string values. The expression values |
|
1978 | A dict with string keys and string values. The expression values | |
1972 | should be valid Python expressions, each of which will be evaluated |
|
1979 | should be valid Python expressions, each of which will be evaluated | |
1973 | in the user namespace. |
|
1980 | in the user namespace. | |
1974 |
|
1981 | |||
1975 | Returns |
|
1982 | Returns | |
1976 | ------- |
|
1983 | ------- | |
1977 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1984 | A dict, keyed like the input expressions dict, with the repr() of each | |
1978 | value. |
|
1985 | value. | |
1979 | """ |
|
1986 | """ | |
1980 | out = {} |
|
1987 | out = {} | |
1981 | user_ns = self.user_ns |
|
1988 | user_ns = self.user_ns | |
1982 | global_ns = self.user_global_ns |
|
1989 | global_ns = self.user_global_ns | |
1983 | for key, expr in expressions.iteritems(): |
|
1990 | for key, expr in expressions.iteritems(): | |
1984 | try: |
|
1991 | try: | |
1985 | value = repr(eval(expr, global_ns, user_ns)) |
|
1992 | value = repr(eval(expr, global_ns, user_ns)) | |
1986 | except: |
|
1993 | except: | |
1987 | value = self._simple_error() |
|
1994 | value = self._simple_error() | |
1988 | out[key] = value |
|
1995 | out[key] = value | |
1989 | return out |
|
1996 | return out | |
1990 |
|
1997 | |||
1991 | #------------------------------------------------------------------------- |
|
1998 | #------------------------------------------------------------------------- | |
1992 | # Things related to the running of code |
|
1999 | # Things related to the running of code | |
1993 | #------------------------------------------------------------------------- |
|
2000 | #------------------------------------------------------------------------- | |
1994 |
|
2001 | |||
1995 | def ex(self, cmd): |
|
2002 | def ex(self, cmd): | |
1996 | """Execute a normal python statement in user namespace.""" |
|
2003 | """Execute a normal python statement in user namespace.""" | |
1997 | with nested(self.builtin_trap,): |
|
2004 | with nested(self.builtin_trap,): | |
1998 | exec cmd in self.user_global_ns, self.user_ns |
|
2005 | exec cmd in self.user_global_ns, self.user_ns | |
1999 |
|
2006 | |||
2000 | def ev(self, expr): |
|
2007 | def ev(self, expr): | |
2001 | """Evaluate python expression expr in user namespace. |
|
2008 | """Evaluate python expression expr in user namespace. | |
2002 |
|
2009 | |||
2003 | Returns the result of evaluation |
|
2010 | Returns the result of evaluation | |
2004 | """ |
|
2011 | """ | |
2005 | with nested(self.builtin_trap,): |
|
2012 | with nested(self.builtin_trap,): | |
2006 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2013 | return eval(expr, self.user_global_ns, self.user_ns) | |
2007 |
|
2014 | |||
2008 | def safe_execfile(self, fname, *where, **kw): |
|
2015 | def safe_execfile(self, fname, *where, **kw): | |
2009 | """A safe version of the builtin execfile(). |
|
2016 | """A safe version of the builtin execfile(). | |
2010 |
|
2017 | |||
2011 | This version will never throw an exception, but instead print |
|
2018 | This version will never throw an exception, but instead print | |
2012 | helpful error messages to the screen. This only works on pure |
|
2019 | helpful error messages to the screen. This only works on pure | |
2013 | Python files with the .py extension. |
|
2020 | Python files with the .py extension. | |
2014 |
|
2021 | |||
2015 | Parameters |
|
2022 | Parameters | |
2016 | ---------- |
|
2023 | ---------- | |
2017 | fname : string |
|
2024 | fname : string | |
2018 | The name of the file to be executed. |
|
2025 | The name of the file to be executed. | |
2019 | where : tuple |
|
2026 | where : tuple | |
2020 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2027 | One or two namespaces, passed to execfile() as (globals,locals). | |
2021 | If only one is given, it is passed as both. |
|
2028 | If only one is given, it is passed as both. | |
2022 | exit_ignore : bool (False) |
|
2029 | exit_ignore : bool (False) | |
2023 | If True, then silence SystemExit for non-zero status (it is always |
|
2030 | If True, then silence SystemExit for non-zero status (it is always | |
2024 | silenced for zero status, as it is so common). |
|
2031 | silenced for zero status, as it is so common). | |
2025 | """ |
|
2032 | """ | |
2026 | kw.setdefault('exit_ignore', False) |
|
2033 | kw.setdefault('exit_ignore', False) | |
2027 |
|
2034 | |||
2028 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2035 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2029 | # Make sure we have a .py file |
|
2036 | # Make sure we have a .py file | |
2030 | if not fname.endswith('.py'): |
|
2037 | if not fname.endswith('.py'): | |
2031 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2038 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2032 |
|
2039 | |||
2033 | # Make sure we can open the file |
|
2040 | # Make sure we can open the file | |
2034 | try: |
|
2041 | try: | |
2035 | with open(fname) as thefile: |
|
2042 | with open(fname) as thefile: | |
2036 | pass |
|
2043 | pass | |
2037 | except: |
|
2044 | except: | |
2038 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2045 | warn('Could not open file <%s> for safe execution.' % fname) | |
2039 | return |
|
2046 | return | |
2040 |
|
2047 | |||
2041 | # Find things also in current directory. This is needed to mimic the |
|
2048 | # Find things also in current directory. This is needed to mimic the | |
2042 | # behavior of running a script from the system command line, where |
|
2049 | # behavior of running a script from the system command line, where | |
2043 | # Python inserts the script's directory into sys.path |
|
2050 | # Python inserts the script's directory into sys.path | |
2044 | dname = os.path.dirname(fname) |
|
2051 | dname = os.path.dirname(fname) | |
2045 |
|
2052 | |||
2046 | if isinstance(fname, unicode): |
|
2053 | if isinstance(fname, unicode): | |
2047 | # execfile uses default encoding instead of filesystem encoding |
|
2054 | # execfile uses default encoding instead of filesystem encoding | |
2048 | # so unicode filenames will fail |
|
2055 | # so unicode filenames will fail | |
2049 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) |
|
2056 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) | |
2050 |
|
2057 | |||
2051 | with prepended_to_syspath(dname): |
|
2058 | with prepended_to_syspath(dname): | |
2052 | try: |
|
2059 | try: | |
2053 | execfile(fname,*where) |
|
2060 | execfile(fname,*where) | |
2054 | except SystemExit, status: |
|
2061 | except SystemExit, status: | |
2055 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2062 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2056 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2063 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2057 | # these are considered normal by the OS: |
|
2064 | # these are considered normal by the OS: | |
2058 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2065 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2059 | # 0 |
|
2066 | # 0 | |
2060 | # > python -c'import sys;sys.exit()'; echo $? |
|
2067 | # > python -c'import sys;sys.exit()'; echo $? | |
2061 | # 0 |
|
2068 | # 0 | |
2062 | # For other exit status, we show the exception unless |
|
2069 | # For other exit status, we show the exception unless | |
2063 | # explicitly silenced, but only in short form. |
|
2070 | # explicitly silenced, but only in short form. | |
2064 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2071 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2065 | self.showtraceback(exception_only=True) |
|
2072 | self.showtraceback(exception_only=True) | |
2066 | except: |
|
2073 | except: | |
2067 | self.showtraceback() |
|
2074 | self.showtraceback() | |
2068 |
|
2075 | |||
2069 | def safe_execfile_ipy(self, fname): |
|
2076 | def safe_execfile_ipy(self, fname): | |
2070 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2077 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2071 |
|
2078 | |||
2072 | Parameters |
|
2079 | Parameters | |
2073 | ---------- |
|
2080 | ---------- | |
2074 | fname : str |
|
2081 | fname : str | |
2075 | The name of the file to execute. The filename must have a |
|
2082 | The name of the file to execute. The filename must have a | |
2076 | .ipy extension. |
|
2083 | .ipy extension. | |
2077 | """ |
|
2084 | """ | |
2078 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2085 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2079 |
|
2086 | |||
2080 | # Make sure we have a .py file |
|
2087 | # Make sure we have a .py file | |
2081 | if not fname.endswith('.ipy'): |
|
2088 | if not fname.endswith('.ipy'): | |
2082 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2089 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2083 |
|
2090 | |||
2084 | # Make sure we can open the file |
|
2091 | # Make sure we can open the file | |
2085 | try: |
|
2092 | try: | |
2086 | with open(fname) as thefile: |
|
2093 | with open(fname) as thefile: | |
2087 | pass |
|
2094 | pass | |
2088 | except: |
|
2095 | except: | |
2089 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2096 | warn('Could not open file <%s> for safe execution.' % fname) | |
2090 | return |
|
2097 | return | |
2091 |
|
2098 | |||
2092 | # Find things also in current directory. This is needed to mimic the |
|
2099 | # Find things also in current directory. This is needed to mimic the | |
2093 | # behavior of running a script from the system command line, where |
|
2100 | # behavior of running a script from the system command line, where | |
2094 | # Python inserts the script's directory into sys.path |
|
2101 | # Python inserts the script's directory into sys.path | |
2095 | dname = os.path.dirname(fname) |
|
2102 | dname = os.path.dirname(fname) | |
2096 |
|
2103 | |||
2097 | with prepended_to_syspath(dname): |
|
2104 | with prepended_to_syspath(dname): | |
2098 | try: |
|
2105 | try: | |
2099 | with open(fname) as thefile: |
|
2106 | with open(fname) as thefile: | |
2100 | # self.run_cell currently captures all exceptions |
|
2107 | # self.run_cell currently captures all exceptions | |
2101 | # raised in user code. It would be nice if there were |
|
2108 | # raised in user code. It would be nice if there were | |
2102 | # versions of runlines, execfile that did raise, so |
|
2109 | # versions of runlines, execfile that did raise, so | |
2103 | # we could catch the errors. |
|
2110 | # we could catch the errors. | |
2104 | self.run_cell(thefile.read(), store_history=False) |
|
2111 | self.run_cell(thefile.read(), store_history=False) | |
2105 | except: |
|
2112 | except: | |
2106 | self.showtraceback() |
|
2113 | self.showtraceback() | |
2107 | warn('Unknown failure executing file: <%s>' % fname) |
|
2114 | warn('Unknown failure executing file: <%s>' % fname) | |
2108 |
|
2115 | |||
2109 | def run_cell(self, raw_cell, store_history=True): |
|
2116 | def run_cell(self, raw_cell, store_history=True): | |
2110 | """Run a complete IPython cell. |
|
2117 | """Run a complete IPython cell. | |
2111 |
|
2118 | |||
2112 | Parameters |
|
2119 | Parameters | |
2113 | ---------- |
|
2120 | ---------- | |
2114 | raw_cell : str |
|
2121 | raw_cell : str | |
2115 | The code (including IPython code such as %magic functions) to run. |
|
2122 | The code (including IPython code such as %magic functions) to run. | |
2116 | store_history : bool |
|
2123 | store_history : bool | |
2117 | If True, the raw and translated cell will be stored in IPython's |
|
2124 | If True, the raw and translated cell will be stored in IPython's | |
2118 | history. For user code calling back into IPython's machinery, this |
|
2125 | history. For user code calling back into IPython's machinery, this | |
2119 | should be set to False. |
|
2126 | should be set to False. | |
2120 | """ |
|
2127 | """ | |
2121 | if (not raw_cell) or raw_cell.isspace(): |
|
2128 | if (not raw_cell) or raw_cell.isspace(): | |
2122 | return |
|
2129 | return | |
2123 |
|
2130 | |||
2124 | for line in raw_cell.splitlines(): |
|
2131 | for line in raw_cell.splitlines(): | |
2125 | self.input_splitter.push(line) |
|
2132 | self.input_splitter.push(line) | |
2126 | cell = self.input_splitter.source_reset() |
|
2133 | cell = self.input_splitter.source_reset() | |
2127 |
|
2134 | |||
2128 | with self.builtin_trap: |
|
2135 | with self.builtin_trap: | |
2129 | if len(cell.splitlines()) == 1: |
|
2136 | if len(cell.splitlines()) == 1: | |
2130 | cell = self.prefilter_manager.prefilter_lines(cell) |
|
2137 | cell = self.prefilter_manager.prefilter_lines(cell) | |
2131 |
|
2138 | |||
2132 | # Store raw and processed history |
|
2139 | # Store raw and processed history | |
2133 | if store_history: |
|
2140 | if store_history: | |
2134 | self.history_manager.store_inputs(self.execution_count, |
|
2141 | self.history_manager.store_inputs(self.execution_count, | |
2135 | cell, raw_cell) |
|
2142 | cell, raw_cell) | |
2136 |
|
2143 | |||
2137 | self.logger.log(cell, raw_cell) |
|
2144 | self.logger.log(cell, raw_cell) | |
2138 |
|
2145 | |||
2139 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2146 | cell_name = self.compile.cache(cell, self.execution_count) | |
2140 |
|
2147 | |||
2141 | with self.display_trap: |
|
2148 | with self.display_trap: | |
2142 | try: |
|
2149 | try: | |
2143 | code_ast = ast.parse(cell, filename=cell_name) |
|
2150 | code_ast = ast.parse(cell, filename=cell_name) | |
2144 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2151 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2145 | # Case 1 |
|
2152 | # Case 1 | |
2146 | self.showsyntaxerror() |
|
2153 | self.showsyntaxerror() | |
2147 | self.execution_count += 1 |
|
2154 | self.execution_count += 1 | |
2148 | return None |
|
2155 | return None | |
2149 |
|
2156 | |||
2150 | interactivity = 'last' # Last node to be run interactive |
|
2157 | interactivity = 'last' # Last node to be run interactive | |
2151 | if len(cell.splitlines()) == 1: |
|
2158 | if len(cell.splitlines()) == 1: | |
2152 | interactivity = 'all' # Single line; run fully interactive |
|
2159 | interactivity = 'all' # Single line; run fully interactive | |
2153 |
|
2160 | |||
2154 | self.run_ast_nodes(code_ast.body, cell_name, interactivity) |
|
2161 | self.run_ast_nodes(code_ast.body, cell_name, interactivity) | |
2155 |
|
2162 | |||
2156 | if store_history: |
|
2163 | if store_history: | |
2157 | # Write output to the database. Does nothing unless |
|
2164 | # Write output to the database. Does nothing unless | |
2158 | # history output logging is enabled. |
|
2165 | # history output logging is enabled. | |
2159 | self.history_manager.store_output(self.execution_count) |
|
2166 | self.history_manager.store_output(self.execution_count) | |
2160 | # Each cell is a *single* input, regardless of how many lines it has |
|
2167 | # Each cell is a *single* input, regardless of how many lines it has | |
2161 | self.execution_count += 1 |
|
2168 | self.execution_count += 1 | |
2162 |
|
2169 | |||
2163 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last'): |
|
2170 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last'): | |
2164 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2171 | """Run a sequence of AST nodes. The execution mode depends on the | |
2165 | interactivity parameter. |
|
2172 | interactivity parameter. | |
2166 |
|
2173 | |||
2167 | Parameters |
|
2174 | Parameters | |
2168 | ---------- |
|
2175 | ---------- | |
2169 | nodelist : list |
|
2176 | nodelist : list | |
2170 | A sequence of AST nodes to run. |
|
2177 | A sequence of AST nodes to run. | |
2171 | cell_name : str |
|
2178 | cell_name : str | |
2172 | Will be passed to the compiler as the filename of the cell. Typically |
|
2179 | Will be passed to the compiler as the filename of the cell. Typically | |
2173 | the value returned by ip.compile.cache(cell). |
|
2180 | the value returned by ip.compile.cache(cell). | |
2174 | interactivity : str |
|
2181 | interactivity : str | |
2175 | 'all', 'last' or 'none', specifying which nodes should be run |
|
2182 | 'all', 'last' or 'none', specifying which nodes should be run | |
2176 | interactively (displaying output from expressions). Other values for |
|
2183 | interactively (displaying output from expressions). Other values for | |
2177 | this parameter will raise a ValueError. |
|
2184 | this parameter will raise a ValueError. | |
2178 | """ |
|
2185 | """ | |
2179 | if not nodelist: |
|
2186 | if not nodelist: | |
2180 | return |
|
2187 | return | |
2181 |
|
2188 | |||
2182 | if interactivity == 'none': |
|
2189 | if interactivity == 'none': | |
2183 | to_run_exec, to_run_interactive = nodelist, [] |
|
2190 | to_run_exec, to_run_interactive = nodelist, [] | |
2184 | elif interactivity == 'last': |
|
2191 | elif interactivity == 'last': | |
2185 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2192 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2186 | elif interactivity == 'all': |
|
2193 | elif interactivity == 'all': | |
2187 | to_run_exec, to_run_interactive = [], nodelist |
|
2194 | to_run_exec, to_run_interactive = [], nodelist | |
2188 | else: |
|
2195 | else: | |
2189 | raise ValueError("Interactivity was %r" % interactivity) |
|
2196 | raise ValueError("Interactivity was %r" % interactivity) | |
2190 |
|
2197 | |||
2191 | exec_count = self.execution_count |
|
2198 | exec_count = self.execution_count | |
2192 | if to_run_exec: |
|
2199 | if to_run_exec: | |
2193 | mod = ast.Module(to_run_exec) |
|
2200 | mod = ast.Module(to_run_exec) | |
2194 | self.code_to_run = code = self.compile(mod, cell_name, "exec") |
|
2201 | self.code_to_run = code = self.compile(mod, cell_name, "exec") | |
2195 | if self.run_code(code) == 1: |
|
2202 | if self.run_code(code) == 1: | |
2196 | return |
|
2203 | return | |
2197 |
|
2204 | |||
2198 | if to_run_interactive: |
|
2205 | if to_run_interactive: | |
2199 | mod = ast.Interactive(to_run_interactive) |
|
2206 | mod = ast.Interactive(to_run_interactive) | |
2200 | self.code_to_run = code = self.compile(mod, cell_name, "single") |
|
2207 | self.code_to_run = code = self.compile(mod, cell_name, "single") | |
2201 | return self.run_code(code) |
|
2208 | return self.run_code(code) | |
2202 |
|
2209 | |||
2203 |
|
2210 | |||
2204 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2211 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2205 | # input logic has been 100% moved to frontends and is stable. |
|
2212 | # input logic has been 100% moved to frontends and is stable. | |
2206 | def runlines(self, lines, clean=False): |
|
2213 | def runlines(self, lines, clean=False): | |
2207 | """Run a string of one or more lines of source. |
|
2214 | """Run a string of one or more lines of source. | |
2208 |
|
2215 | |||
2209 | This method is capable of running a string containing multiple source |
|
2216 | This method is capable of running a string containing multiple source | |
2210 | lines, as if they had been entered at the IPython prompt. Since it |
|
2217 | lines, as if they had been entered at the IPython prompt. Since it | |
2211 | exposes IPython's processing machinery, the given strings can contain |
|
2218 | exposes IPython's processing machinery, the given strings can contain | |
2212 | magic calls (%magic), special shell access (!cmd), etc. |
|
2219 | magic calls (%magic), special shell access (!cmd), etc. | |
2213 | """ |
|
2220 | """ | |
2214 |
|
2221 | |||
2215 | if not isinstance(lines, (list, tuple)): |
|
2222 | if not isinstance(lines, (list, tuple)): | |
2216 | lines = lines.splitlines() |
|
2223 | lines = lines.splitlines() | |
2217 |
|
2224 | |||
2218 | if clean: |
|
2225 | if clean: | |
2219 | lines = self._cleanup_ipy_script(lines) |
|
2226 | lines = self._cleanup_ipy_script(lines) | |
2220 |
|
2227 | |||
2221 | # We must start with a clean buffer, in case this is run from an |
|
2228 | # We must start with a clean buffer, in case this is run from an | |
2222 | # interactive IPython session (via a magic, for example). |
|
2229 | # interactive IPython session (via a magic, for example). | |
2223 | self.reset_buffer() |
|
2230 | self.reset_buffer() | |
2224 |
|
2231 | |||
2225 | # Since we will prefilter all lines, store the user's raw input too |
|
2232 | # Since we will prefilter all lines, store the user's raw input too | |
2226 | # before we apply any transformations |
|
2233 | # before we apply any transformations | |
2227 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2234 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2228 |
|
2235 | |||
2229 | more = False |
|
2236 | more = False | |
2230 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2237 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2231 | with nested(self.builtin_trap, self.display_trap): |
|
2238 | with nested(self.builtin_trap, self.display_trap): | |
2232 | for line in lines: |
|
2239 | for line in lines: | |
2233 | # skip blank lines so we don't mess up the prompt counter, but |
|
2240 | # skip blank lines so we don't mess up the prompt counter, but | |
2234 | # do NOT skip even a blank line if we are in a code block (more |
|
2241 | # do NOT skip even a blank line if we are in a code block (more | |
2235 | # is true) |
|
2242 | # is true) | |
2236 |
|
2243 | |||
2237 | if line or more: |
|
2244 | if line or more: | |
2238 | more = self.push_line(prefilter_lines(line, more)) |
|
2245 | more = self.push_line(prefilter_lines(line, more)) | |
2239 | # IPython's run_source returns None if there was an error |
|
2246 | # IPython's run_source returns None if there was an error | |
2240 | # compiling the code. This allows us to stop processing |
|
2247 | # compiling the code. This allows us to stop processing | |
2241 | # right away, so the user gets the error message at the |
|
2248 | # right away, so the user gets the error message at the | |
2242 | # right place. |
|
2249 | # right place. | |
2243 | if more is None: |
|
2250 | if more is None: | |
2244 | break |
|
2251 | break | |
2245 | # final newline in case the input didn't have it, so that the code |
|
2252 | # final newline in case the input didn't have it, so that the code | |
2246 | # actually does get executed |
|
2253 | # actually does get executed | |
2247 | if more: |
|
2254 | if more: | |
2248 | self.push_line('\n') |
|
2255 | self.push_line('\n') | |
2249 |
|
2256 | |||
2250 | def run_source(self, source, filename=None, |
|
2257 | def run_source(self, source, filename=None, | |
2251 | symbol='single', post_execute=True): |
|
2258 | symbol='single', post_execute=True): | |
2252 | """Compile and run some source in the interpreter. |
|
2259 | """Compile and run some source in the interpreter. | |
2253 |
|
2260 | |||
2254 | Arguments are as for compile_command(). |
|
2261 | Arguments are as for compile_command(). | |
2255 |
|
2262 | |||
2256 | One several things can happen: |
|
2263 | One several things can happen: | |
2257 |
|
2264 | |||
2258 | 1) The input is incorrect; compile_command() raised an |
|
2265 | 1) The input is incorrect; compile_command() raised an | |
2259 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2266 | exception (SyntaxError or OverflowError). A syntax traceback | |
2260 | will be printed by calling the showsyntaxerror() method. |
|
2267 | will be printed by calling the showsyntaxerror() method. | |
2261 |
|
2268 | |||
2262 | 2) The input is incomplete, and more input is required; |
|
2269 | 2) The input is incomplete, and more input is required; | |
2263 | compile_command() returned None. Nothing happens. |
|
2270 | compile_command() returned None. Nothing happens. | |
2264 |
|
2271 | |||
2265 | 3) The input is complete; compile_command() returned a code |
|
2272 | 3) The input is complete; compile_command() returned a code | |
2266 | object. The code is executed by calling self.run_code() (which |
|
2273 | object. The code is executed by calling self.run_code() (which | |
2267 | also handles run-time exceptions, except for SystemExit). |
|
2274 | also handles run-time exceptions, except for SystemExit). | |
2268 |
|
2275 | |||
2269 | The return value is: |
|
2276 | The return value is: | |
2270 |
|
2277 | |||
2271 | - True in case 2 |
|
2278 | - True in case 2 | |
2272 |
|
2279 | |||
2273 | - False in the other cases, unless an exception is raised, where |
|
2280 | - False in the other cases, unless an exception is raised, where | |
2274 | None is returned instead. This can be used by external callers to |
|
2281 | None is returned instead. This can be used by external callers to | |
2275 | know whether to continue feeding input or not. |
|
2282 | know whether to continue feeding input or not. | |
2276 |
|
2283 | |||
2277 | The return value can be used to decide whether to use sys.ps1 or |
|
2284 | The return value can be used to decide whether to use sys.ps1 or | |
2278 | sys.ps2 to prompt the next line.""" |
|
2285 | sys.ps2 to prompt the next line.""" | |
2279 |
|
2286 | |||
2280 | # We need to ensure that the source is unicode from here on. |
|
2287 | # We need to ensure that the source is unicode from here on. | |
2281 | if type(source)==str: |
|
2288 | if type(source)==str: | |
2282 | usource = source.decode(self.stdin_encoding) |
|
2289 | usource = source.decode(self.stdin_encoding) | |
2283 | else: |
|
2290 | else: | |
2284 | usource = source |
|
2291 | usource = source | |
2285 |
|
2292 | |||
2286 | if False: # dbg |
|
2293 | if False: # dbg | |
2287 | print 'Source:', repr(source) # dbg |
|
2294 | print 'Source:', repr(source) # dbg | |
2288 | print 'USource:', repr(usource) # dbg |
|
2295 | print 'USource:', repr(usource) # dbg | |
2289 | print 'type:', type(source) # dbg |
|
2296 | print 'type:', type(source) # dbg | |
2290 | print 'encoding', self.stdin_encoding # dbg |
|
2297 | print 'encoding', self.stdin_encoding # dbg | |
2291 |
|
2298 | |||
2292 | try: |
|
2299 | try: | |
2293 | code_name = self.compile.cache(usource, self.execution_count) |
|
2300 | code_name = self.compile.cache(usource, self.execution_count) | |
2294 | code = self.compile(usource, code_name, symbol) |
|
2301 | code = self.compile(usource, code_name, symbol) | |
2295 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2302 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2296 | # Case 1 |
|
2303 | # Case 1 | |
2297 | self.showsyntaxerror(filename) |
|
2304 | self.showsyntaxerror(filename) | |
2298 | return None |
|
2305 | return None | |
2299 |
|
2306 | |||
2300 | if code is None: |
|
2307 | if code is None: | |
2301 | # Case 2 |
|
2308 | # Case 2 | |
2302 | return True |
|
2309 | return True | |
2303 |
|
2310 | |||
2304 | # Case 3 |
|
2311 | # Case 3 | |
2305 | # We store the code object so that threaded shells and |
|
2312 | # We store the code object so that threaded shells and | |
2306 | # custom exception handlers can access all this info if needed. |
|
2313 | # custom exception handlers can access all this info if needed. | |
2307 | # The source corresponding to this can be obtained from the |
|
2314 | # The source corresponding to this can be obtained from the | |
2308 | # buffer attribute as '\n'.join(self.buffer). |
|
2315 | # buffer attribute as '\n'.join(self.buffer). | |
2309 | self.code_to_run = code |
|
2316 | self.code_to_run = code | |
2310 | # now actually execute the code object |
|
2317 | # now actually execute the code object | |
2311 | if self.run_code(code, post_execute) == 0: |
|
2318 | if self.run_code(code, post_execute) == 0: | |
2312 | return False |
|
2319 | return False | |
2313 | else: |
|
2320 | else: | |
2314 | return None |
|
2321 | return None | |
2315 |
|
2322 | |||
2316 | # For backwards compatibility |
|
2323 | # For backwards compatibility | |
2317 | runsource = run_source |
|
2324 | runsource = run_source | |
2318 |
|
2325 | |||
2319 | def run_code(self, code_obj, post_execute=True): |
|
2326 | def run_code(self, code_obj, post_execute=True): | |
2320 | """Execute a code object. |
|
2327 | """Execute a code object. | |
2321 |
|
2328 | |||
2322 | When an exception occurs, self.showtraceback() is called to display a |
|
2329 | When an exception occurs, self.showtraceback() is called to display a | |
2323 | traceback. |
|
2330 | traceback. | |
2324 |
|
2331 | |||
2325 | Return value: a flag indicating whether the code to be run completed |
|
2332 | Return value: a flag indicating whether the code to be run completed | |
2326 | successfully: |
|
2333 | successfully: | |
2327 |
|
2334 | |||
2328 | - 0: successful execution. |
|
2335 | - 0: successful execution. | |
2329 | - 1: an error occurred. |
|
2336 | - 1: an error occurred. | |
2330 | """ |
|
2337 | """ | |
2331 |
|
2338 | |||
2332 | # Set our own excepthook in case the user code tries to call it |
|
2339 | # Set our own excepthook in case the user code tries to call it | |
2333 | # directly, so that the IPython crash handler doesn't get triggered |
|
2340 | # directly, so that the IPython crash handler doesn't get triggered | |
2334 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2341 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2335 |
|
2342 | |||
2336 | # we save the original sys.excepthook in the instance, in case config |
|
2343 | # we save the original sys.excepthook in the instance, in case config | |
2337 | # code (such as magics) needs access to it. |
|
2344 | # code (such as magics) needs access to it. | |
2338 | self.sys_excepthook = old_excepthook |
|
2345 | self.sys_excepthook = old_excepthook | |
2339 | outflag = 1 # happens in more places, so it's easier as default |
|
2346 | outflag = 1 # happens in more places, so it's easier as default | |
2340 | try: |
|
2347 | try: | |
2341 | try: |
|
2348 | try: | |
2342 | self.hooks.pre_run_code_hook() |
|
2349 | self.hooks.pre_run_code_hook() | |
2343 | #rprint('Running code', repr(code_obj)) # dbg |
|
2350 | #rprint('Running code', repr(code_obj)) # dbg | |
2344 | exec code_obj in self.user_global_ns, self.user_ns |
|
2351 | exec code_obj in self.user_global_ns, self.user_ns | |
2345 | finally: |
|
2352 | finally: | |
2346 | # Reset our crash handler in place |
|
2353 | # Reset our crash handler in place | |
2347 | sys.excepthook = old_excepthook |
|
2354 | sys.excepthook = old_excepthook | |
2348 | except SystemExit: |
|
2355 | except SystemExit: | |
2349 | self.reset_buffer() |
|
2356 | self.reset_buffer() | |
2350 | self.showtraceback(exception_only=True) |
|
2357 | self.showtraceback(exception_only=True) | |
2351 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2358 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2352 | except self.custom_exceptions: |
|
2359 | except self.custom_exceptions: | |
2353 | etype,value,tb = sys.exc_info() |
|
2360 | etype,value,tb = sys.exc_info() | |
2354 | self.CustomTB(etype,value,tb) |
|
2361 | self.CustomTB(etype,value,tb) | |
2355 | except: |
|
2362 | except: | |
2356 | self.showtraceback() |
|
2363 | self.showtraceback() | |
2357 | else: |
|
2364 | else: | |
2358 | outflag = 0 |
|
2365 | outflag = 0 | |
2359 | if softspace(sys.stdout, 0): |
|
2366 | if softspace(sys.stdout, 0): | |
2360 |
|
2367 | |||
2361 |
|
2368 | |||
2362 | # Execute any registered post-execution functions. Here, any errors |
|
2369 | # Execute any registered post-execution functions. Here, any errors | |
2363 | # are reported only minimally and just on the terminal, because the |
|
2370 | # are reported only minimally and just on the terminal, because the | |
2364 | # main exception channel may be occupied with a user traceback. |
|
2371 | # main exception channel may be occupied with a user traceback. | |
2365 | # FIXME: we need to think this mechanism a little more carefully. |
|
2372 | # FIXME: we need to think this mechanism a little more carefully. | |
2366 | if post_execute: |
|
2373 | if post_execute: | |
2367 | for func in self._post_execute: |
|
2374 | for func in self._post_execute: | |
2368 | try: |
|
2375 | try: | |
2369 | func() |
|
2376 | func() | |
2370 | except: |
|
2377 | except: | |
2371 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2378 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2372 | func |
|
2379 | func | |
2373 | print >> io.Term.cout, head |
|
2380 | print >> io.Term.cout, head | |
2374 | print >> io.Term.cout, self._simple_error() |
|
2381 | print >> io.Term.cout, self._simple_error() | |
2375 | print >> io.Term.cout, 'Removing from post_execute' |
|
2382 | print >> io.Term.cout, 'Removing from post_execute' | |
2376 | self._post_execute.remove(func) |
|
2383 | self._post_execute.remove(func) | |
2377 |
|
2384 | |||
2378 | # Flush out code object which has been run (and source) |
|
2385 | # Flush out code object which has been run (and source) | |
2379 | self.code_to_run = None |
|
2386 | self.code_to_run = None | |
2380 | return outflag |
|
2387 | return outflag | |
2381 |
|
2388 | |||
2382 | # For backwards compatibility |
|
2389 | # For backwards compatibility | |
2383 | runcode = run_code |
|
2390 | runcode = run_code | |
2384 |
|
2391 | |||
2385 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2392 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2386 | # input logic has been 100% moved to frontends and is stable. |
|
2393 | # input logic has been 100% moved to frontends and is stable. | |
2387 | def push_line(self, line): |
|
2394 | def push_line(self, line): | |
2388 | """Push a line to the interpreter. |
|
2395 | """Push a line to the interpreter. | |
2389 |
|
2396 | |||
2390 | The line should not have a trailing newline; it may have |
|
2397 | The line should not have a trailing newline; it may have | |
2391 | internal newlines. The line is appended to a buffer and the |
|
2398 | internal newlines. The line is appended to a buffer and the | |
2392 | interpreter's run_source() method is called with the |
|
2399 | interpreter's run_source() method is called with the | |
2393 | concatenated contents of the buffer as source. If this |
|
2400 | concatenated contents of the buffer as source. If this | |
2394 | indicates that the command was executed or invalid, the buffer |
|
2401 | indicates that the command was executed or invalid, the buffer | |
2395 | is reset; otherwise, the command is incomplete, and the buffer |
|
2402 | is reset; otherwise, the command is incomplete, and the buffer | |
2396 | is left as it was after the line was appended. The return |
|
2403 | is left as it was after the line was appended. The return | |
2397 | value is 1 if more input is required, 0 if the line was dealt |
|
2404 | value is 1 if more input is required, 0 if the line was dealt | |
2398 | with in some way (this is the same as run_source()). |
|
2405 | with in some way (this is the same as run_source()). | |
2399 | """ |
|
2406 | """ | |
2400 |
|
2407 | |||
2401 | # autoindent management should be done here, and not in the |
|
2408 | # autoindent management should be done here, and not in the | |
2402 | # interactive loop, since that one is only seen by keyboard input. We |
|
2409 | # interactive loop, since that one is only seen by keyboard input. We | |
2403 | # need this done correctly even for code run via runlines (which uses |
|
2410 | # need this done correctly even for code run via runlines (which uses | |
2404 | # push). |
|
2411 | # push). | |
2405 |
|
2412 | |||
2406 | #print 'push line: <%s>' % line # dbg |
|
2413 | #print 'push line: <%s>' % line # dbg | |
2407 | self.buffer.append(line) |
|
2414 | self.buffer.append(line) | |
2408 | full_source = '\n'.join(self.buffer) |
|
2415 | full_source = '\n'.join(self.buffer) | |
2409 | more = self.run_source(full_source, self.filename) |
|
2416 | more = self.run_source(full_source, self.filename) | |
2410 | if not more: |
|
2417 | if not more: | |
2411 | self.history_manager.store_inputs(self.execution_count, |
|
2418 | self.history_manager.store_inputs(self.execution_count, | |
2412 | '\n'.join(self.buffer_raw), full_source) |
|
2419 | '\n'.join(self.buffer_raw), full_source) | |
2413 | self.reset_buffer() |
|
2420 | self.reset_buffer() | |
2414 | self.execution_count += 1 |
|
2421 | self.execution_count += 1 | |
2415 | return more |
|
2422 | return more | |
2416 |
|
2423 | |||
2417 | def reset_buffer(self): |
|
2424 | def reset_buffer(self): | |
2418 | """Reset the input buffer.""" |
|
2425 | """Reset the input buffer.""" | |
2419 | self.buffer[:] = [] |
|
2426 | self.buffer[:] = [] | |
2420 | self.buffer_raw[:] = [] |
|
2427 | self.buffer_raw[:] = [] | |
2421 | self.input_splitter.reset() |
|
2428 | self.input_splitter.reset() | |
2422 |
|
2429 | |||
2423 | # For backwards compatibility |
|
2430 | # For backwards compatibility | |
2424 | resetbuffer = reset_buffer |
|
2431 | resetbuffer = reset_buffer | |
2425 |
|
2432 | |||
2426 | def _is_secondary_block_start(self, s): |
|
2433 | def _is_secondary_block_start(self, s): | |
2427 | if not s.endswith(':'): |
|
2434 | if not s.endswith(':'): | |
2428 | return False |
|
2435 | return False | |
2429 | if (s.startswith('elif') or |
|
2436 | if (s.startswith('elif') or | |
2430 | s.startswith('else') or |
|
2437 | s.startswith('else') or | |
2431 | s.startswith('except') or |
|
2438 | s.startswith('except') or | |
2432 | s.startswith('finally')): |
|
2439 | s.startswith('finally')): | |
2433 | return True |
|
2440 | return True | |
2434 |
|
2441 | |||
2435 | def _cleanup_ipy_script(self, script): |
|
2442 | def _cleanup_ipy_script(self, script): | |
2436 | """Make a script safe for self.runlines() |
|
2443 | """Make a script safe for self.runlines() | |
2437 |
|
2444 | |||
2438 | Currently, IPython is lines based, with blocks being detected by |
|
2445 | Currently, IPython is lines based, with blocks being detected by | |
2439 | empty lines. This is a problem for block based scripts that may |
|
2446 | empty lines. This is a problem for block based scripts that may | |
2440 | not have empty lines after blocks. This script adds those empty |
|
2447 | not have empty lines after blocks. This script adds those empty | |
2441 | lines to make scripts safe for running in the current line based |
|
2448 | lines to make scripts safe for running in the current line based | |
2442 | IPython. |
|
2449 | IPython. | |
2443 | """ |
|
2450 | """ | |
2444 | res = [] |
|
2451 | res = [] | |
2445 | lines = script.splitlines() |
|
2452 | lines = script.splitlines() | |
2446 | level = 0 |
|
2453 | level = 0 | |
2447 |
|
2454 | |||
2448 | for l in lines: |
|
2455 | for l in lines: | |
2449 | lstripped = l.lstrip() |
|
2456 | lstripped = l.lstrip() | |
2450 | stripped = l.strip() |
|
2457 | stripped = l.strip() | |
2451 | if not stripped: |
|
2458 | if not stripped: | |
2452 | continue |
|
2459 | continue | |
2453 | newlevel = len(l) - len(lstripped) |
|
2460 | newlevel = len(l) - len(lstripped) | |
2454 | if level > 0 and newlevel == 0 and \ |
|
2461 | if level > 0 and newlevel == 0 and \ | |
2455 | not self._is_secondary_block_start(stripped): |
|
2462 | not self._is_secondary_block_start(stripped): | |
2456 | # add empty line |
|
2463 | # add empty line | |
2457 | res.append('') |
|
2464 | res.append('') | |
2458 | res.append(l) |
|
2465 | res.append(l) | |
2459 | level = newlevel |
|
2466 | level = newlevel | |
2460 |
|
2467 | |||
2461 | return '\n'.join(res) + '\n' |
|
2468 | return '\n'.join(res) + '\n' | |
2462 |
|
2469 | |||
2463 | #------------------------------------------------------------------------- |
|
2470 | #------------------------------------------------------------------------- | |
2464 | # Things related to GUI support and pylab |
|
2471 | # Things related to GUI support and pylab | |
2465 | #------------------------------------------------------------------------- |
|
2472 | #------------------------------------------------------------------------- | |
2466 |
|
2473 | |||
2467 | def enable_pylab(self, gui=None): |
|
2474 | def enable_pylab(self, gui=None): | |
2468 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2475 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2469 |
|
2476 | |||
2470 | #------------------------------------------------------------------------- |
|
2477 | #------------------------------------------------------------------------- | |
2471 | # Utilities |
|
2478 | # Utilities | |
2472 | #------------------------------------------------------------------------- |
|
2479 | #------------------------------------------------------------------------- | |
2473 |
|
2480 | |||
2474 | def var_expand(self,cmd,depth=0): |
|
2481 | def var_expand(self,cmd,depth=0): | |
2475 | """Expand python variables in a string. |
|
2482 | """Expand python variables in a string. | |
2476 |
|
2483 | |||
2477 | The depth argument indicates how many frames above the caller should |
|
2484 | The depth argument indicates how many frames above the caller should | |
2478 | be walked to look for the local namespace where to expand variables. |
|
2485 | be walked to look for the local namespace where to expand variables. | |
2479 |
|
2486 | |||
2480 | The global namespace for expansion is always the user's interactive |
|
2487 | The global namespace for expansion is always the user's interactive | |
2481 | namespace. |
|
2488 | namespace. | |
2482 | """ |
|
2489 | """ | |
2483 | res = ItplNS(cmd, self.user_ns, # globals |
|
2490 | res = ItplNS(cmd, self.user_ns, # globals | |
2484 | # Skip our own frame in searching for locals: |
|
2491 | # Skip our own frame in searching for locals: | |
2485 | sys._getframe(depth+1).f_locals # locals |
|
2492 | sys._getframe(depth+1).f_locals # locals | |
2486 | ) |
|
2493 | ) | |
2487 | return str(res).decode(res.codec) |
|
2494 | return str(res).decode(res.codec) | |
2488 |
|
2495 | |||
2489 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2496 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2490 | """Make a new tempfile and return its filename. |
|
2497 | """Make a new tempfile and return its filename. | |
2491 |
|
2498 | |||
2492 | This makes a call to tempfile.mktemp, but it registers the created |
|
2499 | This makes a call to tempfile.mktemp, but it registers the created | |
2493 | filename internally so ipython cleans it up at exit time. |
|
2500 | filename internally so ipython cleans it up at exit time. | |
2494 |
|
2501 | |||
2495 | Optional inputs: |
|
2502 | Optional inputs: | |
2496 |
|
2503 | |||
2497 | - data(None): if data is given, it gets written out to the temp file |
|
2504 | - data(None): if data is given, it gets written out to the temp file | |
2498 | immediately, and the file is closed again.""" |
|
2505 | immediately, and the file is closed again.""" | |
2499 |
|
2506 | |||
2500 | filename = tempfile.mktemp('.py', prefix) |
|
2507 | filename = tempfile.mktemp('.py', prefix) | |
2501 | self.tempfiles.append(filename) |
|
2508 | self.tempfiles.append(filename) | |
2502 |
|
2509 | |||
2503 | if data: |
|
2510 | if data: | |
2504 | tmp_file = open(filename,'w') |
|
2511 | tmp_file = open(filename,'w') | |
2505 | tmp_file.write(data) |
|
2512 | tmp_file.write(data) | |
2506 | tmp_file.close() |
|
2513 | tmp_file.close() | |
2507 | return filename |
|
2514 | return filename | |
2508 |
|
2515 | |||
2509 | # TODO: This should be removed when Term is refactored. |
|
2516 | # TODO: This should be removed when Term is refactored. | |
2510 | def write(self,data): |
|
2517 | def write(self,data): | |
2511 | """Write a string to the default output""" |
|
2518 | """Write a string to the default output""" | |
2512 | io.Term.cout.write(data) |
|
2519 | io.Term.cout.write(data) | |
2513 |
|
2520 | |||
2514 | # TODO: This should be removed when Term is refactored. |
|
2521 | # TODO: This should be removed when Term is refactored. | |
2515 | def write_err(self,data): |
|
2522 | def write_err(self,data): | |
2516 | """Write a string to the default error output""" |
|
2523 | """Write a string to the default error output""" | |
2517 | io.Term.cerr.write(data) |
|
2524 | io.Term.cerr.write(data) | |
2518 |
|
2525 | |||
2519 | def ask_yes_no(self,prompt,default=True): |
|
2526 | def ask_yes_no(self,prompt,default=True): | |
2520 | if self.quiet: |
|
2527 | if self.quiet: | |
2521 | return True |
|
2528 | return True | |
2522 | return ask_yes_no(prompt,default) |
|
2529 | return ask_yes_no(prompt,default) | |
2523 |
|
2530 | |||
2524 | def show_usage(self): |
|
2531 | def show_usage(self): | |
2525 | """Show a usage message""" |
|
2532 | """Show a usage message""" | |
2526 | page.page(IPython.core.usage.interactive_usage) |
|
2533 | page.page(IPython.core.usage.interactive_usage) | |
2527 |
|
2534 | |||
2528 | def find_user_code(self, target, raw=True): |
|
2535 | def find_user_code(self, target, raw=True): | |
2529 | """Get a code string from history, file, or a string or macro. |
|
2536 | """Get a code string from history, file, or a string or macro. | |
2530 |
|
2537 | |||
2531 | This is mainly used by magic functions. |
|
2538 | This is mainly used by magic functions. | |
2532 |
|
2539 | |||
2533 | Parameters |
|
2540 | Parameters | |
2534 | ---------- |
|
2541 | ---------- | |
2535 | target : str |
|
2542 | target : str | |
2536 | A string specifying code to retrieve. This will be tried respectively |
|
2543 | A string specifying code to retrieve. This will be tried respectively | |
2537 | as: ranges of input history (see %history for syntax), a filename, or |
|
2544 | as: ranges of input history (see %history for syntax), a filename, or | |
2538 | an expression evaluating to a string or Macro in the user namespace. |
|
2545 | an expression evaluating to a string or Macro in the user namespace. | |
2539 | raw : bool |
|
2546 | raw : bool | |
2540 | If true (default), retrieve raw history. Has no effect on the other |
|
2547 | If true (default), retrieve raw history. Has no effect on the other | |
2541 | retrieval mechanisms. |
|
2548 | retrieval mechanisms. | |
2542 |
|
2549 | |||
2543 | Returns |
|
2550 | Returns | |
2544 | ------- |
|
2551 | ------- | |
2545 | A string of code. |
|
2552 | A string of code. | |
2546 |
|
2553 | |||
2547 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2554 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
2548 | to an object of another type. In each case, .args[0] is a printable |
|
2555 | to an object of another type. In each case, .args[0] is a printable | |
2549 | message. |
|
2556 | message. | |
2550 | """ |
|
2557 | """ | |
2551 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2558 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
2552 | if code: |
|
2559 | if code: | |
2553 | return code |
|
2560 | return code | |
2554 | if os.path.isfile(target): # Read file |
|
2561 | if os.path.isfile(target): # Read file | |
2555 | return open(target, "r").read() |
|
2562 | return open(target, "r").read() | |
2556 |
|
2563 | |||
2557 | try: # User namespace |
|
2564 | try: # User namespace | |
2558 | codeobj = eval(target, self.user_ns) |
|
2565 | codeobj = eval(target, self.user_ns) | |
2559 | except Exception: |
|
2566 | except Exception: | |
2560 | raise ValueError(("'%s' was not found in history, as a file, nor in" |
|
2567 | raise ValueError(("'%s' was not found in history, as a file, nor in" | |
2561 | " the user namespace.") % target) |
|
2568 | " the user namespace.") % target) | |
2562 | if isinstance(codeobj, basestring): |
|
2569 | if isinstance(codeobj, basestring): | |
2563 | return codeobj |
|
2570 | return codeobj | |
2564 | elif isinstance(codeobj, Macro): |
|
2571 | elif isinstance(codeobj, Macro): | |
2565 | return codeobj.value |
|
2572 | return codeobj.value | |
2566 |
|
2573 | |||
2567 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2574 | raise TypeError("%s is neither a string nor a macro." % target, | |
2568 | codeobj) |
|
2575 | codeobj) | |
2569 |
|
2576 | |||
2570 | #------------------------------------------------------------------------- |
|
2577 | #------------------------------------------------------------------------- | |
2571 | # Things related to IPython exiting |
|
2578 | # Things related to IPython exiting | |
2572 | #------------------------------------------------------------------------- |
|
2579 | #------------------------------------------------------------------------- | |
2573 | def atexit_operations(self): |
|
2580 | def atexit_operations(self): | |
2574 | """This will be executed at the time of exit. |
|
2581 | """This will be executed at the time of exit. | |
2575 |
|
2582 | |||
2576 | Cleanup operations and saving of persistent data that is done |
|
2583 | Cleanup operations and saving of persistent data that is done | |
2577 | unconditionally by IPython should be performed here. |
|
2584 | unconditionally by IPython should be performed here. | |
2578 |
|
2585 | |||
2579 | For things that may depend on startup flags or platform specifics (such |
|
2586 | For things that may depend on startup flags or platform specifics (such | |
2580 | as having readline or not), register a separate atexit function in the |
|
2587 | as having readline or not), register a separate atexit function in the | |
2581 | code that has the appropriate information, rather than trying to |
|
2588 | code that has the appropriate information, rather than trying to | |
2582 | clutter |
|
2589 | clutter | |
2583 | """ |
|
2590 | """ | |
2584 | # Cleanup all tempfiles left around |
|
2591 | # Cleanup all tempfiles left around | |
2585 | for tfile in self.tempfiles: |
|
2592 | for tfile in self.tempfiles: | |
2586 | try: |
|
2593 | try: | |
2587 | os.unlink(tfile) |
|
2594 | os.unlink(tfile) | |
2588 | except OSError: |
|
2595 | except OSError: | |
2589 | pass |
|
2596 | pass | |
2590 |
|
2597 | |||
2591 | # Close the history session (this stores the end time and line count) |
|
2598 | # Close the history session (this stores the end time and line count) | |
2592 | self.history_manager.end_session() |
|
2599 | self.history_manager.end_session() | |
2593 |
|
2600 | |||
2594 | # Clear all user namespaces to release all references cleanly. |
|
2601 | # Clear all user namespaces to release all references cleanly. | |
2595 | self.reset(new_session=False) |
|
2602 | self.reset(new_session=False) | |
2596 |
|
2603 | |||
2597 | # Run user hooks |
|
2604 | # Run user hooks | |
2598 | self.hooks.shutdown_hook() |
|
2605 | self.hooks.shutdown_hook() | |
2599 |
|
2606 | |||
2600 | def cleanup(self): |
|
2607 | def cleanup(self): | |
2601 | self.restore_sys_module_state() |
|
2608 | self.restore_sys_module_state() | |
2602 |
|
2609 | |||
2603 |
|
2610 | |||
2604 | class InteractiveShellABC(object): |
|
2611 | class InteractiveShellABC(object): | |
2605 | """An abstract base class for InteractiveShell.""" |
|
2612 | """An abstract base class for InteractiveShell.""" | |
2606 | __metaclass__ = abc.ABCMeta |
|
2613 | __metaclass__ = abc.ABCMeta | |
2607 |
|
2614 | |||
2608 | InteractiveShellABC.register(InteractiveShell) |
|
2615 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,3478 +1,3470 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 | from cStringIO import StringIO |
|
28 | from cStringIO import StringIO | |
29 | from getopt import getopt,GetoptError |
|
29 | from getopt import getopt,GetoptError | |
30 | from pprint import pformat |
|
30 | from pprint import pformat | |
31 | from xmlrpclib import ServerProxy |
|
31 | from xmlrpclib import ServerProxy | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | import IPython |
|
44 | import IPython | |
45 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
46 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.core.macro import Macro |
|
49 | from IPython.core.macro import Macro | |
50 | from IPython.core import page |
|
50 | from IPython.core import page | |
51 | from IPython.core.prefilter import ESC_MAGIC |
|
51 | from IPython.core.prefilter import ESC_MAGIC | |
52 | from IPython.lib.pylabtools import mpl_runner |
|
52 | from IPython.lib.pylabtools import mpl_runner | |
53 | from IPython.external.Itpl import itpl, printpl |
|
53 | from IPython.external.Itpl import itpl, printpl | |
54 | from IPython.testing import decorators as testdec |
|
54 | from IPython.testing import decorators as testdec | |
55 | from IPython.utils.io import file_read, nlprint |
|
55 | from IPython.utils.io import file_read, nlprint | |
56 | import IPython.utils.io |
|
56 | import IPython.utils.io | |
57 | from IPython.utils.path import get_py_filename |
|
57 | from IPython.utils.path import get_py_filename | |
58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
58 | from IPython.utils.process import arg_split, abbrev_cwd | |
59 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
60 | from IPython.utils.text import LSString, SList, format_screen |
|
60 | from IPython.utils.text import LSString, SList, format_screen | |
61 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
62 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
63 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
64 | import IPython.utils.generics |
|
64 | import IPython.utils.generics | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Utility functions |
|
67 | # Utility functions | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | def on_off(tag): |
|
70 | def on_off(tag): | |
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
72 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
73 |
|
73 | |||
74 | class Bunch: pass |
|
74 | class Bunch: pass | |
75 |
|
75 | |||
76 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
77 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
78 |
|
78 | |||
79 | newhead = [] |
|
79 | newhead = [] | |
80 | done = set() |
|
80 | done = set() | |
81 | for h in head: |
|
81 | for h in head: | |
82 | if h in done: |
|
82 | if h in done: | |
83 | continue |
|
83 | continue | |
84 | newhead.append(h) |
|
84 | newhead.append(h) | |
85 | done.add(h) |
|
85 | done.add(h) | |
86 |
|
86 | |||
87 | return newhead + tail |
|
87 | return newhead + tail | |
88 |
|
88 | |||
89 | def needs_local_scope(func): |
|
89 | def needs_local_scope(func): | |
90 | """Decorator to mark magic functions which need to local scope to run.""" |
|
90 | """Decorator to mark magic functions which need to local scope to run.""" | |
91 | func.needs_local_scope = True |
|
91 | func.needs_local_scope = True | |
92 | return func |
|
92 | return func | |
93 |
|
93 | |||
94 | #*************************************************************************** |
|
94 | #*************************************************************************** | |
95 | # Main class implementing Magic functionality |
|
95 | # Main class implementing Magic functionality | |
96 |
|
96 | |||
97 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
97 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
98 | # on construction of the main InteractiveShell object. Something odd is going |
|
98 | # on construction of the main InteractiveShell object. Something odd is going | |
99 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
99 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
100 | # eventually this needs to be clarified. |
|
100 | # eventually this needs to be clarified. | |
101 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
101 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
102 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
102 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
103 | # make Magic a configurable that InteractiveShell does not subclass. |
|
103 | # make Magic a configurable that InteractiveShell does not subclass. | |
104 |
|
104 | |||
105 | class Magic: |
|
105 | class Magic: | |
106 | """Magic functions for InteractiveShell. |
|
106 | """Magic functions for InteractiveShell. | |
107 |
|
107 | |||
108 | Shell functions which can be reached as %function_name. All magic |
|
108 | Shell functions which can be reached as %function_name. All magic | |
109 | functions should accept a string, which they can parse for their own |
|
109 | functions should accept a string, which they can parse for their own | |
110 | needs. This can make some functions easier to type, eg `%cd ../` |
|
110 | needs. This can make some functions easier to type, eg `%cd ../` | |
111 | vs. `%cd("../")` |
|
111 | vs. `%cd("../")` | |
112 |
|
112 | |||
113 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
113 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
114 | at the command line, but it is is needed in the definition. """ |
|
114 | at the command line, but it is is needed in the definition. """ | |
115 |
|
115 | |||
116 | # class globals |
|
116 | # class globals | |
117 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
117 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
118 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
118 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
119 |
|
119 | |||
120 | #...................................................................... |
|
120 | #...................................................................... | |
121 | # some utility functions |
|
121 | # some utility functions | |
122 |
|
122 | |||
123 | def __init__(self,shell): |
|
123 | def __init__(self,shell): | |
124 |
|
124 | |||
125 | self.options_table = {} |
|
125 | self.options_table = {} | |
126 | if profile is None: |
|
126 | if profile is None: | |
127 | self.magic_prun = self.profile_missing_notice |
|
127 | self.magic_prun = self.profile_missing_notice | |
128 | self.shell = shell |
|
128 | self.shell = shell | |
129 |
|
129 | |||
130 | # namespace for holding state we may need |
|
130 | # namespace for holding state we may need | |
131 | self._magic_state = Bunch() |
|
131 | self._magic_state = Bunch() | |
132 |
|
132 | |||
133 | def profile_missing_notice(self, *args, **kwargs): |
|
133 | def profile_missing_notice(self, *args, **kwargs): | |
134 | error("""\ |
|
134 | error("""\ | |
135 | The profile module could not be found. It has been removed from the standard |
|
135 | The profile module could not be found. It has been removed from the standard | |
136 | python packages because of its non-free license. To use profiling, install the |
|
136 | python packages because of its non-free license. To use profiling, install the | |
137 | python-profiler package from non-free.""") |
|
137 | python-profiler package from non-free.""") | |
138 |
|
138 | |||
139 | def default_option(self,fn,optstr): |
|
139 | def default_option(self,fn,optstr): | |
140 | """Make an entry in the options_table for fn, with value optstr""" |
|
140 | """Make an entry in the options_table for fn, with value optstr""" | |
141 |
|
141 | |||
142 | if fn not in self.lsmagic(): |
|
142 | if fn not in self.lsmagic(): | |
143 | error("%s is not a magic function" % fn) |
|
143 | error("%s is not a magic function" % fn) | |
144 | self.options_table[fn] = optstr |
|
144 | self.options_table[fn] = optstr | |
145 |
|
145 | |||
146 | def lsmagic(self): |
|
146 | def lsmagic(self): | |
147 | """Return a list of currently available magic functions. |
|
147 | """Return a list of currently available magic functions. | |
148 |
|
148 | |||
149 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
149 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
150 | ['magic_ls','magic_cd',...]""" |
|
150 | ['magic_ls','magic_cd',...]""" | |
151 |
|
151 | |||
152 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
152 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
153 |
|
153 | |||
154 | # magics in class definition |
|
154 | # magics in class definition | |
155 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
155 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
156 | callable(Magic.__dict__[fn]) |
|
156 | callable(Magic.__dict__[fn]) | |
157 | # in instance namespace (run-time user additions) |
|
157 | # in instance namespace (run-time user additions) | |
158 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
158 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
159 | callable(self.__dict__[fn]) |
|
159 | callable(self.__dict__[fn]) | |
160 | # and bound magics by user (so they can access self): |
|
160 | # and bound magics by user (so they can access self): | |
161 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
161 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
162 | callable(self.__class__.__dict__[fn]) |
|
162 | callable(self.__class__.__dict__[fn]) | |
163 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
163 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
164 | filter(inst_magic,self.__dict__.keys()) + \ |
|
164 | filter(inst_magic,self.__dict__.keys()) + \ | |
165 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
165 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
166 | out = [] |
|
166 | out = [] | |
167 | for fn in set(magics): |
|
167 | for fn in set(magics): | |
168 | out.append(fn.replace('magic_','',1)) |
|
168 | out.append(fn.replace('magic_','',1)) | |
169 | out.sort() |
|
169 | out.sort() | |
170 | return out |
|
170 | return out | |
171 |
|
171 | |||
172 | def extract_input_lines(self, range_str, raw=False): |
|
172 | def extract_input_lines(self, range_str, raw=False): | |
173 | """Return as a string a set of input history slices. |
|
173 | """Return as a string a set of input history slices. | |
174 |
|
174 | |||
175 | Inputs: |
|
175 | Inputs: | |
176 |
|
176 | |||
177 | - range_str: the set of slices is given as a string, like |
|
177 | - range_str: the set of slices is given as a string, like | |
178 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions |
|
178 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions | |
179 | which get their arguments as strings. The number before the / is the |
|
179 | which get their arguments as strings. The number before the / is the | |
180 | session number: ~n goes n back from the current session. |
|
180 | session number: ~n goes n back from the current session. | |
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 | lines = self.shell.history_manager.\ |
|
192 | lines = self.shell.history_manager.\ | |
193 | get_range_by_str(range_str, raw=raw) |
|
193 | get_range_by_str(range_str, raw=raw) | |
194 | return "\n".join(x for _, _, x in lines) |
|
194 | return "\n".join(x for _, _, x in lines) | |
195 |
|
195 | |||
196 | def arg_err(self,func): |
|
196 | def arg_err(self,func): | |
197 | """Print docstring if incorrect arguments were passed""" |
|
197 | """Print docstring if incorrect arguments were passed""" | |
198 | print 'Error in arguments:' |
|
198 | print 'Error in arguments:' | |
199 | print oinspect.getdoc(func) |
|
199 | print oinspect.getdoc(func) | |
200 |
|
200 | |||
201 | def format_latex(self,strng): |
|
201 | def format_latex(self,strng): | |
202 | """Format a string for latex inclusion.""" |
|
202 | """Format a string for latex inclusion.""" | |
203 |
|
203 | |||
204 | # Characters that need to be escaped for latex: |
|
204 | # Characters that need to be escaped for latex: | |
205 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
205 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
206 | # Magic command names as headers: |
|
206 | # Magic command names as headers: | |
207 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
207 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
208 | re.MULTILINE) |
|
208 | re.MULTILINE) | |
209 | # Magic commands |
|
209 | # Magic commands | |
210 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
210 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
211 | re.MULTILINE) |
|
211 | re.MULTILINE) | |
212 | # Paragraph continue |
|
212 | # Paragraph continue | |
213 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
213 | par_re = re.compile(r'\\$',re.MULTILINE) | |
214 |
|
214 | |||
215 | # The "\n" symbol |
|
215 | # The "\n" symbol | |
216 | newline_re = re.compile(r'\\n') |
|
216 | newline_re = re.compile(r'\\n') | |
217 |
|
217 | |||
218 | # Now build the string for output: |
|
218 | # Now build the string for output: | |
219 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
219 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
220 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
220 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
221 | strng) |
|
221 | strng) | |
222 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
222 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
223 | strng = par_re.sub(r'\\\\',strng) |
|
223 | strng = par_re.sub(r'\\\\',strng) | |
224 | strng = escape_re.sub(r'\\\1',strng) |
|
224 | strng = escape_re.sub(r'\\\1',strng) | |
225 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
225 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
226 | return strng |
|
226 | return strng | |
227 |
|
227 | |||
228 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
228 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
229 | """Parse options passed to an argument string. |
|
229 | """Parse options passed to an argument string. | |
230 |
|
230 | |||
231 | The interface is similar to that of getopt(), but it returns back a |
|
231 | The interface is similar to that of getopt(), but it returns back a | |
232 | Struct with the options as keys and the stripped argument string still |
|
232 | Struct with the options as keys and the stripped argument string still | |
233 | as a string. |
|
233 | as a string. | |
234 |
|
234 | |||
235 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
235 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
236 | This allows us to easily expand variables, glob files, quote |
|
236 | This allows us to easily expand variables, glob files, quote | |
237 | arguments, etc. |
|
237 | arguments, etc. | |
238 |
|
238 | |||
239 | Options: |
|
239 | Options: | |
240 | -mode: default 'string'. If given as 'list', the argument string is |
|
240 | -mode: default 'string'. If given as 'list', the argument string is | |
241 | returned as a list (split on whitespace) instead of a string. |
|
241 | returned as a list (split on whitespace) instead of a string. | |
242 |
|
242 | |||
243 | -list_all: put all option values in lists. Normally only options |
|
243 | -list_all: put all option values in lists. Normally only options | |
244 | appearing more than once are put in a list. |
|
244 | appearing more than once are put in a list. | |
245 |
|
245 | |||
246 | -posix (True): whether to split the input line in POSIX mode or not, |
|
246 | -posix (True): whether to split the input line in POSIX mode or not, | |
247 | as per the conventions outlined in the shlex module from the |
|
247 | as per the conventions outlined in the shlex module from the | |
248 | standard library.""" |
|
248 | standard library.""" | |
249 |
|
249 | |||
250 | # inject default options at the beginning of the input line |
|
250 | # inject default options at the beginning of the input line | |
251 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
251 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
252 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
252 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
253 |
|
253 | |||
254 | mode = kw.get('mode','string') |
|
254 | mode = kw.get('mode','string') | |
255 | if mode not in ['string','list']: |
|
255 | if mode not in ['string','list']: | |
256 | raise ValueError,'incorrect mode given: %s' % mode |
|
256 | raise ValueError,'incorrect mode given: %s' % mode | |
257 | # Get options |
|
257 | # Get options | |
258 | list_all = kw.get('list_all',0) |
|
258 | list_all = kw.get('list_all',0) | |
259 | posix = kw.get('posix', os.name == 'posix') |
|
259 | posix = kw.get('posix', os.name == 'posix') | |
260 |
|
260 | |||
261 | # Check if we have more than one argument to warrant extra processing: |
|
261 | # Check if we have more than one argument to warrant extra processing: | |
262 | odict = {} # Dictionary with options |
|
262 | odict = {} # Dictionary with options | |
263 | args = arg_str.split() |
|
263 | args = arg_str.split() | |
264 | if len(args) >= 1: |
|
264 | if len(args) >= 1: | |
265 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
265 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
266 | # need to look for options |
|
266 | # need to look for options | |
267 | argv = arg_split(arg_str,posix) |
|
267 | argv = arg_split(arg_str,posix) | |
268 | # Do regular option processing |
|
268 | # Do regular option processing | |
269 | try: |
|
269 | try: | |
270 | opts,args = getopt(argv,opt_str,*long_opts) |
|
270 | opts,args = getopt(argv,opt_str,*long_opts) | |
271 | except GetoptError,e: |
|
271 | except GetoptError,e: | |
272 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
272 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
273 | " ".join(long_opts))) |
|
273 | " ".join(long_opts))) | |
274 | for o,a in opts: |
|
274 | for o,a in opts: | |
275 | if o.startswith('--'): |
|
275 | if o.startswith('--'): | |
276 | o = o[2:] |
|
276 | o = o[2:] | |
277 | else: |
|
277 | else: | |
278 | o = o[1:] |
|
278 | o = o[1:] | |
279 | try: |
|
279 | try: | |
280 | odict[o].append(a) |
|
280 | odict[o].append(a) | |
281 | except AttributeError: |
|
281 | except AttributeError: | |
282 | odict[o] = [odict[o],a] |
|
282 | odict[o] = [odict[o],a] | |
283 | except KeyError: |
|
283 | except KeyError: | |
284 | if list_all: |
|
284 | if list_all: | |
285 | odict[o] = [a] |
|
285 | odict[o] = [a] | |
286 | else: |
|
286 | else: | |
287 | odict[o] = a |
|
287 | odict[o] = a | |
288 |
|
288 | |||
289 | # Prepare opts,args for return |
|
289 | # Prepare opts,args for return | |
290 | opts = Struct(odict) |
|
290 | opts = Struct(odict) | |
291 | if mode == 'string': |
|
291 | if mode == 'string': | |
292 | args = ' '.join(args) |
|
292 | args = ' '.join(args) | |
293 |
|
293 | |||
294 | return opts,args |
|
294 | return opts,args | |
295 |
|
295 | |||
296 | #...................................................................... |
|
296 | #...................................................................... | |
297 | # And now the actual magic functions |
|
297 | # And now the actual magic functions | |
298 |
|
298 | |||
299 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
299 | # Functions for IPython shell work (vars,funcs, config, etc) | |
300 | def magic_lsmagic(self, parameter_s = ''): |
|
300 | def magic_lsmagic(self, parameter_s = ''): | |
301 | """List currently available magic functions.""" |
|
301 | """List currently available magic functions.""" | |
302 | mesc = ESC_MAGIC |
|
302 | mesc = ESC_MAGIC | |
303 | print 'Available magic functions:\n'+mesc+\ |
|
303 | print 'Available magic functions:\n'+mesc+\ | |
304 | (' '+mesc).join(self.lsmagic()) |
|
304 | (' '+mesc).join(self.lsmagic()) | |
305 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
305 | print '\n' + Magic.auto_status[self.shell.automagic] | |
306 | return None |
|
306 | return None | |
307 |
|
307 | |||
308 | def magic_magic(self, parameter_s = ''): |
|
308 | def magic_magic(self, parameter_s = ''): | |
309 | """Print information about the magic function system. |
|
309 | """Print information about the magic function system. | |
310 |
|
310 | |||
311 | Supported formats: -latex, -brief, -rest |
|
311 | Supported formats: -latex, -brief, -rest | |
312 | """ |
|
312 | """ | |
313 |
|
313 | |||
314 | mode = '' |
|
314 | mode = '' | |
315 | try: |
|
315 | try: | |
316 | if parameter_s.split()[0] == '-latex': |
|
316 | if parameter_s.split()[0] == '-latex': | |
317 | mode = 'latex' |
|
317 | mode = 'latex' | |
318 | if parameter_s.split()[0] == '-brief': |
|
318 | if parameter_s.split()[0] == '-brief': | |
319 | mode = 'brief' |
|
319 | mode = 'brief' | |
320 | if parameter_s.split()[0] == '-rest': |
|
320 | if parameter_s.split()[0] == '-rest': | |
321 | mode = 'rest' |
|
321 | mode = 'rest' | |
322 | rest_docs = [] |
|
322 | rest_docs = [] | |
323 | except: |
|
323 | except: | |
324 | pass |
|
324 | pass | |
325 |
|
325 | |||
326 | magic_docs = [] |
|
326 | magic_docs = [] | |
327 | for fname in self.lsmagic(): |
|
327 | for fname in self.lsmagic(): | |
328 | mname = 'magic_' + fname |
|
328 | mname = 'magic_' + fname | |
329 | for space in (Magic,self,self.__class__): |
|
329 | for space in (Magic,self,self.__class__): | |
330 | try: |
|
330 | try: | |
331 | fn = space.__dict__[mname] |
|
331 | fn = space.__dict__[mname] | |
332 | except KeyError: |
|
332 | except KeyError: | |
333 | pass |
|
333 | pass | |
334 | else: |
|
334 | else: | |
335 | break |
|
335 | break | |
336 | if mode == 'brief': |
|
336 | if mode == 'brief': | |
337 | # only first line |
|
337 | # only first line | |
338 | if fn.__doc__: |
|
338 | if fn.__doc__: | |
339 | fndoc = fn.__doc__.split('\n',1)[0] |
|
339 | fndoc = fn.__doc__.split('\n',1)[0] | |
340 | else: |
|
340 | else: | |
341 | fndoc = 'No documentation' |
|
341 | fndoc = 'No documentation' | |
342 | else: |
|
342 | else: | |
343 | if fn.__doc__: |
|
343 | if fn.__doc__: | |
344 | fndoc = fn.__doc__.rstrip() |
|
344 | fndoc = fn.__doc__.rstrip() | |
345 | else: |
|
345 | else: | |
346 | fndoc = 'No documentation' |
|
346 | fndoc = 'No documentation' | |
347 |
|
347 | |||
348 |
|
348 | |||
349 | if mode == 'rest': |
|
349 | if mode == 'rest': | |
350 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
350 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
351 | fname,fndoc)) |
|
351 | fname,fndoc)) | |
352 |
|
352 | |||
353 | else: |
|
353 | else: | |
354 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
354 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
355 | fname,fndoc)) |
|
355 | fname,fndoc)) | |
356 |
|
356 | |||
357 | magic_docs = ''.join(magic_docs) |
|
357 | magic_docs = ''.join(magic_docs) | |
358 |
|
358 | |||
359 | if mode == 'rest': |
|
359 | if mode == 'rest': | |
360 | return "".join(rest_docs) |
|
360 | return "".join(rest_docs) | |
361 |
|
361 | |||
362 | if mode == 'latex': |
|
362 | if mode == 'latex': | |
363 | print self.format_latex(magic_docs) |
|
363 | print self.format_latex(magic_docs) | |
364 | return |
|
364 | return | |
365 | else: |
|
365 | else: | |
366 | magic_docs = format_screen(magic_docs) |
|
366 | magic_docs = format_screen(magic_docs) | |
367 | if mode == 'brief': |
|
367 | if mode == 'brief': | |
368 | return magic_docs |
|
368 | return magic_docs | |
369 |
|
369 | |||
370 | outmsg = """ |
|
370 | outmsg = """ | |
371 | IPython's 'magic' functions |
|
371 | IPython's 'magic' functions | |
372 | =========================== |
|
372 | =========================== | |
373 |
|
373 | |||
374 | The magic function system provides a series of functions which allow you to |
|
374 | The magic function system provides a series of functions which allow you to | |
375 | control the behavior of IPython itself, plus a lot of system-type |
|
375 | control the behavior of IPython itself, plus a lot of system-type | |
376 | features. All these functions are prefixed with a % character, but parameters |
|
376 | features. All these functions are prefixed with a % character, but parameters | |
377 | are given without parentheses or quotes. |
|
377 | are given without parentheses or quotes. | |
378 |
|
378 | |||
379 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
379 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
380 | %automagic function), you don't need to type in the % explicitly. By default, |
|
380 | %automagic function), you don't need to type in the % explicitly. By default, | |
381 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
381 | IPython ships with automagic on, so you should only rarely need the % escape. | |
382 |
|
382 | |||
383 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
383 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
384 | to 'mydir', if it exists. |
|
384 | to 'mydir', if it exists. | |
385 |
|
385 | |||
386 | You can define your own magic functions to extend the system. See the supplied |
|
386 | You can define your own magic functions to extend the system. See the supplied | |
387 | ipythonrc and example-magic.py files for details (in your ipython |
|
387 | ipythonrc and example-magic.py files for details (in your ipython | |
388 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). |
|
388 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). | |
389 |
|
389 | |||
390 | You can also define your own aliased names for magic functions. In your |
|
390 | You can also define your own aliased names for magic functions. In your | |
391 | ipythonrc file, placing a line like: |
|
391 | ipythonrc file, placing a line like: | |
392 |
|
392 | |||
393 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
393 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
394 |
|
394 | |||
395 | will define %pf as a new name for %profile. |
|
395 | will define %pf as a new name for %profile. | |
396 |
|
396 | |||
397 | You can also call magics in code using the magic() function, which IPython |
|
397 | You can also call magics in code using the magic() function, which IPython | |
398 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
398 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
399 |
|
399 | |||
400 | For a list of the available magic functions, use %lsmagic. For a description |
|
400 | For a list of the available magic functions, use %lsmagic. For a description | |
401 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
401 | of any of them, type %magic_name?, e.g. '%cd?'. | |
402 |
|
402 | |||
403 | Currently the magic system has the following functions:\n""" |
|
403 | Currently the magic system has the following functions:\n""" | |
404 |
|
404 | |||
405 | mesc = ESC_MAGIC |
|
405 | mesc = ESC_MAGIC | |
406 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
406 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
407 | "\n\n%s%s\n\n%s" % (outmsg, |
|
407 | "\n\n%s%s\n\n%s" % (outmsg, | |
408 | magic_docs,mesc,mesc, |
|
408 | magic_docs,mesc,mesc, | |
409 | (' '+mesc).join(self.lsmagic()), |
|
409 | (' '+mesc).join(self.lsmagic()), | |
410 | Magic.auto_status[self.shell.automagic] ) ) |
|
410 | Magic.auto_status[self.shell.automagic] ) ) | |
411 | page.page(outmsg) |
|
411 | page.page(outmsg) | |
412 |
|
412 | |||
413 | def magic_automagic(self, parameter_s = ''): |
|
413 | def magic_automagic(self, parameter_s = ''): | |
414 | """Make magic functions callable without having to type the initial %. |
|
414 | """Make magic functions callable without having to type the initial %. | |
415 |
|
415 | |||
416 | Without argumentsl toggles on/off (when off, you must call it as |
|
416 | Without argumentsl toggles on/off (when off, you must call it as | |
417 | %automagic, of course). With arguments it sets the value, and you can |
|
417 | %automagic, of course). With arguments it sets the value, and you can | |
418 | use any of (case insensitive): |
|
418 | use any of (case insensitive): | |
419 |
|
419 | |||
420 | - on,1,True: to activate |
|
420 | - on,1,True: to activate | |
421 |
|
421 | |||
422 | - off,0,False: to deactivate. |
|
422 | - off,0,False: to deactivate. | |
423 |
|
423 | |||
424 | Note that magic functions have lowest priority, so if there's a |
|
424 | Note that magic functions have lowest priority, so if there's a | |
425 | variable whose name collides with that of a magic fn, automagic won't |
|
425 | variable whose name collides with that of a magic fn, automagic won't | |
426 | work for that function (you get the variable instead). However, if you |
|
426 | work for that function (you get the variable instead). However, if you | |
427 | delete the variable (del var), the previously shadowed magic function |
|
427 | delete the variable (del var), the previously shadowed magic function | |
428 | becomes visible to automagic again.""" |
|
428 | becomes visible to automagic again.""" | |
429 |
|
429 | |||
430 | arg = parameter_s.lower() |
|
430 | arg = parameter_s.lower() | |
431 | if parameter_s in ('on','1','true'): |
|
431 | if parameter_s in ('on','1','true'): | |
432 | self.shell.automagic = True |
|
432 | self.shell.automagic = True | |
433 | elif parameter_s in ('off','0','false'): |
|
433 | elif parameter_s in ('off','0','false'): | |
434 | self.shell.automagic = False |
|
434 | self.shell.automagic = False | |
435 | else: |
|
435 | else: | |
436 | self.shell.automagic = not self.shell.automagic |
|
436 | self.shell.automagic = not self.shell.automagic | |
437 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
437 | print '\n' + Magic.auto_status[self.shell.automagic] | |
438 |
|
438 | |||
439 | @testdec.skip_doctest |
|
439 | @testdec.skip_doctest | |
440 | def magic_autocall(self, parameter_s = ''): |
|
440 | def magic_autocall(self, parameter_s = ''): | |
441 | """Make functions callable without having to type parentheses. |
|
441 | """Make functions callable without having to type parentheses. | |
442 |
|
442 | |||
443 | Usage: |
|
443 | Usage: | |
444 |
|
444 | |||
445 | %autocall [mode] |
|
445 | %autocall [mode] | |
446 |
|
446 | |||
447 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
447 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
448 | value is toggled on and off (remembering the previous state). |
|
448 | value is toggled on and off (remembering the previous state). | |
449 |
|
449 | |||
450 | In more detail, these values mean: |
|
450 | In more detail, these values mean: | |
451 |
|
451 | |||
452 | 0 -> fully disabled |
|
452 | 0 -> fully disabled | |
453 |
|
453 | |||
454 | 1 -> active, but do not apply if there are no arguments on the line. |
|
454 | 1 -> active, but do not apply if there are no arguments on the line. | |
455 |
|
455 | |||
456 | In this mode, you get: |
|
456 | In this mode, you get: | |
457 |
|
457 | |||
458 | In [1]: callable |
|
458 | In [1]: callable | |
459 | Out[1]: <built-in function callable> |
|
459 | Out[1]: <built-in function callable> | |
460 |
|
460 | |||
461 | In [2]: callable 'hello' |
|
461 | In [2]: callable 'hello' | |
462 | ------> callable('hello') |
|
462 | ------> callable('hello') | |
463 | Out[2]: False |
|
463 | Out[2]: False | |
464 |
|
464 | |||
465 | 2 -> Active always. Even if no arguments are present, the callable |
|
465 | 2 -> Active always. Even if no arguments are present, the callable | |
466 | object is called: |
|
466 | object is called: | |
467 |
|
467 | |||
468 | In [2]: float |
|
468 | In [2]: float | |
469 | ------> float() |
|
469 | ------> float() | |
470 | Out[2]: 0.0 |
|
470 | Out[2]: 0.0 | |
471 |
|
471 | |||
472 | Note that even with autocall off, you can still use '/' at the start of |
|
472 | Note that even with autocall off, you can still use '/' at the start of | |
473 | a line to treat the first argument on the command line as a function |
|
473 | a line to treat the first argument on the command line as a function | |
474 | and add parentheses to it: |
|
474 | and add parentheses to it: | |
475 |
|
475 | |||
476 | In [8]: /str 43 |
|
476 | In [8]: /str 43 | |
477 | ------> str(43) |
|
477 | ------> str(43) | |
478 | Out[8]: '43' |
|
478 | Out[8]: '43' | |
479 |
|
479 | |||
480 | # all-random (note for auto-testing) |
|
480 | # all-random (note for auto-testing) | |
481 | """ |
|
481 | """ | |
482 |
|
482 | |||
483 | if parameter_s: |
|
483 | if parameter_s: | |
484 | arg = int(parameter_s) |
|
484 | arg = int(parameter_s) | |
485 | else: |
|
485 | else: | |
486 | arg = 'toggle' |
|
486 | arg = 'toggle' | |
487 |
|
487 | |||
488 | if not arg in (0,1,2,'toggle'): |
|
488 | if not arg in (0,1,2,'toggle'): | |
489 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
489 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
490 | return |
|
490 | return | |
491 |
|
491 | |||
492 | if arg in (0,1,2): |
|
492 | if arg in (0,1,2): | |
493 | self.shell.autocall = arg |
|
493 | self.shell.autocall = arg | |
494 | else: # toggle |
|
494 | else: # toggle | |
495 | if self.shell.autocall: |
|
495 | if self.shell.autocall: | |
496 | self._magic_state.autocall_save = self.shell.autocall |
|
496 | self._magic_state.autocall_save = self.shell.autocall | |
497 | self.shell.autocall = 0 |
|
497 | self.shell.autocall = 0 | |
498 | else: |
|
498 | else: | |
499 | try: |
|
499 | try: | |
500 | self.shell.autocall = self._magic_state.autocall_save |
|
500 | self.shell.autocall = self._magic_state.autocall_save | |
501 | except AttributeError: |
|
501 | except AttributeError: | |
502 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
502 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
503 |
|
503 | |||
504 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
504 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
505 |
|
505 | |||
506 |
|
506 | |||
507 | def magic_page(self, parameter_s=''): |
|
507 | def magic_page(self, parameter_s=''): | |
508 | """Pretty print the object and display it through a pager. |
|
508 | """Pretty print the object and display it through a pager. | |
509 |
|
509 | |||
510 | %page [options] OBJECT |
|
510 | %page [options] OBJECT | |
511 |
|
511 | |||
512 | If no object is given, use _ (last output). |
|
512 | If no object is given, use _ (last output). | |
513 |
|
513 | |||
514 | Options: |
|
514 | Options: | |
515 |
|
515 | |||
516 | -r: page str(object), don't pretty-print it.""" |
|
516 | -r: page str(object), don't pretty-print it.""" | |
517 |
|
517 | |||
518 | # After a function contributed by Olivier Aubert, slightly modified. |
|
518 | # After a function contributed by Olivier Aubert, slightly modified. | |
519 |
|
519 | |||
520 | # Process options/args |
|
520 | # Process options/args | |
521 | opts,args = self.parse_options(parameter_s,'r') |
|
521 | opts,args = self.parse_options(parameter_s,'r') | |
522 | raw = 'r' in opts |
|
522 | raw = 'r' in opts | |
523 |
|
523 | |||
524 | oname = args and args or '_' |
|
524 | oname = args and args or '_' | |
525 | info = self._ofind(oname) |
|
525 | info = self._ofind(oname) | |
526 | if info['found']: |
|
526 | if info['found']: | |
527 | txt = (raw and str or pformat)( info['obj'] ) |
|
527 | txt = (raw and str or pformat)( info['obj'] ) | |
528 | page.page(txt) |
|
528 | page.page(txt) | |
529 | else: |
|
529 | else: | |
530 | print 'Object `%s` not found' % oname |
|
530 | print 'Object `%s` not found' % oname | |
531 |
|
531 | |||
532 | def magic_profile(self, parameter_s=''): |
|
532 | def magic_profile(self, parameter_s=''): | |
533 | """Print your currently active IPython profile.""" |
|
533 | """Print your currently active IPython profile.""" | |
534 | if self.shell.profile: |
|
534 | if self.shell.profile: | |
535 | printpl('Current IPython profile: $self.shell.profile.') |
|
535 | printpl('Current IPython profile: $self.shell.profile.') | |
536 | else: |
|
536 | else: | |
537 | print 'No profile active.' |
|
537 | print 'No profile active.' | |
538 |
|
538 | |||
539 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
539 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
540 | """Provide detailed information about an object. |
|
540 | """Provide detailed information about an object. | |
541 |
|
541 | |||
542 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
542 | '%pinfo object' is just a synonym for object? or ?object.""" | |
543 |
|
543 | |||
544 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
544 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
545 |
|
545 | |||
546 |
|
546 | |||
547 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
547 | # detail_level: 0 -> obj? , 1 -> obj?? | |
548 | detail_level = 0 |
|
548 | detail_level = 0 | |
549 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
549 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
550 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
550 | # happen if the user types 'pinfo foo?' at the cmd line. | |
551 | pinfo,qmark1,oname,qmark2 = \ |
|
551 | pinfo,qmark1,oname,qmark2 = \ | |
552 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
552 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
553 | if pinfo or qmark1 or qmark2: |
|
553 | if pinfo or qmark1 or qmark2: | |
554 | detail_level = 1 |
|
554 | detail_level = 1 | |
555 | if "*" in oname: |
|
555 | if "*" in oname: | |
556 | self.magic_psearch(oname) |
|
556 | self.magic_psearch(oname) | |
557 | else: |
|
557 | else: | |
558 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
558 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
559 | namespaces=namespaces) |
|
559 | namespaces=namespaces) | |
560 |
|
560 | |||
561 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
561 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
562 | """Provide extra detailed information about an object. |
|
562 | """Provide extra detailed information about an object. | |
563 |
|
563 | |||
564 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
564 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
565 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
565 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
566 | namespaces=namespaces) |
|
566 | namespaces=namespaces) | |
567 |
|
567 | |||
568 | @testdec.skip_doctest |
|
568 | @testdec.skip_doctest | |
569 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
569 | def magic_pdef(self, parameter_s='', namespaces=None): | |
570 | """Print the definition header for any callable object. |
|
570 | """Print the definition header for any callable object. | |
571 |
|
571 | |||
572 | If the object is a class, print the constructor information. |
|
572 | If the object is a class, print the constructor information. | |
573 |
|
573 | |||
574 | Examples |
|
574 | Examples | |
575 | -------- |
|
575 | -------- | |
576 | :: |
|
576 | :: | |
577 |
|
577 | |||
578 | In [3]: %pdef urllib.urlopen |
|
578 | In [3]: %pdef urllib.urlopen | |
579 | urllib.urlopen(url, data=None, proxies=None) |
|
579 | urllib.urlopen(url, data=None, proxies=None) | |
580 | """ |
|
580 | """ | |
581 | self._inspect('pdef',parameter_s, namespaces) |
|
581 | self._inspect('pdef',parameter_s, namespaces) | |
582 |
|
582 | |||
583 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
583 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
584 | """Print the docstring for an object. |
|
584 | """Print the docstring for an object. | |
585 |
|
585 | |||
586 | If the given object is a class, it will print both the class and the |
|
586 | If the given object is a class, it will print both the class and the | |
587 | constructor docstrings.""" |
|
587 | constructor docstrings.""" | |
588 | self._inspect('pdoc',parameter_s, namespaces) |
|
588 | self._inspect('pdoc',parameter_s, namespaces) | |
589 |
|
589 | |||
590 | def magic_psource(self, parameter_s='', namespaces=None): |
|
590 | def magic_psource(self, parameter_s='', namespaces=None): | |
591 | """Print (or run through pager) the source code for an object.""" |
|
591 | """Print (or run through pager) the source code for an object.""" | |
592 | self._inspect('psource',parameter_s, namespaces) |
|
592 | self._inspect('psource',parameter_s, namespaces) | |
593 |
|
593 | |||
594 | def magic_pfile(self, parameter_s=''): |
|
594 | def magic_pfile(self, parameter_s=''): | |
595 | """Print (or run through pager) the file where an object is defined. |
|
595 | """Print (or run through pager) the file where an object is defined. | |
596 |
|
596 | |||
597 | The file opens at the line where the object definition begins. IPython |
|
597 | The file opens at the line where the object definition begins. IPython | |
598 | will honor the environment variable PAGER if set, and otherwise will |
|
598 | will honor the environment variable PAGER if set, and otherwise will | |
599 | do its best to print the file in a convenient form. |
|
599 | do its best to print the file in a convenient form. | |
600 |
|
600 | |||
601 | If the given argument is not an object currently defined, IPython will |
|
601 | If the given argument is not an object currently defined, IPython will | |
602 | try to interpret it as a filename (automatically adding a .py extension |
|
602 | try to interpret it as a filename (automatically adding a .py extension | |
603 | if needed). You can thus use %pfile as a syntax highlighting code |
|
603 | if needed). You can thus use %pfile as a syntax highlighting code | |
604 | viewer.""" |
|
604 | viewer.""" | |
605 |
|
605 | |||
606 | # first interpret argument as an object name |
|
606 | # first interpret argument as an object name | |
607 | out = self._inspect('pfile',parameter_s) |
|
607 | out = self._inspect('pfile',parameter_s) | |
608 | # if not, try the input as a filename |
|
608 | # if not, try the input as a filename | |
609 | if out == 'not found': |
|
609 | if out == 'not found': | |
610 | try: |
|
610 | try: | |
611 | filename = get_py_filename(parameter_s) |
|
611 | filename = get_py_filename(parameter_s) | |
612 | except IOError,msg: |
|
612 | except IOError,msg: | |
613 | print msg |
|
613 | print msg | |
614 | return |
|
614 | return | |
615 | page.page(self.shell.inspector.format(file(filename).read())) |
|
615 | page.page(self.shell.inspector.format(file(filename).read())) | |
616 |
|
616 | |||
617 | def magic_psearch(self, parameter_s=''): |
|
617 | def magic_psearch(self, parameter_s=''): | |
618 | """Search for object in namespaces by wildcard. |
|
618 | """Search for object in namespaces by wildcard. | |
619 |
|
619 | |||
620 | %psearch [options] PATTERN [OBJECT TYPE] |
|
620 | %psearch [options] PATTERN [OBJECT TYPE] | |
621 |
|
621 | |||
622 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
622 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
623 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
623 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
624 | rest of the command line must be unchanged (options come first), so |
|
624 | rest of the command line must be unchanged (options come first), so | |
625 | for example the following forms are equivalent |
|
625 | for example the following forms are equivalent | |
626 |
|
626 | |||
627 | %psearch -i a* function |
|
627 | %psearch -i a* function | |
628 | -i a* function? |
|
628 | -i a* function? | |
629 | ?-i a* function |
|
629 | ?-i a* function | |
630 |
|
630 | |||
631 | Arguments: |
|
631 | Arguments: | |
632 |
|
632 | |||
633 | PATTERN |
|
633 | PATTERN | |
634 |
|
634 | |||
635 | where PATTERN is a string containing * as a wildcard similar to its |
|
635 | where PATTERN is a string containing * as a wildcard similar to its | |
636 | use in a shell. The pattern is matched in all namespaces on the |
|
636 | use in a shell. The pattern is matched in all namespaces on the | |
637 | search path. By default objects starting with a single _ are not |
|
637 | search path. By default objects starting with a single _ are not | |
638 | matched, many IPython generated objects have a single |
|
638 | matched, many IPython generated objects have a single | |
639 | underscore. The default is case insensitive matching. Matching is |
|
639 | underscore. The default is case insensitive matching. Matching is | |
640 | also done on the attributes of objects and not only on the objects |
|
640 | also done on the attributes of objects and not only on the objects | |
641 | in a module. |
|
641 | in a module. | |
642 |
|
642 | |||
643 | [OBJECT TYPE] |
|
643 | [OBJECT TYPE] | |
644 |
|
644 | |||
645 | Is the name of a python type from the types module. The name is |
|
645 | Is the name of a python type from the types module. The name is | |
646 | given in lowercase without the ending type, ex. StringType is |
|
646 | given in lowercase without the ending type, ex. StringType is | |
647 | written string. By adding a type here only objects matching the |
|
647 | written string. By adding a type here only objects matching the | |
648 | given type are matched. Using all here makes the pattern match all |
|
648 | given type are matched. Using all here makes the pattern match all | |
649 | types (this is the default). |
|
649 | types (this is the default). | |
650 |
|
650 | |||
651 | Options: |
|
651 | Options: | |
652 |
|
652 | |||
653 | -a: makes the pattern match even objects whose names start with a |
|
653 | -a: makes the pattern match even objects whose names start with a | |
654 | single underscore. These names are normally ommitted from the |
|
654 | single underscore. These names are normally ommitted from the | |
655 | search. |
|
655 | search. | |
656 |
|
656 | |||
657 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
657 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
658 | these options is given, the default is read from your ipythonrc |
|
658 | these options is given, the default is read from your ipythonrc | |
659 | file. The option name which sets this value is |
|
659 | file. The option name which sets this value is | |
660 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
660 | 'wildcards_case_sensitive'. If this option is not specified in your | |
661 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
661 | ipythonrc file, IPython's internal default is to do a case sensitive | |
662 | search. |
|
662 | search. | |
663 |
|
663 | |||
664 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
664 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
665 | specifiy can be searched in any of the following namespaces: |
|
665 | specifiy can be searched in any of the following namespaces: | |
666 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
666 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
667 | 'builtin' and 'user' are the search defaults. Note that you should |
|
667 | 'builtin' and 'user' are the search defaults. Note that you should | |
668 | not use quotes when specifying namespaces. |
|
668 | not use quotes when specifying namespaces. | |
669 |
|
669 | |||
670 | 'Builtin' contains the python module builtin, 'user' contains all |
|
670 | 'Builtin' contains the python module builtin, 'user' contains all | |
671 | user data, 'alias' only contain the shell aliases and no python |
|
671 | user data, 'alias' only contain the shell aliases and no python | |
672 | objects, 'internal' contains objects used by IPython. The |
|
672 | objects, 'internal' contains objects used by IPython. The | |
673 | 'user_global' namespace is only used by embedded IPython instances, |
|
673 | 'user_global' namespace is only used by embedded IPython instances, | |
674 | and it contains module-level globals. You can add namespaces to the |
|
674 | and it contains module-level globals. You can add namespaces to the | |
675 | search with -s or exclude them with -e (these options can be given |
|
675 | search with -s or exclude them with -e (these options can be given | |
676 | more than once). |
|
676 | more than once). | |
677 |
|
677 | |||
678 | Examples: |
|
678 | Examples: | |
679 |
|
679 | |||
680 | %psearch a* -> objects beginning with an a |
|
680 | %psearch a* -> objects beginning with an a | |
681 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
681 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
682 | %psearch a* function -> all functions beginning with an a |
|
682 | %psearch a* function -> all functions beginning with an a | |
683 | %psearch re.e* -> objects beginning with an e in module re |
|
683 | %psearch re.e* -> objects beginning with an e in module re | |
684 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
684 | %psearch r*.e* -> objects that start with e in modules starting in r | |
685 | %psearch r*.* string -> all strings in modules beginning with r |
|
685 | %psearch r*.* string -> all strings in modules beginning with r | |
686 |
|
686 | |||
687 | Case sensitve search: |
|
687 | Case sensitve search: | |
688 |
|
688 | |||
689 | %psearch -c a* list all object beginning with lower case a |
|
689 | %psearch -c a* list all object beginning with lower case a | |
690 |
|
690 | |||
691 | Show objects beginning with a single _: |
|
691 | Show objects beginning with a single _: | |
692 |
|
692 | |||
693 | %psearch -a _* list objects beginning with a single underscore""" |
|
693 | %psearch -a _* list objects beginning with a single underscore""" | |
694 | try: |
|
694 | try: | |
695 | parameter_s = parameter_s.encode('ascii') |
|
695 | parameter_s = parameter_s.encode('ascii') | |
696 | except UnicodeEncodeError: |
|
696 | except UnicodeEncodeError: | |
697 | print 'Python identifiers can only contain ascii characters.' |
|
697 | print 'Python identifiers can only contain ascii characters.' | |
698 | return |
|
698 | return | |
699 |
|
699 | |||
700 | # default namespaces to be searched |
|
700 | # default namespaces to be searched | |
701 | def_search = ['user','builtin'] |
|
701 | def_search = ['user','builtin'] | |
702 |
|
702 | |||
703 | # Process options/args |
|
703 | # Process options/args | |
704 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
704 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
705 | opt = opts.get |
|
705 | opt = opts.get | |
706 | shell = self.shell |
|
706 | shell = self.shell | |
707 | psearch = shell.inspector.psearch |
|
707 | psearch = shell.inspector.psearch | |
708 |
|
708 | |||
709 | # select case options |
|
709 | # select case options | |
710 | if opts.has_key('i'): |
|
710 | if opts.has_key('i'): | |
711 | ignore_case = True |
|
711 | ignore_case = True | |
712 | elif opts.has_key('c'): |
|
712 | elif opts.has_key('c'): | |
713 | ignore_case = False |
|
713 | ignore_case = False | |
714 | else: |
|
714 | else: | |
715 | ignore_case = not shell.wildcards_case_sensitive |
|
715 | ignore_case = not shell.wildcards_case_sensitive | |
716 |
|
716 | |||
717 | # Build list of namespaces to search from user options |
|
717 | # Build list of namespaces to search from user options | |
718 | def_search.extend(opt('s',[])) |
|
718 | def_search.extend(opt('s',[])) | |
719 | ns_exclude = ns_exclude=opt('e',[]) |
|
719 | ns_exclude = ns_exclude=opt('e',[]) | |
720 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
720 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
721 |
|
721 | |||
722 | # Call the actual search |
|
722 | # Call the actual search | |
723 | try: |
|
723 | try: | |
724 | psearch(args,shell.ns_table,ns_search, |
|
724 | psearch(args,shell.ns_table,ns_search, | |
725 | show_all=opt('a'),ignore_case=ignore_case) |
|
725 | show_all=opt('a'),ignore_case=ignore_case) | |
726 | except: |
|
726 | except: | |
727 | shell.showtraceback() |
|
727 | shell.showtraceback() | |
728 |
|
728 | |||
729 | @testdec.skip_doctest |
|
729 | @testdec.skip_doctest | |
730 | def magic_who_ls(self, parameter_s=''): |
|
730 | def magic_who_ls(self, parameter_s=''): | |
731 | """Return a sorted list of all interactive variables. |
|
731 | """Return a sorted list of all interactive variables. | |
732 |
|
732 | |||
733 | If arguments are given, only variables of types matching these |
|
733 | If arguments are given, only variables of types matching these | |
734 | arguments are returned. |
|
734 | arguments are returned. | |
735 |
|
735 | |||
736 | Examples |
|
736 | Examples | |
737 | -------- |
|
737 | -------- | |
738 |
|
738 | |||
739 | Define two variables and list them with who_ls:: |
|
739 | Define two variables and list them with who_ls:: | |
740 |
|
740 | |||
741 | In [1]: alpha = 123 |
|
741 | In [1]: alpha = 123 | |
742 |
|
742 | |||
743 | In [2]: beta = 'test' |
|
743 | In [2]: beta = 'test' | |
744 |
|
744 | |||
745 | In [3]: %who_ls |
|
745 | In [3]: %who_ls | |
746 | Out[3]: ['alpha', 'beta'] |
|
746 | Out[3]: ['alpha', 'beta'] | |
747 |
|
747 | |||
748 | In [4]: %who_ls int |
|
748 | In [4]: %who_ls int | |
749 | Out[4]: ['alpha'] |
|
749 | Out[4]: ['alpha'] | |
750 |
|
750 | |||
751 | In [5]: %who_ls str |
|
751 | In [5]: %who_ls str | |
752 | Out[5]: ['beta'] |
|
752 | Out[5]: ['beta'] | |
753 | """ |
|
753 | """ | |
754 |
|
754 | |||
755 | user_ns = self.shell.user_ns |
|
755 | user_ns = self.shell.user_ns | |
756 | internal_ns = self.shell.internal_ns |
|
756 | internal_ns = self.shell.internal_ns | |
757 | user_ns_hidden = self.shell.user_ns_hidden |
|
757 | user_ns_hidden = self.shell.user_ns_hidden | |
758 | out = [ i for i in user_ns |
|
758 | out = [ i for i in user_ns | |
759 | if not i.startswith('_') \ |
|
759 | if not i.startswith('_') \ | |
760 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
760 | and not (i in internal_ns or i in user_ns_hidden) ] | |
761 |
|
761 | |||
762 | typelist = parameter_s.split() |
|
762 | typelist = parameter_s.split() | |
763 | if typelist: |
|
763 | if typelist: | |
764 | typeset = set(typelist) |
|
764 | typeset = set(typelist) | |
765 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
765 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
766 |
|
766 | |||
767 | out.sort() |
|
767 | out.sort() | |
768 | return out |
|
768 | return out | |
769 |
|
769 | |||
770 | @testdec.skip_doctest |
|
770 | @testdec.skip_doctest | |
771 | def magic_who(self, parameter_s=''): |
|
771 | def magic_who(self, parameter_s=''): | |
772 | """Print all interactive variables, with some minimal formatting. |
|
772 | """Print all interactive variables, with some minimal formatting. | |
773 |
|
773 | |||
774 | If any arguments are given, only variables whose type matches one of |
|
774 | If any arguments are given, only variables whose type matches one of | |
775 | these are printed. For example: |
|
775 | these are printed. For example: | |
776 |
|
776 | |||
777 | %who function str |
|
777 | %who function str | |
778 |
|
778 | |||
779 | will only list functions and strings, excluding all other types of |
|
779 | will only list functions and strings, excluding all other types of | |
780 | variables. To find the proper type names, simply use type(var) at a |
|
780 | variables. To find the proper type names, simply use type(var) at a | |
781 | command line to see how python prints type names. For example: |
|
781 | command line to see how python prints type names. For example: | |
782 |
|
782 | |||
783 | In [1]: type('hello')\\ |
|
783 | In [1]: type('hello')\\ | |
784 | Out[1]: <type 'str'> |
|
784 | Out[1]: <type 'str'> | |
785 |
|
785 | |||
786 | indicates that the type name for strings is 'str'. |
|
786 | indicates that the type name for strings is 'str'. | |
787 |
|
787 | |||
788 | %who always excludes executed names loaded through your configuration |
|
788 | %who always excludes executed names loaded through your configuration | |
789 | file and things which are internal to IPython. |
|
789 | file and things which are internal to IPython. | |
790 |
|
790 | |||
791 | This is deliberate, as typically you may load many modules and the |
|
791 | This is deliberate, as typically you may load many modules and the | |
792 | purpose of %who is to show you only what you've manually defined. |
|
792 | purpose of %who is to show you only what you've manually defined. | |
793 |
|
793 | |||
794 | Examples |
|
794 | Examples | |
795 | -------- |
|
795 | -------- | |
796 |
|
796 | |||
797 | Define two variables and list them with who:: |
|
797 | Define two variables and list them with who:: | |
798 |
|
798 | |||
799 | In [1]: alpha = 123 |
|
799 | In [1]: alpha = 123 | |
800 |
|
800 | |||
801 | In [2]: beta = 'test' |
|
801 | In [2]: beta = 'test' | |
802 |
|
802 | |||
803 | In [3]: %who |
|
803 | In [3]: %who | |
804 | alpha beta |
|
804 | alpha beta | |
805 |
|
805 | |||
806 | In [4]: %who int |
|
806 | In [4]: %who int | |
807 | alpha |
|
807 | alpha | |
808 |
|
808 | |||
809 | In [5]: %who str |
|
809 | In [5]: %who str | |
810 | beta |
|
810 | beta | |
811 | """ |
|
811 | """ | |
812 |
|
812 | |||
813 | varlist = self.magic_who_ls(parameter_s) |
|
813 | varlist = self.magic_who_ls(parameter_s) | |
814 | if not varlist: |
|
814 | if not varlist: | |
815 | if parameter_s: |
|
815 | if parameter_s: | |
816 | print 'No variables match your requested type.' |
|
816 | print 'No variables match your requested type.' | |
817 | else: |
|
817 | else: | |
818 | print 'Interactive namespace is empty.' |
|
818 | print 'Interactive namespace is empty.' | |
819 | return |
|
819 | return | |
820 |
|
820 | |||
821 | # if we have variables, move on... |
|
821 | # if we have variables, move on... | |
822 | count = 0 |
|
822 | count = 0 | |
823 | for i in varlist: |
|
823 | for i in varlist: | |
824 | print i+'\t', |
|
824 | print i+'\t', | |
825 | count += 1 |
|
825 | count += 1 | |
826 | if count > 8: |
|
826 | if count > 8: | |
827 | count = 0 |
|
827 | count = 0 | |
828 |
|
828 | |||
829 |
|
829 | |||
830 |
|
830 | |||
831 | @testdec.skip_doctest |
|
831 | @testdec.skip_doctest | |
832 | def magic_whos(self, parameter_s=''): |
|
832 | def magic_whos(self, parameter_s=''): | |
833 | """Like %who, but gives some extra information about each variable. |
|
833 | """Like %who, but gives some extra information about each variable. | |
834 |
|
834 | |||
835 | The same type filtering of %who can be applied here. |
|
835 | The same type filtering of %who can be applied here. | |
836 |
|
836 | |||
837 | For all variables, the type is printed. Additionally it prints: |
|
837 | For all variables, the type is printed. Additionally it prints: | |
838 |
|
838 | |||
839 | - For {},[],(): their length. |
|
839 | - For {},[],(): their length. | |
840 |
|
840 | |||
841 | - For numpy arrays, a summary with shape, number of |
|
841 | - For numpy arrays, a summary with shape, number of | |
842 | elements, typecode and size in memory. |
|
842 | elements, typecode and size in memory. | |
843 |
|
843 | |||
844 | - Everything else: a string representation, snipping their middle if |
|
844 | - Everything else: a string representation, snipping their middle if | |
845 | too long. |
|
845 | too long. | |
846 |
|
846 | |||
847 | Examples |
|
847 | Examples | |
848 | -------- |
|
848 | -------- | |
849 |
|
849 | |||
850 | Define two variables and list them with whos:: |
|
850 | Define two variables and list them with whos:: | |
851 |
|
851 | |||
852 | In [1]: alpha = 123 |
|
852 | In [1]: alpha = 123 | |
853 |
|
853 | |||
854 | In [2]: beta = 'test' |
|
854 | In [2]: beta = 'test' | |
855 |
|
855 | |||
856 | In [3]: %whos |
|
856 | In [3]: %whos | |
857 | Variable Type Data/Info |
|
857 | Variable Type Data/Info | |
858 | -------------------------------- |
|
858 | -------------------------------- | |
859 | alpha int 123 |
|
859 | alpha int 123 | |
860 | beta str test |
|
860 | beta str test | |
861 | """ |
|
861 | """ | |
862 |
|
862 | |||
863 | varnames = self.magic_who_ls(parameter_s) |
|
863 | varnames = self.magic_who_ls(parameter_s) | |
864 | if not varnames: |
|
864 | if not varnames: | |
865 | if parameter_s: |
|
865 | if parameter_s: | |
866 | print 'No variables match your requested type.' |
|
866 | print 'No variables match your requested type.' | |
867 | else: |
|
867 | else: | |
868 | print 'Interactive namespace is empty.' |
|
868 | print 'Interactive namespace is empty.' | |
869 | return |
|
869 | return | |
870 |
|
870 | |||
871 | # if we have variables, move on... |
|
871 | # if we have variables, move on... | |
872 |
|
872 | |||
873 | # for these types, show len() instead of data: |
|
873 | # for these types, show len() instead of data: | |
874 | seq_types = ['dict', 'list', 'tuple'] |
|
874 | seq_types = ['dict', 'list', 'tuple'] | |
875 |
|
875 | |||
876 | # for numpy/Numeric arrays, display summary info |
|
876 | # for numpy/Numeric arrays, display summary info | |
877 | try: |
|
877 | try: | |
878 | import numpy |
|
878 | import numpy | |
879 | except ImportError: |
|
879 | except ImportError: | |
880 | ndarray_type = None |
|
880 | ndarray_type = None | |
881 | else: |
|
881 | else: | |
882 | ndarray_type = numpy.ndarray.__name__ |
|
882 | ndarray_type = numpy.ndarray.__name__ | |
883 | try: |
|
883 | try: | |
884 | import Numeric |
|
884 | import Numeric | |
885 | except ImportError: |
|
885 | except ImportError: | |
886 | array_type = None |
|
886 | array_type = None | |
887 | else: |
|
887 | else: | |
888 | array_type = Numeric.ArrayType.__name__ |
|
888 | array_type = Numeric.ArrayType.__name__ | |
889 |
|
889 | |||
890 | # Find all variable names and types so we can figure out column sizes |
|
890 | # Find all variable names and types so we can figure out column sizes | |
891 | def get_vars(i): |
|
891 | def get_vars(i): | |
892 | return self.shell.user_ns[i] |
|
892 | return self.shell.user_ns[i] | |
893 |
|
893 | |||
894 | # some types are well known and can be shorter |
|
894 | # some types are well known and can be shorter | |
895 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
895 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
896 | def type_name(v): |
|
896 | def type_name(v): | |
897 | tn = type(v).__name__ |
|
897 | tn = type(v).__name__ | |
898 | return abbrevs.get(tn,tn) |
|
898 | return abbrevs.get(tn,tn) | |
899 |
|
899 | |||
900 | varlist = map(get_vars,varnames) |
|
900 | varlist = map(get_vars,varnames) | |
901 |
|
901 | |||
902 | typelist = [] |
|
902 | typelist = [] | |
903 | for vv in varlist: |
|
903 | for vv in varlist: | |
904 | tt = type_name(vv) |
|
904 | tt = type_name(vv) | |
905 |
|
905 | |||
906 | if tt=='instance': |
|
906 | if tt=='instance': | |
907 | typelist.append( abbrevs.get(str(vv.__class__), |
|
907 | typelist.append( abbrevs.get(str(vv.__class__), | |
908 | str(vv.__class__))) |
|
908 | str(vv.__class__))) | |
909 | else: |
|
909 | else: | |
910 | typelist.append(tt) |
|
910 | typelist.append(tt) | |
911 |
|
911 | |||
912 | # column labels and # of spaces as separator |
|
912 | # column labels and # of spaces as separator | |
913 | varlabel = 'Variable' |
|
913 | varlabel = 'Variable' | |
914 | typelabel = 'Type' |
|
914 | typelabel = 'Type' | |
915 | datalabel = 'Data/Info' |
|
915 | datalabel = 'Data/Info' | |
916 | colsep = 3 |
|
916 | colsep = 3 | |
917 | # variable format strings |
|
917 | # variable format strings | |
918 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
918 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
919 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
919 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
920 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
920 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
921 | # find the size of the columns to format the output nicely |
|
921 | # find the size of the columns to format the output nicely | |
922 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
922 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
923 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
923 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
924 | # table header |
|
924 | # table header | |
925 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
925 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
926 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
926 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
927 | # and the table itself |
|
927 | # and the table itself | |
928 | kb = 1024 |
|
928 | kb = 1024 | |
929 | Mb = 1048576 # kb**2 |
|
929 | Mb = 1048576 # kb**2 | |
930 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
930 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
931 | print itpl(vformat), |
|
931 | print itpl(vformat), | |
932 | if vtype in seq_types: |
|
932 | if vtype in seq_types: | |
933 | print "n="+str(len(var)) |
|
933 | print "n="+str(len(var)) | |
934 | elif vtype in [array_type,ndarray_type]: |
|
934 | elif vtype in [array_type,ndarray_type]: | |
935 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
935 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
936 | if vtype==ndarray_type: |
|
936 | if vtype==ndarray_type: | |
937 | # numpy |
|
937 | # numpy | |
938 | vsize = var.size |
|
938 | vsize = var.size | |
939 | vbytes = vsize*var.itemsize |
|
939 | vbytes = vsize*var.itemsize | |
940 | vdtype = var.dtype |
|
940 | vdtype = var.dtype | |
941 | else: |
|
941 | else: | |
942 | # Numeric |
|
942 | # Numeric | |
943 | vsize = Numeric.size(var) |
|
943 | vsize = Numeric.size(var) | |
944 | vbytes = vsize*var.itemsize() |
|
944 | vbytes = vsize*var.itemsize() | |
945 | vdtype = var.typecode() |
|
945 | vdtype = var.typecode() | |
946 |
|
946 | |||
947 | if vbytes < 100000: |
|
947 | if vbytes < 100000: | |
948 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
948 | print aformat % (vshape,vsize,vdtype,vbytes) | |
949 | else: |
|
949 | else: | |
950 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
950 | print aformat % (vshape,vsize,vdtype,vbytes), | |
951 | if vbytes < Mb: |
|
951 | if vbytes < Mb: | |
952 | print '(%s kb)' % (vbytes/kb,) |
|
952 | print '(%s kb)' % (vbytes/kb,) | |
953 | else: |
|
953 | else: | |
954 | print '(%s Mb)' % (vbytes/Mb,) |
|
954 | print '(%s Mb)' % (vbytes/Mb,) | |
955 | else: |
|
955 | else: | |
956 | try: |
|
956 | try: | |
957 | vstr = str(var) |
|
957 | vstr = str(var) | |
958 | except UnicodeEncodeError: |
|
958 | except UnicodeEncodeError: | |
959 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
959 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
960 | 'backslashreplace') |
|
960 | 'backslashreplace') | |
961 | vstr = vstr.replace('\n','\\n') |
|
961 | vstr = vstr.replace('\n','\\n') | |
962 | if len(vstr) < 50: |
|
962 | if len(vstr) < 50: | |
963 | print vstr |
|
963 | print vstr | |
964 | else: |
|
964 | else: | |
965 | printpl(vfmt_short) |
|
965 | printpl(vfmt_short) | |
966 |
|
966 | |||
967 | def magic_reset(self, parameter_s=''): |
|
967 | def magic_reset(self, parameter_s=''): | |
968 | """Resets the namespace by removing all names defined by the user. |
|
968 | """Resets the namespace by removing all names defined by the user. | |
969 |
|
969 | |||
970 | Parameters |
|
970 | Parameters | |
971 | ---------- |
|
971 | ---------- | |
972 | -f : force reset without asking for confirmation. |
|
972 | -f : force reset without asking for confirmation. | |
973 |
|
973 | |||
974 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
974 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
975 | References to objects may be kept. By default (without this option), |
|
975 | References to objects may be kept. By default (without this option), | |
976 | we do a 'hard' reset, giving you a new session and removing all |
|
976 | we do a 'hard' reset, giving you a new session and removing all | |
977 | references to objects from the current session. |
|
977 | references to objects from the current session. | |
978 |
|
978 | |||
979 | Examples |
|
979 | Examples | |
980 | -------- |
|
980 | -------- | |
981 | In [6]: a = 1 |
|
981 | In [6]: a = 1 | |
982 |
|
982 | |||
983 | In [7]: a |
|
983 | In [7]: a | |
984 | Out[7]: 1 |
|
984 | Out[7]: 1 | |
985 |
|
985 | |||
986 | In [8]: 'a' in _ip.user_ns |
|
986 | In [8]: 'a' in _ip.user_ns | |
987 | Out[8]: True |
|
987 | Out[8]: True | |
988 |
|
988 | |||
989 | In [9]: %reset -f |
|
989 | In [9]: %reset -f | |
990 |
|
990 | |||
991 | In [1]: 'a' in _ip.user_ns |
|
991 | In [1]: 'a' in _ip.user_ns | |
992 | Out[1]: False |
|
992 | Out[1]: False | |
993 | """ |
|
993 | """ | |
994 | opts, args = self.parse_options(parameter_s,'sf') |
|
994 | opts, args = self.parse_options(parameter_s,'sf') | |
995 | if 'f' in opts: |
|
995 | if 'f' in opts: | |
996 | ans = True |
|
996 | ans = True | |
997 | else: |
|
997 | else: | |
998 | ans = self.shell.ask_yes_no( |
|
998 | ans = self.shell.ask_yes_no( | |
999 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
999 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1000 | if not ans: |
|
1000 | if not ans: | |
1001 | print 'Nothing done.' |
|
1001 | print 'Nothing done.' | |
1002 | return |
|
1002 | return | |
1003 |
|
1003 | |||
1004 | if 's' in opts: # Soft reset |
|
1004 | if 's' in opts: # Soft reset | |
1005 | user_ns = self.shell.user_ns |
|
1005 | user_ns = self.shell.user_ns | |
1006 | for i in self.magic_who_ls(): |
|
1006 | for i in self.magic_who_ls(): | |
1007 | del(user_ns[i]) |
|
1007 | del(user_ns[i]) | |
1008 |
|
1008 | |||
1009 | else: # Hard reset |
|
1009 | else: # Hard reset | |
1010 | self.shell.reset(new_session = False) |
|
1010 | self.shell.reset(new_session = False) | |
1011 |
|
1011 | |||
1012 |
|
1012 | |||
1013 |
|
1013 | |||
1014 | def magic_reset_selective(self, parameter_s=''): |
|
1014 | def magic_reset_selective(self, parameter_s=''): | |
1015 | """Resets the namespace by removing names defined by the user. |
|
1015 | """Resets the namespace by removing names defined by the user. | |
1016 |
|
1016 | |||
1017 | Input/Output history are left around in case you need them. |
|
1017 | Input/Output history are left around in case you need them. | |
1018 |
|
1018 | |||
1019 | %reset_selective [-f] regex |
|
1019 | %reset_selective [-f] regex | |
1020 |
|
1020 | |||
1021 | No action is taken if regex is not included |
|
1021 | No action is taken if regex is not included | |
1022 |
|
1022 | |||
1023 | Options |
|
1023 | Options | |
1024 | -f : force reset without asking for confirmation. |
|
1024 | -f : force reset without asking for confirmation. | |
1025 |
|
1025 | |||
1026 | Examples |
|
1026 | Examples | |
1027 | -------- |
|
1027 | -------- | |
1028 |
|
1028 | |||
1029 | We first fully reset the namespace so your output looks identical to |
|
1029 | We first fully reset the namespace so your output looks identical to | |
1030 | this example for pedagogical reasons; in practice you do not need a |
|
1030 | this example for pedagogical reasons; in practice you do not need a | |
1031 | full reset. |
|
1031 | full reset. | |
1032 |
|
1032 | |||
1033 | In [1]: %reset -f |
|
1033 | In [1]: %reset -f | |
1034 |
|
1034 | |||
1035 | Now, with a clean namespace we can make a few variables and use |
|
1035 | Now, with a clean namespace we can make a few variables and use | |
1036 | %reset_selective to only delete names that match our regexp: |
|
1036 | %reset_selective to only delete names that match our regexp: | |
1037 |
|
1037 | |||
1038 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1038 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1039 |
|
1039 | |||
1040 | In [3]: who_ls |
|
1040 | In [3]: who_ls | |
1041 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1041 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1042 |
|
1042 | |||
1043 | In [4]: %reset_selective -f b[2-3]m |
|
1043 | In [4]: %reset_selective -f b[2-3]m | |
1044 |
|
1044 | |||
1045 | In [5]: who_ls |
|
1045 | In [5]: who_ls | |
1046 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1046 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1047 |
|
1047 | |||
1048 | In [6]: %reset_selective -f d |
|
1048 | In [6]: %reset_selective -f d | |
1049 |
|
1049 | |||
1050 | In [7]: who_ls |
|
1050 | In [7]: who_ls | |
1051 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1051 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1052 |
|
1052 | |||
1053 | In [8]: %reset_selective -f c |
|
1053 | In [8]: %reset_selective -f c | |
1054 |
|
1054 | |||
1055 | In [9]: who_ls |
|
1055 | In [9]: who_ls | |
1056 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1056 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1057 |
|
1057 | |||
1058 | In [10]: %reset_selective -f b |
|
1058 | In [10]: %reset_selective -f b | |
1059 |
|
1059 | |||
1060 | In [11]: who_ls |
|
1060 | In [11]: who_ls | |
1061 | Out[11]: ['a'] |
|
1061 | Out[11]: ['a'] | |
1062 | """ |
|
1062 | """ | |
1063 |
|
1063 | |||
1064 | opts, regex = self.parse_options(parameter_s,'f') |
|
1064 | opts, regex = self.parse_options(parameter_s,'f') | |
1065 |
|
1065 | |||
1066 | if opts.has_key('f'): |
|
1066 | if opts.has_key('f'): | |
1067 | ans = True |
|
1067 | ans = True | |
1068 | else: |
|
1068 | else: | |
1069 | ans = self.shell.ask_yes_no( |
|
1069 | ans = self.shell.ask_yes_no( | |
1070 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1070 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1071 | if not ans: |
|
1071 | if not ans: | |
1072 | print 'Nothing done.' |
|
1072 | print 'Nothing done.' | |
1073 | return |
|
1073 | return | |
1074 | user_ns = self.shell.user_ns |
|
1074 | user_ns = self.shell.user_ns | |
1075 | if not regex: |
|
1075 | if not regex: | |
1076 | print 'No regex pattern specified. Nothing done.' |
|
1076 | print 'No regex pattern specified. Nothing done.' | |
1077 | return |
|
1077 | return | |
1078 | else: |
|
1078 | else: | |
1079 | try: |
|
1079 | try: | |
1080 | m = re.compile(regex) |
|
1080 | m = re.compile(regex) | |
1081 | except TypeError: |
|
1081 | except TypeError: | |
1082 | raise TypeError('regex must be a string or compiled pattern') |
|
1082 | raise TypeError('regex must be a string or compiled pattern') | |
1083 | for i in self.magic_who_ls(): |
|
1083 | for i in self.magic_who_ls(): | |
1084 | if m.search(i): |
|
1084 | if m.search(i): | |
1085 | del(user_ns[i]) |
|
1085 | del(user_ns[i]) | |
1086 |
|
1086 | |||
1087 | def magic_logstart(self,parameter_s=''): |
|
1087 | def magic_logstart(self,parameter_s=''): | |
1088 | """Start logging anywhere in a session. |
|
1088 | """Start logging anywhere in a session. | |
1089 |
|
1089 | |||
1090 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1090 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1091 |
|
1091 | |||
1092 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1092 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1093 | current directory, in 'rotate' mode (see below). |
|
1093 | current directory, in 'rotate' mode (see below). | |
1094 |
|
1094 | |||
1095 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1095 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1096 | history up to that point and then continues logging. |
|
1096 | history up to that point and then continues logging. | |
1097 |
|
1097 | |||
1098 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1098 | %logstart takes a second optional parameter: logging mode. This can be one | |
1099 | of (note that the modes are given unquoted):\\ |
|
1099 | of (note that the modes are given unquoted):\\ | |
1100 | append: well, that says it.\\ |
|
1100 | append: well, that says it.\\ | |
1101 | backup: rename (if exists) to name~ and start name.\\ |
|
1101 | backup: rename (if exists) to name~ and start name.\\ | |
1102 | global: single logfile in your home dir, appended to.\\ |
|
1102 | global: single logfile in your home dir, appended to.\\ | |
1103 | over : overwrite existing log.\\ |
|
1103 | over : overwrite existing log.\\ | |
1104 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1104 | rotate: create rotating logs name.1~, name.2~, etc. | |
1105 |
|
1105 | |||
1106 | Options: |
|
1106 | Options: | |
1107 |
|
1107 | |||
1108 | -o: log also IPython's output. In this mode, all commands which |
|
1108 | -o: log also IPython's output. In this mode, all commands which | |
1109 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1109 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1110 | their corresponding input line. The output lines are always |
|
1110 | their corresponding input line. The output lines are always | |
1111 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1111 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1112 | Python code. |
|
1112 | Python code. | |
1113 |
|
1113 | |||
1114 | Since this marker is always the same, filtering only the output from |
|
1114 | Since this marker is always the same, filtering only the output from | |
1115 | a log is very easy, using for example a simple awk call: |
|
1115 | a log is very easy, using for example a simple awk call: | |
1116 |
|
1116 | |||
1117 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1117 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1118 |
|
1118 | |||
1119 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1119 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1120 | input, so that user lines are logged in their final form, converted |
|
1120 | input, so that user lines are logged in their final form, converted | |
1121 | into valid Python. For example, %Exit is logged as |
|
1121 | into valid Python. For example, %Exit is logged as | |
1122 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1122 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1123 | exactly as typed, with no transformations applied. |
|
1123 | exactly as typed, with no transformations applied. | |
1124 |
|
1124 | |||
1125 | -t: put timestamps before each input line logged (these are put in |
|
1125 | -t: put timestamps before each input line logged (these are put in | |
1126 | comments).""" |
|
1126 | comments).""" | |
1127 |
|
1127 | |||
1128 | opts,par = self.parse_options(parameter_s,'ort') |
|
1128 | opts,par = self.parse_options(parameter_s,'ort') | |
1129 | log_output = 'o' in opts |
|
1129 | log_output = 'o' in opts | |
1130 | log_raw_input = 'r' in opts |
|
1130 | log_raw_input = 'r' in opts | |
1131 | timestamp = 't' in opts |
|
1131 | timestamp = 't' in opts | |
1132 |
|
1132 | |||
1133 | logger = self.shell.logger |
|
1133 | logger = self.shell.logger | |
1134 |
|
1134 | |||
1135 | # if no args are given, the defaults set in the logger constructor by |
|
1135 | # if no args are given, the defaults set in the logger constructor by | |
1136 | # ipytohn remain valid |
|
1136 | # ipytohn remain valid | |
1137 | if par: |
|
1137 | if par: | |
1138 | try: |
|
1138 | try: | |
1139 | logfname,logmode = par.split() |
|
1139 | logfname,logmode = par.split() | |
1140 | except: |
|
1140 | except: | |
1141 | logfname = par |
|
1141 | logfname = par | |
1142 | logmode = 'backup' |
|
1142 | logmode = 'backup' | |
1143 | else: |
|
1143 | else: | |
1144 | logfname = logger.logfname |
|
1144 | logfname = logger.logfname | |
1145 | logmode = logger.logmode |
|
1145 | logmode = logger.logmode | |
1146 | # put logfname into rc struct as if it had been called on the command |
|
1146 | # put logfname into rc struct as if it had been called on the command | |
1147 | # line, so it ends up saved in the log header Save it in case we need |
|
1147 | # line, so it ends up saved in the log header Save it in case we need | |
1148 | # to restore it... |
|
1148 | # to restore it... | |
1149 | old_logfile = self.shell.logfile |
|
1149 | old_logfile = self.shell.logfile | |
1150 | if logfname: |
|
1150 | if logfname: | |
1151 | logfname = os.path.expanduser(logfname) |
|
1151 | logfname = os.path.expanduser(logfname) | |
1152 | self.shell.logfile = logfname |
|
1152 | self.shell.logfile = logfname | |
1153 |
|
1153 | |||
1154 | loghead = '# IPython log file\n\n' |
|
1154 | loghead = '# IPython log file\n\n' | |
1155 | try: |
|
1155 | try: | |
1156 | started = logger.logstart(logfname,loghead,logmode, |
|
1156 | started = logger.logstart(logfname,loghead,logmode, | |
1157 | log_output,timestamp,log_raw_input) |
|
1157 | log_output,timestamp,log_raw_input) | |
1158 | except: |
|
1158 | except: | |
1159 | self.shell.logfile = old_logfile |
|
1159 | self.shell.logfile = old_logfile | |
1160 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1160 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1161 | else: |
|
1161 | else: | |
1162 | # log input history up to this point, optionally interleaving |
|
1162 | # log input history up to this point, optionally interleaving | |
1163 | # output if requested |
|
1163 | # output if requested | |
1164 |
|
1164 | |||
1165 | if timestamp: |
|
1165 | if timestamp: | |
1166 | # disable timestamping for the previous history, since we've |
|
1166 | # disable timestamping for the previous history, since we've | |
1167 | # lost those already (no time machine here). |
|
1167 | # lost those already (no time machine here). | |
1168 | logger.timestamp = False |
|
1168 | logger.timestamp = False | |
1169 |
|
1169 | |||
1170 | if log_raw_input: |
|
1170 | if log_raw_input: | |
1171 | input_hist = self.shell.history_manager.input_hist_raw |
|
1171 | input_hist = self.shell.history_manager.input_hist_raw | |
1172 | else: |
|
1172 | else: | |
1173 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1173 | input_hist = self.shell.history_manager.input_hist_parsed | |
1174 |
|
1174 | |||
1175 | if log_output: |
|
1175 | if log_output: | |
1176 | log_write = logger.log_write |
|
1176 | log_write = logger.log_write | |
1177 | output_hist = self.shell.history_manager.output_hist |
|
1177 | output_hist = self.shell.history_manager.output_hist | |
1178 | for n in range(1,len(input_hist)-1): |
|
1178 | for n in range(1,len(input_hist)-1): | |
1179 | log_write(input_hist[n].rstrip()) |
|
1179 | log_write(input_hist[n].rstrip()) | |
1180 | if n in output_hist: |
|
1180 | if n in output_hist: | |
1181 | log_write(repr(output_hist[n]),'output') |
|
1181 | log_write(repr(output_hist[n]),'output') | |
1182 | else: |
|
1182 | else: | |
1183 | logger.log_write(''.join(input_hist[1:])) |
|
1183 | logger.log_write(''.join(input_hist[1:])) | |
1184 | if timestamp: |
|
1184 | if timestamp: | |
1185 | # re-enable timestamping |
|
1185 | # re-enable timestamping | |
1186 | logger.timestamp = True |
|
1186 | logger.timestamp = True | |
1187 |
|
1187 | |||
1188 | print ('Activating auto-logging. ' |
|
1188 | print ('Activating auto-logging. ' | |
1189 | 'Current session state plus future input saved.') |
|
1189 | 'Current session state plus future input saved.') | |
1190 | logger.logstate() |
|
1190 | logger.logstate() | |
1191 |
|
1191 | |||
1192 | def magic_logstop(self,parameter_s=''): |
|
1192 | def magic_logstop(self,parameter_s=''): | |
1193 | """Fully stop logging and close log file. |
|
1193 | """Fully stop logging and close log file. | |
1194 |
|
1194 | |||
1195 | In order to start logging again, a new %logstart call needs to be made, |
|
1195 | In order to start logging again, a new %logstart call needs to be made, | |
1196 | possibly (though not necessarily) with a new filename, mode and other |
|
1196 | possibly (though not necessarily) with a new filename, mode and other | |
1197 | options.""" |
|
1197 | options.""" | |
1198 | self.logger.logstop() |
|
1198 | self.logger.logstop() | |
1199 |
|
1199 | |||
1200 | def magic_logoff(self,parameter_s=''): |
|
1200 | def magic_logoff(self,parameter_s=''): | |
1201 | """Temporarily stop logging. |
|
1201 | """Temporarily stop logging. | |
1202 |
|
1202 | |||
1203 | You must have previously started logging.""" |
|
1203 | You must have previously started logging.""" | |
1204 | self.shell.logger.switch_log(0) |
|
1204 | self.shell.logger.switch_log(0) | |
1205 |
|
1205 | |||
1206 | def magic_logon(self,parameter_s=''): |
|
1206 | def magic_logon(self,parameter_s=''): | |
1207 | """Restart logging. |
|
1207 | """Restart logging. | |
1208 |
|
1208 | |||
1209 | This function is for restarting logging which you've temporarily |
|
1209 | This function is for restarting logging which you've temporarily | |
1210 | stopped with %logoff. For starting logging for the first time, you |
|
1210 | stopped with %logoff. For starting logging for the first time, you | |
1211 | must use the %logstart function, which allows you to specify an |
|
1211 | must use the %logstart function, which allows you to specify an | |
1212 | optional log filename.""" |
|
1212 | optional log filename.""" | |
1213 |
|
1213 | |||
1214 | self.shell.logger.switch_log(1) |
|
1214 | self.shell.logger.switch_log(1) | |
1215 |
|
1215 | |||
1216 | def magic_logstate(self,parameter_s=''): |
|
1216 | def magic_logstate(self,parameter_s=''): | |
1217 | """Print the status of the logging system.""" |
|
1217 | """Print the status of the logging system.""" | |
1218 |
|
1218 | |||
1219 | self.shell.logger.logstate() |
|
1219 | self.shell.logger.logstate() | |
1220 |
|
1220 | |||
1221 | def magic_pdb(self, parameter_s=''): |
|
1221 | def magic_pdb(self, parameter_s=''): | |
1222 | """Control the automatic calling of the pdb interactive debugger. |
|
1222 | """Control the automatic calling of the pdb interactive debugger. | |
1223 |
|
1223 | |||
1224 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1224 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1225 | argument it works as a toggle. |
|
1225 | argument it works as a toggle. | |
1226 |
|
1226 | |||
1227 | When an exception is triggered, IPython can optionally call the |
|
1227 | When an exception is triggered, IPython can optionally call the | |
1228 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1228 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1229 | this feature on and off. |
|
1229 | this feature on and off. | |
1230 |
|
1230 | |||
1231 | The initial state of this feature is set in your ipythonrc |
|
1231 | The initial state of this feature is set in your ipythonrc | |
1232 | configuration file (the variable is called 'pdb'). |
|
1232 | configuration file (the variable is called 'pdb'). | |
1233 |
|
1233 | |||
1234 | If you want to just activate the debugger AFTER an exception has fired, |
|
1234 | If you want to just activate the debugger AFTER an exception has fired, | |
1235 | without having to type '%pdb on' and rerunning your code, you can use |
|
1235 | without having to type '%pdb on' and rerunning your code, you can use | |
1236 | the %debug magic.""" |
|
1236 | the %debug magic.""" | |
1237 |
|
1237 | |||
1238 | par = parameter_s.strip().lower() |
|
1238 | par = parameter_s.strip().lower() | |
1239 |
|
1239 | |||
1240 | if par: |
|
1240 | if par: | |
1241 | try: |
|
1241 | try: | |
1242 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1242 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1243 | except KeyError: |
|
1243 | except KeyError: | |
1244 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1244 | print ('Incorrect argument. Use on/1, off/0, ' | |
1245 | 'or nothing for a toggle.') |
|
1245 | 'or nothing for a toggle.') | |
1246 | return |
|
1246 | return | |
1247 | else: |
|
1247 | else: | |
1248 | # toggle |
|
1248 | # toggle | |
1249 | new_pdb = not self.shell.call_pdb |
|
1249 | new_pdb = not self.shell.call_pdb | |
1250 |
|
1250 | |||
1251 | # set on the shell |
|
1251 | # set on the shell | |
1252 | self.shell.call_pdb = new_pdb |
|
1252 | self.shell.call_pdb = new_pdb | |
1253 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1253 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1254 |
|
1254 | |||
1255 | def magic_debug(self, parameter_s=''): |
|
1255 | def magic_debug(self, parameter_s=''): | |
1256 | """Activate the interactive debugger in post-mortem mode. |
|
1256 | """Activate the interactive debugger in post-mortem mode. | |
1257 |
|
1257 | |||
1258 | If an exception has just occurred, this lets you inspect its stack |
|
1258 | If an exception has just occurred, this lets you inspect its stack | |
1259 | frames interactively. Note that this will always work only on the last |
|
1259 | frames interactively. Note that this will always work only on the last | |
1260 | traceback that occurred, so you must call this quickly after an |
|
1260 | traceback that occurred, so you must call this quickly after an | |
1261 | exception that you wish to inspect has fired, because if another one |
|
1261 | exception that you wish to inspect has fired, because if another one | |
1262 | occurs, it clobbers the previous one. |
|
1262 | occurs, it clobbers the previous one. | |
1263 |
|
1263 | |||
1264 | If you want IPython to automatically do this on every exception, see |
|
1264 | If you want IPython to automatically do this on every exception, see | |
1265 | the %pdb magic for more details. |
|
1265 | the %pdb magic for more details. | |
1266 | """ |
|
1266 | """ | |
1267 | self.shell.debugger(force=True) |
|
1267 | self.shell.debugger(force=True) | |
1268 |
|
1268 | |||
1269 | @testdec.skip_doctest |
|
1269 | @testdec.skip_doctest | |
1270 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1270 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1271 | opts=None,arg_lst=None,prog_ns=None): |
|
1271 | opts=None,arg_lst=None,prog_ns=None): | |
1272 |
|
1272 | |||
1273 | """Run a statement through the python code profiler. |
|
1273 | """Run a statement through the python code profiler. | |
1274 |
|
1274 | |||
1275 | Usage: |
|
1275 | Usage: | |
1276 | %prun [options] statement |
|
1276 | %prun [options] statement | |
1277 |
|
1277 | |||
1278 | The given statement (which doesn't require quote marks) is run via the |
|
1278 | The given statement (which doesn't require quote marks) is run via the | |
1279 | python profiler in a manner similar to the profile.run() function. |
|
1279 | python profiler in a manner similar to the profile.run() function. | |
1280 | Namespaces are internally managed to work correctly; profile.run |
|
1280 | Namespaces are internally managed to work correctly; profile.run | |
1281 | cannot be used in IPython because it makes certain assumptions about |
|
1281 | cannot be used in IPython because it makes certain assumptions about | |
1282 | namespaces which do not hold under IPython. |
|
1282 | namespaces which do not hold under IPython. | |
1283 |
|
1283 | |||
1284 | Options: |
|
1284 | Options: | |
1285 |
|
1285 | |||
1286 | -l <limit>: you can place restrictions on what or how much of the |
|
1286 | -l <limit>: you can place restrictions on what or how much of the | |
1287 | profile gets printed. The limit value can be: |
|
1287 | profile gets printed. The limit value can be: | |
1288 |
|
1288 | |||
1289 | * A string: only information for function names containing this string |
|
1289 | * A string: only information for function names containing this string | |
1290 | is printed. |
|
1290 | is printed. | |
1291 |
|
1291 | |||
1292 | * An integer: only these many lines are printed. |
|
1292 | * An integer: only these many lines are printed. | |
1293 |
|
1293 | |||
1294 | * A float (between 0 and 1): this fraction of the report is printed |
|
1294 | * A float (between 0 and 1): this fraction of the report is printed | |
1295 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1295 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1296 |
|
1296 | |||
1297 | You can combine several limits with repeated use of the option. For |
|
1297 | You can combine several limits with repeated use of the option. For | |
1298 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1298 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1299 | information about class constructors. |
|
1299 | information about class constructors. | |
1300 |
|
1300 | |||
1301 | -r: return the pstats.Stats object generated by the profiling. This |
|
1301 | -r: return the pstats.Stats object generated by the profiling. This | |
1302 | object has all the information about the profile in it, and you can |
|
1302 | object has all the information about the profile in it, and you can | |
1303 | later use it for further analysis or in other functions. |
|
1303 | later use it for further analysis or in other functions. | |
1304 |
|
1304 | |||
1305 | -s <key>: sort profile by given key. You can provide more than one key |
|
1305 | -s <key>: sort profile by given key. You can provide more than one key | |
1306 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1306 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1307 | default sorting key is 'time'. |
|
1307 | default sorting key is 'time'. | |
1308 |
|
1308 | |||
1309 | The following is copied verbatim from the profile documentation |
|
1309 | The following is copied verbatim from the profile documentation | |
1310 | referenced below: |
|
1310 | referenced below: | |
1311 |
|
1311 | |||
1312 | When more than one key is provided, additional keys are used as |
|
1312 | When more than one key is provided, additional keys are used as | |
1313 | secondary criteria when the there is equality in all keys selected |
|
1313 | secondary criteria when the there is equality in all keys selected | |
1314 | before them. |
|
1314 | before them. | |
1315 |
|
1315 | |||
1316 | Abbreviations can be used for any key names, as long as the |
|
1316 | Abbreviations can be used for any key names, as long as the | |
1317 | abbreviation is unambiguous. The following are the keys currently |
|
1317 | abbreviation is unambiguous. The following are the keys currently | |
1318 | defined: |
|
1318 | defined: | |
1319 |
|
1319 | |||
1320 | Valid Arg Meaning |
|
1320 | Valid Arg Meaning | |
1321 | "calls" call count |
|
1321 | "calls" call count | |
1322 | "cumulative" cumulative time |
|
1322 | "cumulative" cumulative time | |
1323 | "file" file name |
|
1323 | "file" file name | |
1324 | "module" file name |
|
1324 | "module" file name | |
1325 | "pcalls" primitive call count |
|
1325 | "pcalls" primitive call count | |
1326 | "line" line number |
|
1326 | "line" line number | |
1327 | "name" function name |
|
1327 | "name" function name | |
1328 | "nfl" name/file/line |
|
1328 | "nfl" name/file/line | |
1329 | "stdname" standard name |
|
1329 | "stdname" standard name | |
1330 | "time" internal time |
|
1330 | "time" internal time | |
1331 |
|
1331 | |||
1332 | Note that all sorts on statistics are in descending order (placing |
|
1332 | Note that all sorts on statistics are in descending order (placing | |
1333 | most time consuming items first), where as name, file, and line number |
|
1333 | most time consuming items first), where as name, file, and line number | |
1334 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1334 | searches are in ascending order (i.e., alphabetical). The subtle | |
1335 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1335 | distinction between "nfl" and "stdname" is that the standard name is a | |
1336 | sort of the name as printed, which means that the embedded line |
|
1336 | sort of the name as printed, which means that the embedded line | |
1337 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1337 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1338 | would (if the file names were the same) appear in the string order |
|
1338 | would (if the file names were the same) appear in the string order | |
1339 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1339 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1340 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1340 | line numbers. In fact, sort_stats("nfl") is the same as | |
1341 | sort_stats("name", "file", "line"). |
|
1341 | sort_stats("name", "file", "line"). | |
1342 |
|
1342 | |||
1343 | -T <filename>: save profile results as shown on screen to a text |
|
1343 | -T <filename>: save profile results as shown on screen to a text | |
1344 | file. The profile is still shown on screen. |
|
1344 | file. The profile is still shown on screen. | |
1345 |
|
1345 | |||
1346 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1346 | -D <filename>: save (via dump_stats) profile statistics to given | |
1347 | filename. This data is in a format understod by the pstats module, and |
|
1347 | filename. This data is in a format understod by the pstats module, and | |
1348 | is generated by a call to the dump_stats() method of profile |
|
1348 | is generated by a call to the dump_stats() method of profile | |
1349 | objects. The profile is still shown on screen. |
|
1349 | objects. The profile is still shown on screen. | |
1350 |
|
1350 | |||
1351 | If you want to run complete programs under the profiler's control, use |
|
1351 | If you want to run complete programs under the profiler's control, use | |
1352 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1352 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1353 | contains profiler specific options as described here. |
|
1353 | contains profiler specific options as described here. | |
1354 |
|
1354 | |||
1355 | You can read the complete documentation for the profile module with:: |
|
1355 | You can read the complete documentation for the profile module with:: | |
1356 |
|
1356 | |||
1357 | In [1]: import profile; profile.help() |
|
1357 | In [1]: import profile; profile.help() | |
1358 | """ |
|
1358 | """ | |
1359 |
|
1359 | |||
1360 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1360 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1361 | # protect user quote marks |
|
1361 | # protect user quote marks | |
1362 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1362 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1363 |
|
1363 | |||
1364 | if user_mode: # regular user call |
|
1364 | if user_mode: # regular user call | |
1365 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1365 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1366 | list_all=1) |
|
1366 | list_all=1) | |
1367 | namespace = self.shell.user_ns |
|
1367 | namespace = self.shell.user_ns | |
1368 | else: # called to run a program by %run -p |
|
1368 | else: # called to run a program by %run -p | |
1369 | try: |
|
1369 | try: | |
1370 | filename = get_py_filename(arg_lst[0]) |
|
1370 | filename = get_py_filename(arg_lst[0]) | |
1371 | except IOError,msg: |
|
1371 | except IOError,msg: | |
1372 | error(msg) |
|
1372 | error(msg) | |
1373 | return |
|
1373 | return | |
1374 |
|
1374 | |||
1375 | arg_str = 'execfile(filename,prog_ns)' |
|
1375 | arg_str = 'execfile(filename,prog_ns)' | |
1376 | namespace = locals() |
|
1376 | namespace = locals() | |
1377 |
|
1377 | |||
1378 | opts.merge(opts_def) |
|
1378 | opts.merge(opts_def) | |
1379 |
|
1379 | |||
1380 | prof = profile.Profile() |
|
1380 | prof = profile.Profile() | |
1381 | try: |
|
1381 | try: | |
1382 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1382 | prof = prof.runctx(arg_str,namespace,namespace) | |
1383 | sys_exit = '' |
|
1383 | sys_exit = '' | |
1384 | except SystemExit: |
|
1384 | except SystemExit: | |
1385 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1385 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1386 |
|
1386 | |||
1387 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1387 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1388 |
|
1388 | |||
1389 | lims = opts.l |
|
1389 | lims = opts.l | |
1390 | if lims: |
|
1390 | if lims: | |
1391 | lims = [] # rebuild lims with ints/floats/strings |
|
1391 | lims = [] # rebuild lims with ints/floats/strings | |
1392 | for lim in opts.l: |
|
1392 | for lim in opts.l: | |
1393 | try: |
|
1393 | try: | |
1394 | lims.append(int(lim)) |
|
1394 | lims.append(int(lim)) | |
1395 | except ValueError: |
|
1395 | except ValueError: | |
1396 | try: |
|
1396 | try: | |
1397 | lims.append(float(lim)) |
|
1397 | lims.append(float(lim)) | |
1398 | except ValueError: |
|
1398 | except ValueError: | |
1399 | lims.append(lim) |
|
1399 | lims.append(lim) | |
1400 |
|
1400 | |||
1401 | # Trap output. |
|
1401 | # Trap output. | |
1402 | stdout_trap = StringIO() |
|
1402 | stdout_trap = StringIO() | |
1403 |
|
1403 | |||
1404 | if hasattr(stats,'stream'): |
|
1404 | if hasattr(stats,'stream'): | |
1405 | # In newer versions of python, the stats object has a 'stream' |
|
1405 | # In newer versions of python, the stats object has a 'stream' | |
1406 | # attribute to write into. |
|
1406 | # attribute to write into. | |
1407 | stats.stream = stdout_trap |
|
1407 | stats.stream = stdout_trap | |
1408 | stats.print_stats(*lims) |
|
1408 | stats.print_stats(*lims) | |
1409 | else: |
|
1409 | else: | |
1410 | # For older versions, we manually redirect stdout during printing |
|
1410 | # For older versions, we manually redirect stdout during printing | |
1411 | sys_stdout = sys.stdout |
|
1411 | sys_stdout = sys.stdout | |
1412 | try: |
|
1412 | try: | |
1413 | sys.stdout = stdout_trap |
|
1413 | sys.stdout = stdout_trap | |
1414 | stats.print_stats(*lims) |
|
1414 | stats.print_stats(*lims) | |
1415 | finally: |
|
1415 | finally: | |
1416 | sys.stdout = sys_stdout |
|
1416 | sys.stdout = sys_stdout | |
1417 |
|
1417 | |||
1418 | output = stdout_trap.getvalue() |
|
1418 | output = stdout_trap.getvalue() | |
1419 | output = output.rstrip() |
|
1419 | output = output.rstrip() | |
1420 |
|
1420 | |||
1421 | page.page(output) |
|
1421 | page.page(output) | |
1422 | print sys_exit, |
|
1422 | print sys_exit, | |
1423 |
|
1423 | |||
1424 | dump_file = opts.D[0] |
|
1424 | dump_file = opts.D[0] | |
1425 | text_file = opts.T[0] |
|
1425 | text_file = opts.T[0] | |
1426 | if dump_file: |
|
1426 | if dump_file: | |
1427 | prof.dump_stats(dump_file) |
|
1427 | prof.dump_stats(dump_file) | |
1428 | print '\n*** Profile stats marshalled to file',\ |
|
1428 | print '\n*** Profile stats marshalled to file',\ | |
1429 | `dump_file`+'.',sys_exit |
|
1429 | `dump_file`+'.',sys_exit | |
1430 | if text_file: |
|
1430 | if text_file: | |
1431 | pfile = file(text_file,'w') |
|
1431 | pfile = file(text_file,'w') | |
1432 | pfile.write(output) |
|
1432 | pfile.write(output) | |
1433 | pfile.close() |
|
1433 | pfile.close() | |
1434 | print '\n*** Profile printout saved to text file',\ |
|
1434 | print '\n*** Profile printout saved to text file',\ | |
1435 | `text_file`+'.',sys_exit |
|
1435 | `text_file`+'.',sys_exit | |
1436 |
|
1436 | |||
1437 | if opts.has_key('r'): |
|
1437 | if opts.has_key('r'): | |
1438 | return stats |
|
1438 | return stats | |
1439 | else: |
|
1439 | else: | |
1440 | return None |
|
1440 | return None | |
1441 |
|
1441 | |||
1442 | @testdec.skip_doctest |
|
1442 | @testdec.skip_doctest | |
1443 | def magic_run(self, parameter_s ='',runner=None, |
|
1443 | def magic_run(self, parameter_s ='',runner=None, | |
1444 | file_finder=get_py_filename): |
|
1444 | file_finder=get_py_filename): | |
1445 | """Run the named file inside IPython as a program. |
|
1445 | """Run the named file inside IPython as a program. | |
1446 |
|
1446 | |||
1447 | Usage:\\ |
|
1447 | Usage:\\ | |
1448 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1448 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1449 |
|
1449 | |||
1450 | Parameters after the filename are passed as command-line arguments to |
|
1450 | Parameters after the filename are passed as command-line arguments to | |
1451 | the program (put in sys.argv). Then, control returns to IPython's |
|
1451 | the program (put in sys.argv). Then, control returns to IPython's | |
1452 | prompt. |
|
1452 | prompt. | |
1453 |
|
1453 | |||
1454 | This is similar to running at a system prompt:\\ |
|
1454 | This is similar to running at a system prompt:\\ | |
1455 | $ python file args\\ |
|
1455 | $ python file args\\ | |
1456 | but with the advantage of giving you IPython's tracebacks, and of |
|
1456 | but with the advantage of giving you IPython's tracebacks, and of | |
1457 | loading all variables into your interactive namespace for further use |
|
1457 | loading all variables into your interactive namespace for further use | |
1458 | (unless -p is used, see below). |
|
1458 | (unless -p is used, see below). | |
1459 |
|
1459 | |||
1460 | The file is executed in a namespace initially consisting only of |
|
1460 | The file is executed in a namespace initially consisting only of | |
1461 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1461 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1462 | sees its environment as if it were being run as a stand-alone program |
|
1462 | sees its environment as if it were being run as a stand-alone program | |
1463 | (except for sharing global objects such as previously imported |
|
1463 | (except for sharing global objects such as previously imported | |
1464 | modules). But after execution, the IPython interactive namespace gets |
|
1464 | modules). But after execution, the IPython interactive namespace gets | |
1465 | updated with all variables defined in the program (except for __name__ |
|
1465 | updated with all variables defined in the program (except for __name__ | |
1466 | and sys.argv). This allows for very convenient loading of code for |
|
1466 | and sys.argv). This allows for very convenient loading of code for | |
1467 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1467 | interactive work, while giving each program a 'clean sheet' to run in. | |
1468 |
|
1468 | |||
1469 | Options: |
|
1469 | Options: | |
1470 |
|
1470 | |||
1471 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1471 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1472 | without extension (as python does under import). This allows running |
|
1472 | without extension (as python does under import). This allows running | |
1473 | scripts and reloading the definitions in them without calling code |
|
1473 | scripts and reloading the definitions in them without calling code | |
1474 | protected by an ' if __name__ == "__main__" ' clause. |
|
1474 | protected by an ' if __name__ == "__main__" ' clause. | |
1475 |
|
1475 | |||
1476 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1476 | -i: run the file in IPython's namespace instead of an empty one. This | |
1477 | is useful if you are experimenting with code written in a text editor |
|
1477 | is useful if you are experimenting with code written in a text editor | |
1478 | which depends on variables defined interactively. |
|
1478 | which depends on variables defined interactively. | |
1479 |
|
1479 | |||
1480 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1480 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1481 | being run. This is particularly useful if IPython is being used to |
|
1481 | being run. This is particularly useful if IPython is being used to | |
1482 | run unittests, which always exit with a sys.exit() call. In such |
|
1482 | run unittests, which always exit with a sys.exit() call. In such | |
1483 | cases you are interested in the output of the test results, not in |
|
1483 | cases you are interested in the output of the test results, not in | |
1484 | seeing a traceback of the unittest module. |
|
1484 | seeing a traceback of the unittest module. | |
1485 |
|
1485 | |||
1486 | -t: print timing information at the end of the run. IPython will give |
|
1486 | -t: print timing information at the end of the run. IPython will give | |
1487 | you an estimated CPU time consumption for your script, which under |
|
1487 | you an estimated CPU time consumption for your script, which under | |
1488 | Unix uses the resource module to avoid the wraparound problems of |
|
1488 | Unix uses the resource module to avoid the wraparound problems of | |
1489 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1489 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1490 | is also given (for Windows platforms this is reported as 0.0). |
|
1490 | is also given (for Windows platforms this is reported as 0.0). | |
1491 |
|
1491 | |||
1492 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1492 | If -t is given, an additional -N<N> option can be given, where <N> | |
1493 | must be an integer indicating how many times you want the script to |
|
1493 | must be an integer indicating how many times you want the script to | |
1494 | run. The final timing report will include total and per run results. |
|
1494 | run. The final timing report will include total and per run results. | |
1495 |
|
1495 | |||
1496 | For example (testing the script uniq_stable.py): |
|
1496 | For example (testing the script uniq_stable.py): | |
1497 |
|
1497 | |||
1498 | In [1]: run -t uniq_stable |
|
1498 | In [1]: run -t uniq_stable | |
1499 |
|
1499 | |||
1500 | IPython CPU timings (estimated):\\ |
|
1500 | IPython CPU timings (estimated):\\ | |
1501 | User : 0.19597 s.\\ |
|
1501 | User : 0.19597 s.\\ | |
1502 | System: 0.0 s.\\ |
|
1502 | System: 0.0 s.\\ | |
1503 |
|
1503 | |||
1504 | In [2]: run -t -N5 uniq_stable |
|
1504 | In [2]: run -t -N5 uniq_stable | |
1505 |
|
1505 | |||
1506 | IPython CPU timings (estimated):\\ |
|
1506 | IPython CPU timings (estimated):\\ | |
1507 | Total runs performed: 5\\ |
|
1507 | Total runs performed: 5\\ | |
1508 | Times : Total Per run\\ |
|
1508 | Times : Total Per run\\ | |
1509 | User : 0.910862 s, 0.1821724 s.\\ |
|
1509 | User : 0.910862 s, 0.1821724 s.\\ | |
1510 | System: 0.0 s, 0.0 s. |
|
1510 | System: 0.0 s, 0.0 s. | |
1511 |
|
1511 | |||
1512 | -d: run your program under the control of pdb, the Python debugger. |
|
1512 | -d: run your program under the control of pdb, the Python debugger. | |
1513 | This allows you to execute your program step by step, watch variables, |
|
1513 | This allows you to execute your program step by step, watch variables, | |
1514 | etc. Internally, what IPython does is similar to calling: |
|
1514 | etc. Internally, what IPython does is similar to calling: | |
1515 |
|
1515 | |||
1516 | pdb.run('execfile("YOURFILENAME")') |
|
1516 | pdb.run('execfile("YOURFILENAME")') | |
1517 |
|
1517 | |||
1518 | with a breakpoint set on line 1 of your file. You can change the line |
|
1518 | with a breakpoint set on line 1 of your file. You can change the line | |
1519 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1519 | number for this automatic breakpoint to be <N> by using the -bN option | |
1520 | (where N must be an integer). For example: |
|
1520 | (where N must be an integer). For example: | |
1521 |
|
1521 | |||
1522 | %run -d -b40 myscript |
|
1522 | %run -d -b40 myscript | |
1523 |
|
1523 | |||
1524 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1524 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1525 | the first breakpoint must be set on a line which actually does |
|
1525 | the first breakpoint must be set on a line which actually does | |
1526 | something (not a comment or docstring) for it to stop execution. |
|
1526 | something (not a comment or docstring) for it to stop execution. | |
1527 |
|
1527 | |||
1528 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1528 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1529 | first enter 'c' (without qoutes) to start execution up to the first |
|
1529 | first enter 'c' (without qoutes) to start execution up to the first | |
1530 | breakpoint. |
|
1530 | breakpoint. | |
1531 |
|
1531 | |||
1532 | Entering 'help' gives information about the use of the debugger. You |
|
1532 | Entering 'help' gives information about the use of the debugger. You | |
1533 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1533 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1534 | at a prompt. |
|
1534 | at a prompt. | |
1535 |
|
1535 | |||
1536 | -p: run program under the control of the Python profiler module (which |
|
1536 | -p: run program under the control of the Python profiler module (which | |
1537 | prints a detailed report of execution times, function calls, etc). |
|
1537 | prints a detailed report of execution times, function calls, etc). | |
1538 |
|
1538 | |||
1539 | You can pass other options after -p which affect the behavior of the |
|
1539 | You can pass other options after -p which affect the behavior of the | |
1540 | profiler itself. See the docs for %prun for details. |
|
1540 | profiler itself. See the docs for %prun for details. | |
1541 |
|
1541 | |||
1542 | In this mode, the program's variables do NOT propagate back to the |
|
1542 | In this mode, the program's variables do NOT propagate back to the | |
1543 | IPython interactive namespace (because they remain in the namespace |
|
1543 | IPython interactive namespace (because they remain in the namespace | |
1544 | where the profiler executes them). |
|
1544 | where the profiler executes them). | |
1545 |
|
1545 | |||
1546 | Internally this triggers a call to %prun, see its documentation for |
|
1546 | Internally this triggers a call to %prun, see its documentation for | |
1547 | details on the options available specifically for profiling. |
|
1547 | details on the options available specifically for profiling. | |
1548 |
|
1548 | |||
1549 | There is one special usage for which the text above doesn't apply: |
|
1549 | There is one special usage for which the text above doesn't apply: | |
1550 | if the filename ends with .ipy, the file is run as ipython script, |
|
1550 | if the filename ends with .ipy, the file is run as ipython script, | |
1551 | just as if the commands were written on IPython prompt. |
|
1551 | just as if the commands were written on IPython prompt. | |
1552 | """ |
|
1552 | """ | |
1553 |
|
1553 | |||
1554 | # get arguments and set sys.argv for program to be run. |
|
1554 | # get arguments and set sys.argv for program to be run. | |
1555 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1555 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1556 | mode='list',list_all=1) |
|
1556 | mode='list',list_all=1) | |
1557 |
|
1557 | |||
1558 | try: |
|
1558 | try: | |
1559 | filename = file_finder(arg_lst[0]) |
|
1559 | filename = file_finder(arg_lst[0]) | |
1560 | except IndexError: |
|
1560 | except IndexError: | |
1561 | warn('you must provide at least a filename.') |
|
1561 | warn('you must provide at least a filename.') | |
1562 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1562 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1563 | return |
|
1563 | return | |
1564 | except IOError,msg: |
|
1564 | except IOError,msg: | |
1565 | error(msg) |
|
1565 | error(msg) | |
1566 | return |
|
1566 | return | |
1567 |
|
1567 | |||
1568 | if filename.lower().endswith('.ipy'): |
|
1568 | if filename.lower().endswith('.ipy'): | |
1569 | self.shell.safe_execfile_ipy(filename) |
|
1569 | self.shell.safe_execfile_ipy(filename) | |
1570 | return |
|
1570 | return | |
1571 |
|
1571 | |||
1572 | # Control the response to exit() calls made by the script being run |
|
1572 | # Control the response to exit() calls made by the script being run | |
1573 | exit_ignore = opts.has_key('e') |
|
1573 | exit_ignore = opts.has_key('e') | |
1574 |
|
1574 | |||
1575 | # Make sure that the running script gets a proper sys.argv as if it |
|
1575 | # Make sure that the running script gets a proper sys.argv as if it | |
1576 | # were run from a system shell. |
|
1576 | # were run from a system shell. | |
1577 | save_argv = sys.argv # save it for later restoring |
|
1577 | save_argv = sys.argv # save it for later restoring | |
1578 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1578 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1579 |
|
1579 | |||
1580 | if opts.has_key('i'): |
|
1580 | if opts.has_key('i'): | |
1581 | # Run in user's interactive namespace |
|
1581 | # Run in user's interactive namespace | |
1582 | prog_ns = self.shell.user_ns |
|
1582 | prog_ns = self.shell.user_ns | |
1583 | __name__save = self.shell.user_ns['__name__'] |
|
1583 | __name__save = self.shell.user_ns['__name__'] | |
1584 | prog_ns['__name__'] = '__main__' |
|
1584 | prog_ns['__name__'] = '__main__' | |
1585 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1585 | main_mod = self.shell.new_main_mod(prog_ns) | |
1586 | else: |
|
1586 | else: | |
1587 | # Run in a fresh, empty namespace |
|
1587 | # Run in a fresh, empty namespace | |
1588 | if opts.has_key('n'): |
|
1588 | if opts.has_key('n'): | |
1589 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1589 | name = os.path.splitext(os.path.basename(filename))[0] | |
1590 | else: |
|
1590 | else: | |
1591 | name = '__main__' |
|
1591 | name = '__main__' | |
1592 |
|
1592 | |||
1593 | main_mod = self.shell.new_main_mod() |
|
1593 | main_mod = self.shell.new_main_mod() | |
1594 | prog_ns = main_mod.__dict__ |
|
1594 | prog_ns = main_mod.__dict__ | |
1595 | prog_ns['__name__'] = name |
|
1595 | prog_ns['__name__'] = name | |
1596 |
|
1596 | |||
1597 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1597 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1598 | # set the __file__ global in the script's namespace |
|
1598 | # set the __file__ global in the script's namespace | |
1599 | prog_ns['__file__'] = filename |
|
1599 | prog_ns['__file__'] = filename | |
1600 |
|
1600 | |||
1601 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1601 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1602 | # that, if we overwrite __main__, we replace it at the end |
|
1602 | # that, if we overwrite __main__, we replace it at the end | |
1603 | main_mod_name = prog_ns['__name__'] |
|
1603 | main_mod_name = prog_ns['__name__'] | |
1604 |
|
1604 | |||
1605 | if main_mod_name == '__main__': |
|
1605 | if main_mod_name == '__main__': | |
1606 | restore_main = sys.modules['__main__'] |
|
1606 | restore_main = sys.modules['__main__'] | |
1607 | else: |
|
1607 | else: | |
1608 | restore_main = False |
|
1608 | restore_main = False | |
1609 |
|
1609 | |||
1610 | # This needs to be undone at the end to prevent holding references to |
|
1610 | # This needs to be undone at the end to prevent holding references to | |
1611 | # every single object ever created. |
|
1611 | # every single object ever created. | |
1612 | sys.modules[main_mod_name] = main_mod |
|
1612 | sys.modules[main_mod_name] = main_mod | |
1613 |
|
1613 | |||
1614 | try: |
|
1614 | try: | |
1615 | stats = None |
|
1615 | stats = None | |
1616 | with self.readline_no_record: |
|
1616 | with self.readline_no_record: | |
1617 | if opts.has_key('p'): |
|
1617 | if opts.has_key('p'): | |
1618 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1618 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1619 | else: |
|
1619 | else: | |
1620 | if opts.has_key('d'): |
|
1620 | if opts.has_key('d'): | |
1621 | deb = debugger.Pdb(self.shell.colors) |
|
1621 | deb = debugger.Pdb(self.shell.colors) | |
1622 | # reset Breakpoint state, which is moronically kept |
|
1622 | # reset Breakpoint state, which is moronically kept | |
1623 | # in a class |
|
1623 | # in a class | |
1624 | bdb.Breakpoint.next = 1 |
|
1624 | bdb.Breakpoint.next = 1 | |
1625 | bdb.Breakpoint.bplist = {} |
|
1625 | bdb.Breakpoint.bplist = {} | |
1626 | bdb.Breakpoint.bpbynumber = [None] |
|
1626 | bdb.Breakpoint.bpbynumber = [None] | |
1627 | # Set an initial breakpoint to stop execution |
|
1627 | # Set an initial breakpoint to stop execution | |
1628 | maxtries = 10 |
|
1628 | maxtries = 10 | |
1629 | bp = int(opts.get('b',[1])[0]) |
|
1629 | bp = int(opts.get('b',[1])[0]) | |
1630 | checkline = deb.checkline(filename,bp) |
|
1630 | checkline = deb.checkline(filename,bp) | |
1631 | if not checkline: |
|
1631 | if not checkline: | |
1632 | for bp in range(bp+1,bp+maxtries+1): |
|
1632 | for bp in range(bp+1,bp+maxtries+1): | |
1633 | if deb.checkline(filename,bp): |
|
1633 | if deb.checkline(filename,bp): | |
1634 | break |
|
1634 | break | |
1635 | else: |
|
1635 | else: | |
1636 | msg = ("\nI failed to find a valid line to set " |
|
1636 | msg = ("\nI failed to find a valid line to set " | |
1637 | "a breakpoint\n" |
|
1637 | "a breakpoint\n" | |
1638 | "after trying up to line: %s.\n" |
|
1638 | "after trying up to line: %s.\n" | |
1639 | "Please set a valid breakpoint manually " |
|
1639 | "Please set a valid breakpoint manually " | |
1640 | "with the -b option." % bp) |
|
1640 | "with the -b option." % bp) | |
1641 | error(msg) |
|
1641 | error(msg) | |
1642 | return |
|
1642 | return | |
1643 | # if we find a good linenumber, set the breakpoint |
|
1643 | # if we find a good linenumber, set the breakpoint | |
1644 | deb.do_break('%s:%s' % (filename,bp)) |
|
1644 | deb.do_break('%s:%s' % (filename,bp)) | |
1645 | # Start file run |
|
1645 | # Start file run | |
1646 | print "NOTE: Enter 'c' at the", |
|
1646 | print "NOTE: Enter 'c' at the", | |
1647 | print "%s prompt to start your script." % deb.prompt |
|
1647 | print "%s prompt to start your script." % deb.prompt | |
1648 | try: |
|
1648 | try: | |
1649 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1649 | deb.run('execfile("%s")' % filename,prog_ns) | |
1650 |
|
1650 | |||
1651 | except: |
|
1651 | except: | |
1652 | etype, value, tb = sys.exc_info() |
|
1652 | etype, value, tb = sys.exc_info() | |
1653 | # Skip three frames in the traceback: the %run one, |
|
1653 | # Skip three frames in the traceback: the %run one, | |
1654 | # one inside bdb.py, and the command-line typed by the |
|
1654 | # one inside bdb.py, and the command-line typed by the | |
1655 | # user (run by exec in pdb itself). |
|
1655 | # user (run by exec in pdb itself). | |
1656 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1656 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1657 | else: |
|
1657 | else: | |
1658 | if runner is None: |
|
1658 | if runner is None: | |
1659 | runner = self.shell.safe_execfile |
|
1659 | runner = self.shell.safe_execfile | |
1660 | if opts.has_key('t'): |
|
1660 | if opts.has_key('t'): | |
1661 | # timed execution |
|
1661 | # timed execution | |
1662 | try: |
|
1662 | try: | |
1663 | nruns = int(opts['N'][0]) |
|
1663 | nruns = int(opts['N'][0]) | |
1664 | if nruns < 1: |
|
1664 | if nruns < 1: | |
1665 | error('Number of runs must be >=1') |
|
1665 | error('Number of runs must be >=1') | |
1666 | return |
|
1666 | return | |
1667 | except (KeyError): |
|
1667 | except (KeyError): | |
1668 | nruns = 1 |
|
1668 | nruns = 1 | |
1669 | if nruns == 1: |
|
1669 | if nruns == 1: | |
1670 | t0 = clock2() |
|
1670 | t0 = clock2() | |
1671 | runner(filename,prog_ns,prog_ns, |
|
1671 | runner(filename,prog_ns,prog_ns, | |
1672 | exit_ignore=exit_ignore) |
|
1672 | exit_ignore=exit_ignore) | |
1673 | t1 = clock2() |
|
1673 | t1 = clock2() | |
1674 | t_usr = t1[0]-t0[0] |
|
1674 | t_usr = t1[0]-t0[0] | |
1675 | t_sys = t1[1]-t0[1] |
|
1675 | t_sys = t1[1]-t0[1] | |
1676 | print "\nIPython CPU timings (estimated):" |
|
1676 | print "\nIPython CPU timings (estimated):" | |
1677 | print " User : %10s s." % t_usr |
|
1677 | print " User : %10s s." % t_usr | |
1678 | print " System: %10s s." % t_sys |
|
1678 | print " System: %10s s." % t_sys | |
1679 | else: |
|
1679 | else: | |
1680 | runs = range(nruns) |
|
1680 | runs = range(nruns) | |
1681 | t0 = clock2() |
|
1681 | t0 = clock2() | |
1682 | for nr in runs: |
|
1682 | for nr in runs: | |
1683 | runner(filename,prog_ns,prog_ns, |
|
1683 | runner(filename,prog_ns,prog_ns, | |
1684 | exit_ignore=exit_ignore) |
|
1684 | exit_ignore=exit_ignore) | |
1685 | t1 = clock2() |
|
1685 | t1 = clock2() | |
1686 | t_usr = t1[0]-t0[0] |
|
1686 | t_usr = t1[0]-t0[0] | |
1687 | t_sys = t1[1]-t0[1] |
|
1687 | t_sys = t1[1]-t0[1] | |
1688 | print "\nIPython CPU timings (estimated):" |
|
1688 | print "\nIPython CPU timings (estimated):" | |
1689 | print "Total runs performed:",nruns |
|
1689 | print "Total runs performed:",nruns | |
1690 | print " Times : %10s %10s" % ('Total','Per run') |
|
1690 | print " Times : %10s %10s" % ('Total','Per run') | |
1691 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1691 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1692 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1692 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1693 |
|
1693 | |||
1694 | else: |
|
1694 | else: | |
1695 | # regular execution |
|
1695 | # regular execution | |
1696 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1696 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1697 |
|
1697 | |||
1698 | if opts.has_key('i'): |
|
1698 | if opts.has_key('i'): | |
1699 | self.shell.user_ns['__name__'] = __name__save |
|
1699 | self.shell.user_ns['__name__'] = __name__save | |
1700 | else: |
|
1700 | else: | |
1701 | # The shell MUST hold a reference to prog_ns so after %run |
|
1701 | # The shell MUST hold a reference to prog_ns so after %run | |
1702 | # exits, the python deletion mechanism doesn't zero it out |
|
1702 | # exits, the python deletion mechanism doesn't zero it out | |
1703 | # (leaving dangling references). |
|
1703 | # (leaving dangling references). | |
1704 | self.shell.cache_main_mod(prog_ns,filename) |
|
1704 | self.shell.cache_main_mod(prog_ns,filename) | |
1705 | # update IPython interactive namespace |
|
1705 | # update IPython interactive namespace | |
1706 |
|
1706 | |||
1707 | # Some forms of read errors on the file may mean the |
|
1707 | # Some forms of read errors on the file may mean the | |
1708 | # __name__ key was never set; using pop we don't have to |
|
1708 | # __name__ key was never set; using pop we don't have to | |
1709 | # worry about a possible KeyError. |
|
1709 | # worry about a possible KeyError. | |
1710 | prog_ns.pop('__name__', None) |
|
1710 | prog_ns.pop('__name__', None) | |
1711 |
|
1711 | |||
1712 | self.shell.user_ns.update(prog_ns) |
|
1712 | self.shell.user_ns.update(prog_ns) | |
1713 | finally: |
|
1713 | finally: | |
1714 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1714 | # It's a bit of a mystery why, but __builtins__ can change from | |
1715 | # being a module to becoming a dict missing some key data after |
|
1715 | # being a module to becoming a dict missing some key data after | |
1716 | # %run. As best I can see, this is NOT something IPython is doing |
|
1716 | # %run. As best I can see, this is NOT something IPython is doing | |
1717 | # at all, and similar problems have been reported before: |
|
1717 | # at all, and similar problems have been reported before: | |
1718 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1718 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1719 | # Since this seems to be done by the interpreter itself, the best |
|
1719 | # Since this seems to be done by the interpreter itself, the best | |
1720 | # we can do is to at least restore __builtins__ for the user on |
|
1720 | # we can do is to at least restore __builtins__ for the user on | |
1721 | # exit. |
|
1721 | # exit. | |
1722 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1722 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1723 |
|
1723 | |||
1724 | # Ensure key global structures are restored |
|
1724 | # Ensure key global structures are restored | |
1725 | sys.argv = save_argv |
|
1725 | sys.argv = save_argv | |
1726 | if restore_main: |
|
1726 | if restore_main: | |
1727 | sys.modules['__main__'] = restore_main |
|
1727 | sys.modules['__main__'] = restore_main | |
1728 | else: |
|
1728 | else: | |
1729 | # Remove from sys.modules the reference to main_mod we'd |
|
1729 | # Remove from sys.modules the reference to main_mod we'd | |
1730 | # added. Otherwise it will trap references to objects |
|
1730 | # added. Otherwise it will trap references to objects | |
1731 | # contained therein. |
|
1731 | # contained therein. | |
1732 | del sys.modules[main_mod_name] |
|
1732 | del sys.modules[main_mod_name] | |
1733 |
|
1733 | |||
1734 | return stats |
|
1734 | return stats | |
1735 |
|
1735 | |||
1736 | @testdec.skip_doctest |
|
1736 | @testdec.skip_doctest | |
1737 | def magic_timeit(self, parameter_s =''): |
|
1737 | def magic_timeit(self, parameter_s =''): | |
1738 | """Time execution of a Python statement or expression |
|
1738 | """Time execution of a Python statement or expression | |
1739 |
|
1739 | |||
1740 | Usage:\\ |
|
1740 | Usage:\\ | |
1741 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1741 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1742 |
|
1742 | |||
1743 | Time execution of a Python statement or expression using the timeit |
|
1743 | Time execution of a Python statement or expression using the timeit | |
1744 | module. |
|
1744 | module. | |
1745 |
|
1745 | |||
1746 | Options: |
|
1746 | Options: | |
1747 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1747 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1748 | is not given, a fitting value is chosen. |
|
1748 | is not given, a fitting value is chosen. | |
1749 |
|
1749 | |||
1750 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1750 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1751 | Default: 3 |
|
1751 | Default: 3 | |
1752 |
|
1752 | |||
1753 | -t: use time.time to measure the time, which is the default on Unix. |
|
1753 | -t: use time.time to measure the time, which is the default on Unix. | |
1754 | This function measures wall time. |
|
1754 | This function measures wall time. | |
1755 |
|
1755 | |||
1756 | -c: use time.clock to measure the time, which is the default on |
|
1756 | -c: use time.clock to measure the time, which is the default on | |
1757 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1757 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1758 | instead and returns the CPU user time. |
|
1758 | instead and returns the CPU user time. | |
1759 |
|
1759 | |||
1760 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1760 | -p<P>: use a precision of <P> digits to display the timing result. | |
1761 | Default: 3 |
|
1761 | Default: 3 | |
1762 |
|
1762 | |||
1763 |
|
1763 | |||
1764 | Examples: |
|
1764 | Examples: | |
1765 |
|
1765 | |||
1766 | In [1]: %timeit pass |
|
1766 | In [1]: %timeit pass | |
1767 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1767 | 10000000 loops, best of 3: 53.3 ns per loop | |
1768 |
|
1768 | |||
1769 | In [2]: u = None |
|
1769 | In [2]: u = None | |
1770 |
|
1770 | |||
1771 | In [3]: %timeit u is None |
|
1771 | In [3]: %timeit u is None | |
1772 | 10000000 loops, best of 3: 184 ns per loop |
|
1772 | 10000000 loops, best of 3: 184 ns per loop | |
1773 |
|
1773 | |||
1774 | In [4]: %timeit -r 4 u == None |
|
1774 | In [4]: %timeit -r 4 u == None | |
1775 | 1000000 loops, best of 4: 242 ns per loop |
|
1775 | 1000000 loops, best of 4: 242 ns per loop | |
1776 |
|
1776 | |||
1777 | In [5]: import time |
|
1777 | In [5]: import time | |
1778 |
|
1778 | |||
1779 | In [6]: %timeit -n1 time.sleep(2) |
|
1779 | In [6]: %timeit -n1 time.sleep(2) | |
1780 | 1 loops, best of 3: 2 s per loop |
|
1780 | 1 loops, best of 3: 2 s per loop | |
1781 |
|
1781 | |||
1782 |
|
1782 | |||
1783 | The times reported by %timeit will be slightly higher than those |
|
1783 | The times reported by %timeit will be slightly higher than those | |
1784 | reported by the timeit.py script when variables are accessed. This is |
|
1784 | reported by the timeit.py script when variables are accessed. This is | |
1785 | due to the fact that %timeit executes the statement in the namespace |
|
1785 | due to the fact that %timeit executes the statement in the namespace | |
1786 | of the shell, compared with timeit.py, which uses a single setup |
|
1786 | of the shell, compared with timeit.py, which uses a single setup | |
1787 | statement to import function or create variables. Generally, the bias |
|
1787 | statement to import function or create variables. Generally, the bias | |
1788 | does not matter as long as results from timeit.py are not mixed with |
|
1788 | does not matter as long as results from timeit.py are not mixed with | |
1789 | those from %timeit.""" |
|
1789 | those from %timeit.""" | |
1790 |
|
1790 | |||
1791 | import timeit |
|
1791 | import timeit | |
1792 | import math |
|
1792 | import math | |
1793 |
|
1793 | |||
1794 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1794 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1795 | # certain terminals. Until we figure out a robust way of |
|
1795 | # certain terminals. Until we figure out a robust way of | |
1796 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1796 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1797 | # microseconds. I am really NOT happy about disabling the proper |
|
1797 | # microseconds. I am really NOT happy about disabling the proper | |
1798 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1798 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1799 | # right solution for this is, I'm all ears... |
|
1799 | # right solution for this is, I'm all ears... | |
1800 | # |
|
1800 | # | |
1801 | # Note: using |
|
1801 | # Note: using | |
1802 | # |
|
1802 | # | |
1803 | # s = u'\xb5' |
|
1803 | # s = u'\xb5' | |
1804 | # s.encode(sys.getdefaultencoding()) |
|
1804 | # s.encode(sys.getdefaultencoding()) | |
1805 | # |
|
1805 | # | |
1806 | # is not sufficient, as I've seen terminals where that fails but |
|
1806 | # is not sufficient, as I've seen terminals where that fails but | |
1807 | # print s |
|
1807 | # print s | |
1808 | # |
|
1808 | # | |
1809 | # succeeds |
|
1809 | # succeeds | |
1810 | # |
|
1810 | # | |
1811 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1811 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1812 |
|
1812 | |||
1813 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1813 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1814 | units = [u"s", u"ms",u'us',"ns"] |
|
1814 | units = [u"s", u"ms",u'us',"ns"] | |
1815 |
|
1815 | |||
1816 | scaling = [1, 1e3, 1e6, 1e9] |
|
1816 | scaling = [1, 1e3, 1e6, 1e9] | |
1817 |
|
1817 | |||
1818 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1818 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1819 | posix=False) |
|
1819 | posix=False) | |
1820 | if stmt == "": |
|
1820 | if stmt == "": | |
1821 | return |
|
1821 | return | |
1822 | timefunc = timeit.default_timer |
|
1822 | timefunc = timeit.default_timer | |
1823 | number = int(getattr(opts, "n", 0)) |
|
1823 | number = int(getattr(opts, "n", 0)) | |
1824 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1824 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1825 | precision = int(getattr(opts, "p", 3)) |
|
1825 | precision = int(getattr(opts, "p", 3)) | |
1826 | if hasattr(opts, "t"): |
|
1826 | if hasattr(opts, "t"): | |
1827 | timefunc = time.time |
|
1827 | timefunc = time.time | |
1828 | if hasattr(opts, "c"): |
|
1828 | if hasattr(opts, "c"): | |
1829 | timefunc = clock |
|
1829 | timefunc = clock | |
1830 |
|
1830 | |||
1831 | timer = timeit.Timer(timer=timefunc) |
|
1831 | timer = timeit.Timer(timer=timefunc) | |
1832 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1832 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1833 | # but is there a better way to achieve that the code stmt has access |
|
1833 | # but is there a better way to achieve that the code stmt has access | |
1834 | # to the shell namespace? |
|
1834 | # to the shell namespace? | |
1835 |
|
1835 | |||
1836 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1836 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1837 | 'setup': "pass"} |
|
1837 | 'setup': "pass"} | |
1838 | # Track compilation time so it can be reported if too long |
|
1838 | # Track compilation time so it can be reported if too long | |
1839 | # Minimum time above which compilation time will be reported |
|
1839 | # Minimum time above which compilation time will be reported | |
1840 | tc_min = 0.1 |
|
1840 | tc_min = 0.1 | |
1841 |
|
1841 | |||
1842 | t0 = clock() |
|
1842 | t0 = clock() | |
1843 | code = compile(src, "<magic-timeit>", "exec") |
|
1843 | code = compile(src, "<magic-timeit>", "exec") | |
1844 | tc = clock()-t0 |
|
1844 | tc = clock()-t0 | |
1845 |
|
1845 | |||
1846 | ns = {} |
|
1846 | ns = {} | |
1847 | exec code in self.shell.user_ns, ns |
|
1847 | exec code in self.shell.user_ns, ns | |
1848 | timer.inner = ns["inner"] |
|
1848 | timer.inner = ns["inner"] | |
1849 |
|
1849 | |||
1850 | if number == 0: |
|
1850 | if number == 0: | |
1851 | # determine number so that 0.2 <= total time < 2.0 |
|
1851 | # determine number so that 0.2 <= total time < 2.0 | |
1852 | number = 1 |
|
1852 | number = 1 | |
1853 | for i in range(1, 10): |
|
1853 | for i in range(1, 10): | |
1854 | if timer.timeit(number) >= 0.2: |
|
1854 | if timer.timeit(number) >= 0.2: | |
1855 | break |
|
1855 | break | |
1856 | number *= 10 |
|
1856 | number *= 10 | |
1857 |
|
1857 | |||
1858 | best = min(timer.repeat(repeat, number)) / number |
|
1858 | best = min(timer.repeat(repeat, number)) / number | |
1859 |
|
1859 | |||
1860 | if best > 0.0 and best < 1000.0: |
|
1860 | if best > 0.0 and best < 1000.0: | |
1861 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1861 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1862 | elif best >= 1000.0: |
|
1862 | elif best >= 1000.0: | |
1863 | order = 0 |
|
1863 | order = 0 | |
1864 | else: |
|
1864 | else: | |
1865 | order = 3 |
|
1865 | order = 3 | |
1866 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1866 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1867 | precision, |
|
1867 | precision, | |
1868 | best * scaling[order], |
|
1868 | best * scaling[order], | |
1869 | units[order]) |
|
1869 | units[order]) | |
1870 | if tc > tc_min: |
|
1870 | if tc > tc_min: | |
1871 | print "Compiler time: %.2f s" % tc |
|
1871 | print "Compiler time: %.2f s" % tc | |
1872 |
|
1872 | |||
1873 | @testdec.skip_doctest |
|
1873 | @testdec.skip_doctest | |
1874 | @needs_local_scope |
|
1874 | @needs_local_scope | |
1875 | def magic_time(self,parameter_s = ''): |
|
1875 | def magic_time(self,parameter_s = ''): | |
1876 | """Time execution of a Python statement or expression. |
|
1876 | """Time execution of a Python statement or expression. | |
1877 |
|
1877 | |||
1878 | The CPU and wall clock times are printed, and the value of the |
|
1878 | The CPU and wall clock times are printed, and the value of the | |
1879 | expression (if any) is returned. Note that under Win32, system time |
|
1879 | expression (if any) is returned. Note that under Win32, system time | |
1880 | is always reported as 0, since it can not be measured. |
|
1880 | is always reported as 0, since it can not be measured. | |
1881 |
|
1881 | |||
1882 | This function provides very basic timing functionality. In Python |
|
1882 | This function provides very basic timing functionality. In Python | |
1883 | 2.3, the timeit module offers more control and sophistication, so this |
|
1883 | 2.3, the timeit module offers more control and sophistication, so this | |
1884 | could be rewritten to use it (patches welcome). |
|
1884 | could be rewritten to use it (patches welcome). | |
1885 |
|
1885 | |||
1886 | Some examples: |
|
1886 | Some examples: | |
1887 |
|
1887 | |||
1888 | In [1]: time 2**128 |
|
1888 | In [1]: time 2**128 | |
1889 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1889 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1890 | Wall time: 0.00 |
|
1890 | Wall time: 0.00 | |
1891 | Out[1]: 340282366920938463463374607431768211456L |
|
1891 | Out[1]: 340282366920938463463374607431768211456L | |
1892 |
|
1892 | |||
1893 | In [2]: n = 1000000 |
|
1893 | In [2]: n = 1000000 | |
1894 |
|
1894 | |||
1895 | In [3]: time sum(range(n)) |
|
1895 | In [3]: time sum(range(n)) | |
1896 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1896 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1897 | Wall time: 1.37 |
|
1897 | Wall time: 1.37 | |
1898 | Out[3]: 499999500000L |
|
1898 | Out[3]: 499999500000L | |
1899 |
|
1899 | |||
1900 | In [4]: time print 'hello world' |
|
1900 | In [4]: time print 'hello world' | |
1901 | hello world |
|
1901 | hello world | |
1902 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1902 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1903 | Wall time: 0.00 |
|
1903 | Wall time: 0.00 | |
1904 |
|
1904 | |||
1905 | Note that the time needed by Python to compile the given expression |
|
1905 | Note that the time needed by Python to compile the given expression | |
1906 | will be reported if it is more than 0.1s. In this example, the |
|
1906 | will be reported if it is more than 0.1s. In this example, the | |
1907 | actual exponentiation is done by Python at compilation time, so while |
|
1907 | actual exponentiation is done by Python at compilation time, so while | |
1908 | the expression can take a noticeable amount of time to compute, that |
|
1908 | the expression can take a noticeable amount of time to compute, that | |
1909 | time is purely due to the compilation: |
|
1909 | time is purely due to the compilation: | |
1910 |
|
1910 | |||
1911 | In [5]: time 3**9999; |
|
1911 | In [5]: time 3**9999; | |
1912 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1912 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1913 | Wall time: 0.00 s |
|
1913 | Wall time: 0.00 s | |
1914 |
|
1914 | |||
1915 | In [6]: time 3**999999; |
|
1915 | In [6]: time 3**999999; | |
1916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1917 | Wall time: 0.00 s |
|
1917 | Wall time: 0.00 s | |
1918 | Compiler : 0.78 s |
|
1918 | Compiler : 0.78 s | |
1919 | """ |
|
1919 | """ | |
1920 |
|
1920 | |||
1921 | # fail immediately if the given expression can't be compiled |
|
1921 | # fail immediately if the given expression can't be compiled | |
1922 |
|
1922 | |||
1923 | expr = self.shell.prefilter(parameter_s,False) |
|
1923 | expr = self.shell.prefilter(parameter_s,False) | |
1924 |
|
1924 | |||
1925 | # Minimum time above which compilation time will be reported |
|
1925 | # Minimum time above which compilation time will be reported | |
1926 | tc_min = 0.1 |
|
1926 | tc_min = 0.1 | |
1927 |
|
1927 | |||
1928 | try: |
|
1928 | try: | |
1929 | mode = 'eval' |
|
1929 | mode = 'eval' | |
1930 | t0 = clock() |
|
1930 | t0 = clock() | |
1931 | code = compile(expr,'<timed eval>',mode) |
|
1931 | code = compile(expr,'<timed eval>',mode) | |
1932 | tc = clock()-t0 |
|
1932 | tc = clock()-t0 | |
1933 | except SyntaxError: |
|
1933 | except SyntaxError: | |
1934 | mode = 'exec' |
|
1934 | mode = 'exec' | |
1935 | t0 = clock() |
|
1935 | t0 = clock() | |
1936 | code = compile(expr,'<timed exec>',mode) |
|
1936 | code = compile(expr,'<timed exec>',mode) | |
1937 | tc = clock()-t0 |
|
1937 | tc = clock()-t0 | |
1938 | # skew measurement as little as possible |
|
1938 | # skew measurement as little as possible | |
1939 | glob = self.shell.user_ns |
|
1939 | glob = self.shell.user_ns | |
1940 | locs = self._magic_locals |
|
1940 | locs = self._magic_locals | |
1941 | clk = clock2 |
|
1941 | clk = clock2 | |
1942 | wtime = time.time |
|
1942 | wtime = time.time | |
1943 | # time execution |
|
1943 | # time execution | |
1944 | wall_st = wtime() |
|
1944 | wall_st = wtime() | |
1945 | if mode=='eval': |
|
1945 | if mode=='eval': | |
1946 | st = clk() |
|
1946 | st = clk() | |
1947 | out = eval(code, glob, locs) |
|
1947 | out = eval(code, glob, locs) | |
1948 | end = clk() |
|
1948 | end = clk() | |
1949 | else: |
|
1949 | else: | |
1950 | st = clk() |
|
1950 | st = clk() | |
1951 | exec code in glob, locs |
|
1951 | exec code in glob, locs | |
1952 | end = clk() |
|
1952 | end = clk() | |
1953 | out = None |
|
1953 | out = None | |
1954 | wall_end = wtime() |
|
1954 | wall_end = wtime() | |
1955 | # Compute actual times and report |
|
1955 | # Compute actual times and report | |
1956 | wall_time = wall_end-wall_st |
|
1956 | wall_time = wall_end-wall_st | |
1957 | cpu_user = end[0]-st[0] |
|
1957 | cpu_user = end[0]-st[0] | |
1958 | cpu_sys = end[1]-st[1] |
|
1958 | cpu_sys = end[1]-st[1] | |
1959 | cpu_tot = cpu_user+cpu_sys |
|
1959 | cpu_tot = cpu_user+cpu_sys | |
1960 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1960 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1961 | (cpu_user,cpu_sys,cpu_tot) |
|
1961 | (cpu_user,cpu_sys,cpu_tot) | |
1962 | print "Wall time: %.2f s" % wall_time |
|
1962 | print "Wall time: %.2f s" % wall_time | |
1963 | if tc > tc_min: |
|
1963 | if tc > tc_min: | |
1964 | print "Compiler : %.2f s" % tc |
|
1964 | print "Compiler : %.2f s" % tc | |
1965 | return out |
|
1965 | return out | |
1966 |
|
1966 | |||
1967 | @testdec.skip_doctest |
|
1967 | @testdec.skip_doctest | |
1968 | def magic_macro(self,parameter_s = ''): |
|
1968 | def magic_macro(self,parameter_s = ''): | |
1969 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1969 | """Define a macro for future re-execution. It accepts ranges of history, | |
1970 | filenames or string objects. |
|
1970 | filenames or string objects. | |
1971 |
|
1971 | |||
1972 | Usage:\\ |
|
1972 | Usage:\\ | |
1973 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1973 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1974 |
|
1974 | |||
1975 | Options: |
|
1975 | Options: | |
1976 |
|
1976 | |||
1977 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1977 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1978 | so that magics are loaded in their transformed version to valid |
|
1978 | so that magics are loaded in their transformed version to valid | |
1979 | Python. If this option is given, the raw input as typed as the |
|
1979 | Python. If this option is given, the raw input as typed as the | |
1980 | command line is used instead. |
|
1980 | command line is used instead. | |
1981 |
|
1981 | |||
1982 | This will define a global variable called `name` which is a string |
|
1982 | This will define a global variable called `name` which is a string | |
1983 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1983 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1984 | above) from your input history into a single string. This variable |
|
1984 | above) from your input history into a single string. This variable | |
1985 | acts like an automatic function which re-executes those lines as if |
|
1985 | acts like an automatic function which re-executes those lines as if | |
1986 | you had typed them. You just type 'name' at the prompt and the code |
|
1986 | you had typed them. You just type 'name' at the prompt and the code | |
1987 | executes. |
|
1987 | executes. | |
1988 |
|
1988 | |||
1989 | The syntax for indicating input ranges is described in %history. |
|
1989 | The syntax for indicating input ranges is described in %history. | |
1990 |
|
1990 | |||
1991 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1991 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1992 | notation, where N:M means numbers N through M-1. |
|
1992 | notation, where N:M means numbers N through M-1. | |
1993 |
|
1993 | |||
1994 | For example, if your history contains (%hist prints it): |
|
1994 | For example, if your history contains (%hist prints it): | |
1995 |
|
1995 | |||
1996 | 44: x=1 |
|
1996 | 44: x=1 | |
1997 | 45: y=3 |
|
1997 | 45: y=3 | |
1998 | 46: z=x+y |
|
1998 | 46: z=x+y | |
1999 | 47: print x |
|
1999 | 47: print x | |
2000 | 48: a=5 |
|
2000 | 48: a=5 | |
2001 | 49: print 'x',x,'y',y |
|
2001 | 49: print 'x',x,'y',y | |
2002 |
|
2002 | |||
2003 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2003 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2004 | called my_macro with: |
|
2004 | called my_macro with: | |
2005 |
|
2005 | |||
2006 | In [55]: %macro my_macro 44-47 49 |
|
2006 | In [55]: %macro my_macro 44-47 49 | |
2007 |
|
2007 | |||
2008 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2008 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2009 | in one pass. |
|
2009 | in one pass. | |
2010 |
|
2010 | |||
2011 | You don't need to give the line-numbers in order, and any given line |
|
2011 | You don't need to give the line-numbers in order, and any given line | |
2012 | number can appear multiple times. You can assemble macros with any |
|
2012 | number can appear multiple times. You can assemble macros with any | |
2013 | lines from your input history in any order. |
|
2013 | lines from your input history in any order. | |
2014 |
|
2014 | |||
2015 | The macro is a simple object which holds its value in an attribute, |
|
2015 | The macro is a simple object which holds its value in an attribute, | |
2016 | but IPython's display system checks for macros and executes them as |
|
2016 | but IPython's display system checks for macros and executes them as | |
2017 | code instead of printing them when you type their name. |
|
2017 | code instead of printing them when you type their name. | |
2018 |
|
2018 | |||
2019 | You can view a macro's contents by explicitly printing it with: |
|
2019 | You can view a macro's contents by explicitly printing it with: | |
2020 |
|
2020 | |||
2021 | 'print macro_name'. |
|
2021 | 'print macro_name'. | |
2022 |
|
2022 | |||
2023 | """ |
|
2023 | """ | |
2024 |
|
2024 | |||
2025 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2025 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2026 | if not args: # List existing macros |
|
2026 | if not args: # List existing macros | |
2027 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2027 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
2028 | isinstance(v, Macro)) |
|
2028 | isinstance(v, Macro)) | |
2029 | if len(args) == 1: |
|
2029 | if len(args) == 1: | |
2030 | raise UsageError( |
|
2030 | raise UsageError( | |
2031 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2031 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2032 | name, codefrom = args[0], " ".join(args[1:]) |
|
2032 | name, codefrom = args[0], " ".join(args[1:]) | |
2033 |
|
2033 | |||
2034 | #print 'rng',ranges # dbg |
|
2034 | #print 'rng',ranges # dbg | |
2035 | try: |
|
2035 | try: | |
2036 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2036 | lines = self.shell.find_user_code(codefrom, 'r' in opts) | |
2037 | except (ValueError, TypeError) as e: |
|
2037 | except (ValueError, TypeError) as e: | |
2038 | print e.args[0] |
|
2038 | print e.args[0] | |
2039 | return |
|
2039 | return | |
2040 | macro = Macro(lines) |
|
2040 | macro = Macro(lines) | |
2041 | self.shell.define_macro(name, macro) |
|
2041 | self.shell.define_macro(name, macro) | |
2042 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2042 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2043 | print '=== Macro contents: ===' |
|
2043 | print '=== Macro contents: ===' | |
2044 | print macro, |
|
2044 | print macro, | |
2045 |
|
2045 | |||
2046 | def magic_save(self,parameter_s = ''): |
|
2046 | def magic_save(self,parameter_s = ''): | |
2047 | """Save a set of lines or a macro to a given filename. |
|
2047 | """Save a set of lines or a macro to a given filename. | |
2048 |
|
2048 | |||
2049 | Usage:\\ |
|
2049 | Usage:\\ | |
2050 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2050 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2051 |
|
2051 | |||
2052 | Options: |
|
2052 | Options: | |
2053 |
|
2053 | |||
2054 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2054 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2055 | so that magics are loaded in their transformed version to valid |
|
2055 | so that magics are loaded in their transformed version to valid | |
2056 | Python. If this option is given, the raw input as typed as the |
|
2056 | Python. If this option is given, the raw input as typed as the | |
2057 | command line is used instead. |
|
2057 | command line is used instead. | |
2058 |
|
2058 | |||
2059 | This function uses the same syntax as %history for input ranges, |
|
2059 | This function uses the same syntax as %history for input ranges, | |
2060 | then saves the lines to the filename you specify. |
|
2060 | then saves the lines to the filename you specify. | |
2061 |
|
2061 | |||
2062 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2062 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2063 | it asks for confirmation before overwriting existing files.""" |
|
2063 | it asks for confirmation before overwriting existing files.""" | |
2064 |
|
2064 | |||
2065 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2065 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2066 | fname, codefrom = args[0], " ".join(args[1:]) |
|
2066 | fname, codefrom = args[0], " ".join(args[1:]) | |
2067 | if not fname.endswith('.py'): |
|
2067 | if not fname.endswith('.py'): | |
2068 | fname += '.py' |
|
2068 | fname += '.py' | |
2069 | if os.path.isfile(fname): |
|
2069 | if os.path.isfile(fname): | |
2070 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2070 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2071 | if ans.lower() not in ['y','yes']: |
|
2071 | if ans.lower() not in ['y','yes']: | |
2072 | print 'Operation cancelled.' |
|
2072 | print 'Operation cancelled.' | |
2073 | return |
|
2073 | return | |
2074 | try: |
|
2074 | try: | |
2075 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2075 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) | |
2076 | except (TypeError, ValueError) as e: |
|
2076 | except (TypeError, ValueError) as e: | |
2077 | print e.args[0] |
|
2077 | print e.args[0] | |
2078 | return |
|
2078 | return | |
2079 | if isinstance(cmds, unicode): |
|
2079 | if isinstance(cmds, unicode): | |
2080 | cmds = cmds.encode("utf-8") |
|
2080 | cmds = cmds.encode("utf-8") | |
2081 | with open(fname,'w') as f: |
|
2081 | with open(fname,'w') as f: | |
2082 | f.write("# coding: utf-8\n") |
|
2082 | f.write("# coding: utf-8\n") | |
2083 | f.write(cmds) |
|
2083 | f.write(cmds) | |
2084 | print 'The following commands were written to file `%s`:' % fname |
|
2084 | print 'The following commands were written to file `%s`:' % fname | |
2085 | print cmds |
|
2085 | print cmds | |
2086 |
|
2086 | |||
2087 | def magic_pastebin(self, parameter_s = ''): |
|
2087 | def magic_pastebin(self, parameter_s = ''): | |
2088 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" |
|
2088 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" | |
2089 | try: |
|
2089 | try: | |
2090 | code = self.shell.find_user_code(parameter_s) |
|
2090 | code = self.shell.find_user_code(parameter_s) | |
2091 | except (ValueError, TypeError) as e: |
|
2091 | except (ValueError, TypeError) as e: | |
2092 | print e.args[0] |
|
2092 | print e.args[0] | |
2093 | return |
|
2093 | return | |
2094 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') |
|
2094 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') | |
2095 | id = pbserver.pastes.newPaste("python", code) |
|
2095 | id = pbserver.pastes.newPaste("python", code) | |
2096 | return "http://paste.pocoo.org/show/" + id |
|
2096 | return "http://paste.pocoo.org/show/" + id | |
2097 |
|
2097 | |||
2098 | def _edit_macro(self,mname,macro): |
|
2098 | def _edit_macro(self,mname,macro): | |
2099 | """open an editor with the macro data in a file""" |
|
2099 | """open an editor with the macro data in a file""" | |
2100 | filename = self.shell.mktempfile(macro.value) |
|
2100 | filename = self.shell.mktempfile(macro.value) | |
2101 | self.shell.hooks.editor(filename) |
|
2101 | self.shell.hooks.editor(filename) | |
2102 |
|
2102 | |||
2103 | # and make a new macro object, to replace the old one |
|
2103 | # and make a new macro object, to replace the old one | |
2104 | mfile = open(filename) |
|
2104 | mfile = open(filename) | |
2105 | mvalue = mfile.read() |
|
2105 | mvalue = mfile.read() | |
2106 | mfile.close() |
|
2106 | mfile.close() | |
2107 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2107 | self.shell.user_ns[mname] = Macro(mvalue) | |
2108 |
|
2108 | |||
2109 | def magic_ed(self,parameter_s=''): |
|
2109 | def magic_ed(self,parameter_s=''): | |
2110 | """Alias to %edit.""" |
|
2110 | """Alias to %edit.""" | |
2111 | return self.magic_edit(parameter_s) |
|
2111 | return self.magic_edit(parameter_s) | |
2112 |
|
2112 | |||
2113 | @testdec.skip_doctest |
|
2113 | @testdec.skip_doctest | |
2114 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2114 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2115 | """Bring up an editor and execute the resulting code. |
|
2115 | """Bring up an editor and execute the resulting code. | |
2116 |
|
2116 | |||
2117 | Usage: |
|
2117 | Usage: | |
2118 | %edit [options] [args] |
|
2118 | %edit [options] [args] | |
2119 |
|
2119 | |||
2120 | %edit runs IPython's editor hook. The default version of this hook is |
|
2120 | %edit runs IPython's editor hook. The default version of this hook is | |
2121 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2121 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2122 | environment variable $EDITOR. If this isn't found, it will default to |
|
2122 | environment variable $EDITOR. If this isn't found, it will default to | |
2123 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2123 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2124 | docstring for how to change the editor hook. |
|
2124 | docstring for how to change the editor hook. | |
2125 |
|
2125 | |||
2126 | You can also set the value of this editor via the command line option |
|
2126 | You can also set the value of this editor via the command line option | |
2127 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2127 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2128 | specifically for IPython an editor different from your typical default |
|
2128 | specifically for IPython an editor different from your typical default | |
2129 | (and for Windows users who typically don't set environment variables). |
|
2129 | (and for Windows users who typically don't set environment variables). | |
2130 |
|
2130 | |||
2131 | This command allows you to conveniently edit multi-line code right in |
|
2131 | This command allows you to conveniently edit multi-line code right in | |
2132 | your IPython session. |
|
2132 | your IPython session. | |
2133 |
|
2133 | |||
2134 | If called without arguments, %edit opens up an empty editor with a |
|
2134 | If called without arguments, %edit opens up an empty editor with a | |
2135 | temporary file and will execute the contents of this file when you |
|
2135 | temporary file and will execute the contents of this file when you | |
2136 | close it (don't forget to save it!). |
|
2136 | close it (don't forget to save it!). | |
2137 |
|
2137 | |||
2138 |
|
2138 | |||
2139 | Options: |
|
2139 | Options: | |
2140 |
|
2140 | |||
2141 | -n <number>: open the editor at a specified line number. By default, |
|
2141 | -n <number>: open the editor at a specified line number. By default, | |
2142 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2142 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2143 | you can configure this by providing your own modified hook if your |
|
2143 | you can configure this by providing your own modified hook if your | |
2144 | favorite editor supports line-number specifications with a different |
|
2144 | favorite editor supports line-number specifications with a different | |
2145 | syntax. |
|
2145 | syntax. | |
2146 |
|
2146 | |||
2147 | -p: this will call the editor with the same data as the previous time |
|
2147 | -p: this will call the editor with the same data as the previous time | |
2148 | it was used, regardless of how long ago (in your current session) it |
|
2148 | it was used, regardless of how long ago (in your current session) it | |
2149 | was. |
|
2149 | was. | |
2150 |
|
2150 | |||
2151 | -r: use 'raw' input. This option only applies to input taken from the |
|
2151 | -r: use 'raw' input. This option only applies to input taken from the | |
2152 | user's history. By default, the 'processed' history is used, so that |
|
2152 | user's history. By default, the 'processed' history is used, so that | |
2153 | magics are loaded in their transformed version to valid Python. If |
|
2153 | magics are loaded in their transformed version to valid Python. If | |
2154 | this option is given, the raw input as typed as the command line is |
|
2154 | this option is given, the raw input as typed as the command line is | |
2155 | used instead. When you exit the editor, it will be executed by |
|
2155 | used instead. When you exit the editor, it will be executed by | |
2156 | IPython's own processor. |
|
2156 | IPython's own processor. | |
2157 |
|
2157 | |||
2158 | -x: do not execute the edited code immediately upon exit. This is |
|
2158 | -x: do not execute the edited code immediately upon exit. This is | |
2159 | mainly useful if you are editing programs which need to be called with |
|
2159 | mainly useful if you are editing programs which need to be called with | |
2160 | command line arguments, which you can then do using %run. |
|
2160 | command line arguments, which you can then do using %run. | |
2161 |
|
2161 | |||
2162 |
|
2162 | |||
2163 | Arguments: |
|
2163 | Arguments: | |
2164 |
|
2164 | |||
2165 | If arguments are given, the following possibilites exist: |
|
2165 | If arguments are given, the following possibilites exist: | |
2166 |
|
2166 | |||
2167 | - If the argument is a filename, IPython will load that into the |
|
2167 | - If the argument is a filename, IPython will load that into the | |
2168 | editor. It will execute its contents with execfile() when you exit, |
|
2168 | editor. It will execute its contents with execfile() when you exit, | |
2169 | loading any code in the file into your interactive namespace. |
|
2169 | loading any code in the file into your interactive namespace. | |
2170 |
|
2170 | |||
2171 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
2171 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
2172 | The syntax is the same as in the %history magic. |
|
2172 | The syntax is the same as in the %history magic. | |
2173 |
|
2173 | |||
2174 | - If the argument is a string variable, its contents are loaded |
|
2174 | - If the argument is a string variable, its contents are loaded | |
2175 | into the editor. You can thus edit any string which contains |
|
2175 | into the editor. You can thus edit any string which contains | |
2176 | python code (including the result of previous edits). |
|
2176 | python code (including the result of previous edits). | |
2177 |
|
2177 | |||
2178 | - If the argument is the name of an object (other than a string), |
|
2178 | - If the argument is the name of an object (other than a string), | |
2179 | IPython will try to locate the file where it was defined and open the |
|
2179 | IPython will try to locate the file where it was defined and open the | |
2180 | editor at the point where it is defined. You can use `%edit function` |
|
2180 | editor at the point where it is defined. You can use `%edit function` | |
2181 | to load an editor exactly at the point where 'function' is defined, |
|
2181 | to load an editor exactly at the point where 'function' is defined, | |
2182 | edit it and have the file be executed automatically. |
|
2182 | edit it and have the file be executed automatically. | |
2183 |
|
2183 | |||
2184 | If the object is a macro (see %macro for details), this opens up your |
|
2184 | If the object is a macro (see %macro for details), this opens up your | |
2185 | specified editor with a temporary file containing the macro's data. |
|
2185 | specified editor with a temporary file containing the macro's data. | |
2186 | Upon exit, the macro is reloaded with the contents of the file. |
|
2186 | Upon exit, the macro is reloaded with the contents of the file. | |
2187 |
|
2187 | |||
2188 | Note: opening at an exact line is only supported under Unix, and some |
|
2188 | Note: opening at an exact line is only supported under Unix, and some | |
2189 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2189 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2190 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2190 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2191 | (X)Emacs, vi, jed, pico and joe all do. |
|
2191 | (X)Emacs, vi, jed, pico and joe all do. | |
2192 |
|
2192 | |||
2193 | After executing your code, %edit will return as output the code you |
|
2193 | After executing your code, %edit will return as output the code you | |
2194 | typed in the editor (except when it was an existing file). This way |
|
2194 | typed in the editor (except when it was an existing file). This way | |
2195 | you can reload the code in further invocations of %edit as a variable, |
|
2195 | you can reload the code in further invocations of %edit as a variable, | |
2196 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2196 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2197 | the output. |
|
2197 | the output. | |
2198 |
|
2198 | |||
2199 | Note that %edit is also available through the alias %ed. |
|
2199 | Note that %edit is also available through the alias %ed. | |
2200 |
|
2200 | |||
2201 | This is an example of creating a simple function inside the editor and |
|
2201 | This is an example of creating a simple function inside the editor and | |
2202 | then modifying it. First, start up the editor: |
|
2202 | then modifying it. First, start up the editor: | |
2203 |
|
2203 | |||
2204 | In [1]: ed |
|
2204 | In [1]: ed | |
2205 | Editing... done. Executing edited code... |
|
2205 | Editing... done. Executing edited code... | |
2206 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2206 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2207 |
|
2207 | |||
2208 | We can then call the function foo(): |
|
2208 | We can then call the function foo(): | |
2209 |
|
2209 | |||
2210 | In [2]: foo() |
|
2210 | In [2]: foo() | |
2211 | foo() was defined in an editing session |
|
2211 | foo() was defined in an editing session | |
2212 |
|
2212 | |||
2213 | Now we edit foo. IPython automatically loads the editor with the |
|
2213 | Now we edit foo. IPython automatically loads the editor with the | |
2214 | (temporary) file where foo() was previously defined: |
|
2214 | (temporary) file where foo() was previously defined: | |
2215 |
|
2215 | |||
2216 | In [3]: ed foo |
|
2216 | In [3]: ed foo | |
2217 | Editing... done. Executing edited code... |
|
2217 | Editing... done. Executing edited code... | |
2218 |
|
2218 | |||
2219 | And if we call foo() again we get the modified version: |
|
2219 | And if we call foo() again we get the modified version: | |
2220 |
|
2220 | |||
2221 | In [4]: foo() |
|
2221 | In [4]: foo() | |
2222 | foo() has now been changed! |
|
2222 | foo() has now been changed! | |
2223 |
|
2223 | |||
2224 | Here is an example of how to edit a code snippet successive |
|
2224 | Here is an example of how to edit a code snippet successive | |
2225 | times. First we call the editor: |
|
2225 | times. First we call the editor: | |
2226 |
|
2226 | |||
2227 | In [5]: ed |
|
2227 | In [5]: ed | |
2228 | Editing... done. Executing edited code... |
|
2228 | Editing... done. Executing edited code... | |
2229 | hello |
|
2229 | hello | |
2230 | Out[5]: "print 'hello'n" |
|
2230 | Out[5]: "print 'hello'n" | |
2231 |
|
2231 | |||
2232 | Now we call it again with the previous output (stored in _): |
|
2232 | Now we call it again with the previous output (stored in _): | |
2233 |
|
2233 | |||
2234 | In [6]: ed _ |
|
2234 | In [6]: ed _ | |
2235 | Editing... done. Executing edited code... |
|
2235 | Editing... done. Executing edited code... | |
2236 | hello world |
|
2236 | hello world | |
2237 | Out[6]: "print 'hello world'n" |
|
2237 | Out[6]: "print 'hello world'n" | |
2238 |
|
2238 | |||
2239 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2239 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2240 |
|
2240 | |||
2241 | In [7]: ed _8 |
|
2241 | In [7]: ed _8 | |
2242 | Editing... done. Executing edited code... |
|
2242 | Editing... done. Executing edited code... | |
2243 | hello again |
|
2243 | hello again | |
2244 | Out[7]: "print 'hello again'n" |
|
2244 | Out[7]: "print 'hello again'n" | |
2245 |
|
2245 | |||
2246 |
|
2246 | |||
2247 | Changing the default editor hook: |
|
2247 | Changing the default editor hook: | |
2248 |
|
2248 | |||
2249 | If you wish to write your own editor hook, you can put it in a |
|
2249 | If you wish to write your own editor hook, you can put it in a | |
2250 | configuration file which you load at startup time. The default hook |
|
2250 | configuration file which you load at startup time. The default hook | |
2251 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2251 | is defined in the IPython.core.hooks module, and you can use that as a | |
2252 | starting example for further modifications. That file also has |
|
2252 | starting example for further modifications. That file also has | |
2253 | general instructions on how to set a new hook for use once you've |
|
2253 | general instructions on how to set a new hook for use once you've | |
2254 | defined it.""" |
|
2254 | defined it.""" | |
2255 |
|
2255 | |||
2256 | # FIXME: This function has become a convoluted mess. It needs a |
|
2256 | # FIXME: This function has become a convoluted mess. It needs a | |
2257 | # ground-up rewrite with clean, simple logic. |
|
2257 | # ground-up rewrite with clean, simple logic. | |
2258 |
|
2258 | |||
2259 | def make_filename(arg): |
|
2259 | def make_filename(arg): | |
2260 | "Make a filename from the given args" |
|
2260 | "Make a filename from the given args" | |
2261 | try: |
|
2261 | try: | |
2262 | filename = get_py_filename(arg) |
|
2262 | filename = get_py_filename(arg) | |
2263 | except IOError: |
|
2263 | except IOError: | |
2264 | if args.endswith('.py'): |
|
2264 | if args.endswith('.py'): | |
2265 | filename = arg |
|
2265 | filename = arg | |
2266 | else: |
|
2266 | else: | |
2267 | filename = None |
|
2267 | filename = None | |
2268 | return filename |
|
2268 | return filename | |
2269 |
|
2269 | |||
2270 | # custom exceptions |
|
2270 | # custom exceptions | |
2271 | class DataIsObject(Exception): pass |
|
2271 | class DataIsObject(Exception): pass | |
2272 |
|
2272 | |||
2273 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2273 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2274 | # Set a few locals from the options for convenience: |
|
2274 | # Set a few locals from the options for convenience: | |
2275 | opts_prev = 'p' in opts |
|
2275 | opts_prev = 'p' in opts | |
2276 | opts_raw = 'r' in opts |
|
2276 | opts_raw = 'r' in opts | |
2277 |
|
2277 | |||
2278 | # Default line number value |
|
2278 | # Default line number value | |
2279 | lineno = opts.get('n',None) |
|
2279 | lineno = opts.get('n',None) | |
2280 |
|
2280 | |||
2281 | if opts_prev: |
|
2281 | if opts_prev: | |
2282 | args = '_%s' % last_call[0] |
|
2282 | args = '_%s' % last_call[0] | |
2283 | if not self.shell.user_ns.has_key(args): |
|
2283 | if not self.shell.user_ns.has_key(args): | |
2284 | args = last_call[1] |
|
2284 | args = last_call[1] | |
2285 |
|
2285 | |||
2286 | # use last_call to remember the state of the previous call, but don't |
|
2286 | # use last_call to remember the state of the previous call, but don't | |
2287 | # let it be clobbered by successive '-p' calls. |
|
2287 | # let it be clobbered by successive '-p' calls. | |
2288 | try: |
|
2288 | try: | |
2289 | last_call[0] = self.shell.displayhook.prompt_count |
|
2289 | last_call[0] = self.shell.displayhook.prompt_count | |
2290 | if not opts_prev: |
|
2290 | if not opts_prev: | |
2291 | last_call[1] = parameter_s |
|
2291 | last_call[1] = parameter_s | |
2292 | except: |
|
2292 | except: | |
2293 | pass |
|
2293 | pass | |
2294 |
|
2294 | |||
2295 | # by default this is done with temp files, except when the given |
|
2295 | # by default this is done with temp files, except when the given | |
2296 | # arg is a filename |
|
2296 | # arg is a filename | |
2297 | use_temp = True |
|
2297 | use_temp = True | |
2298 |
|
2298 | |||
2299 | data = '' |
|
2299 | data = '' | |
2300 | if args.endswith('.py'): |
|
2300 | if args.endswith('.py'): | |
2301 | filename = make_filename(args) |
|
2301 | filename = make_filename(args) | |
2302 | use_temp = False |
|
2302 | use_temp = False | |
2303 | elif args: |
|
2303 | elif args: | |
2304 | # Mode where user specifies ranges of lines, like in %macro. |
|
2304 | # Mode where user specifies ranges of lines, like in %macro. | |
2305 | data = self.extract_input_lines(args, opts_raw) |
|
2305 | data = self.extract_input_lines(args, opts_raw) | |
2306 | if not data: |
|
2306 | if not data: | |
2307 | try: |
|
2307 | try: | |
2308 | # Load the parameter given as a variable. If not a string, |
|
2308 | # Load the parameter given as a variable. If not a string, | |
2309 | # process it as an object instead (below) |
|
2309 | # process it as an object instead (below) | |
2310 |
|
2310 | |||
2311 | #print '*** args',args,'type',type(args) # dbg |
|
2311 | #print '*** args',args,'type',type(args) # dbg | |
2312 | data = eval(args, self.shell.user_ns) |
|
2312 | data = eval(args, self.shell.user_ns) | |
2313 | if not isinstance(data, basestring): |
|
2313 | if not isinstance(data, basestring): | |
2314 | raise DataIsObject |
|
2314 | raise DataIsObject | |
2315 |
|
2315 | |||
2316 | except (NameError,SyntaxError): |
|
2316 | except (NameError,SyntaxError): | |
2317 | # given argument is not a variable, try as a filename |
|
2317 | # given argument is not a variable, try as a filename | |
2318 | filename = make_filename(args) |
|
2318 | filename = make_filename(args) | |
2319 | if filename is None: |
|
2319 | if filename is None: | |
2320 | warn("Argument given (%s) can't be found as a variable " |
|
2320 | warn("Argument given (%s) can't be found as a variable " | |
2321 | "or as a filename." % args) |
|
2321 | "or as a filename." % args) | |
2322 | return |
|
2322 | return | |
2323 | use_temp = False |
|
2323 | use_temp = False | |
2324 |
|
2324 | |||
2325 | except DataIsObject: |
|
2325 | except DataIsObject: | |
2326 | # macros have a special edit function |
|
2326 | # macros have a special edit function | |
2327 | if isinstance(data, Macro): |
|
2327 | if isinstance(data, Macro): | |
2328 | self._edit_macro(args,data) |
|
2328 | self._edit_macro(args,data) | |
2329 | return |
|
2329 | return | |
2330 |
|
2330 | |||
2331 | # For objects, try to edit the file where they are defined |
|
2331 | # For objects, try to edit the file where they are defined | |
2332 | try: |
|
2332 | try: | |
2333 | filename = inspect.getabsfile(data) |
|
2333 | filename = inspect.getabsfile(data) | |
2334 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2334 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2335 | # class created by %edit? Try to find source |
|
2335 | # class created by %edit? Try to find source | |
2336 | # by looking for method definitions instead, the |
|
2336 | # by looking for method definitions instead, the | |
2337 | # __module__ in those classes is FakeModule. |
|
2337 | # __module__ in those classes is FakeModule. | |
2338 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2338 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2339 | for attr in attrs: |
|
2339 | for attr in attrs: | |
2340 | if not inspect.ismethod(attr): |
|
2340 | if not inspect.ismethod(attr): | |
2341 | continue |
|
2341 | continue | |
2342 | filename = inspect.getabsfile(attr) |
|
2342 | filename = inspect.getabsfile(attr) | |
2343 | if filename and 'fakemodule' not in filename.lower(): |
|
2343 | if filename and 'fakemodule' not in filename.lower(): | |
2344 | # change the attribute to be the edit target instead |
|
2344 | # change the attribute to be the edit target instead | |
2345 | data = attr |
|
2345 | data = attr | |
2346 | break |
|
2346 | break | |
2347 |
|
2347 | |||
2348 | datafile = 1 |
|
2348 | datafile = 1 | |
2349 | except TypeError: |
|
2349 | except TypeError: | |
2350 | filename = make_filename(args) |
|
2350 | filename = make_filename(args) | |
2351 | datafile = 1 |
|
2351 | datafile = 1 | |
2352 | warn('Could not find file where `%s` is defined.\n' |
|
2352 | warn('Could not find file where `%s` is defined.\n' | |
2353 | 'Opening a file named `%s`' % (args,filename)) |
|
2353 | 'Opening a file named `%s`' % (args,filename)) | |
2354 | # Now, make sure we can actually read the source (if it was in |
|
2354 | # Now, make sure we can actually read the source (if it was in | |
2355 | # a temp file it's gone by now). |
|
2355 | # a temp file it's gone by now). | |
2356 | if datafile: |
|
2356 | if datafile: | |
2357 | try: |
|
2357 | try: | |
2358 | if lineno is None: |
|
2358 | if lineno is None: | |
2359 | lineno = inspect.getsourcelines(data)[1] |
|
2359 | lineno = inspect.getsourcelines(data)[1] | |
2360 | except IOError: |
|
2360 | except IOError: | |
2361 | filename = make_filename(args) |
|
2361 | filename = make_filename(args) | |
2362 | if filename is None: |
|
2362 | if filename is None: | |
2363 | warn('The file `%s` where `%s` was defined cannot ' |
|
2363 | warn('The file `%s` where `%s` was defined cannot ' | |
2364 | 'be read.' % (filename,data)) |
|
2364 | 'be read.' % (filename,data)) | |
2365 | return |
|
2365 | return | |
2366 | use_temp = False |
|
2366 | use_temp = False | |
2367 |
|
2367 | |||
2368 | if use_temp: |
|
2368 | if use_temp: | |
2369 | filename = self.shell.mktempfile(data) |
|
2369 | filename = self.shell.mktempfile(data) | |
2370 | print 'IPython will make a temporary file named:',filename |
|
2370 | print 'IPython will make a temporary file named:',filename | |
2371 |
|
2371 | |||
2372 | # do actual editing here |
|
2372 | # do actual editing here | |
2373 | print 'Editing...', |
|
2373 | print 'Editing...', | |
2374 | sys.stdout.flush() |
|
2374 | sys.stdout.flush() | |
2375 | try: |
|
2375 | try: | |
2376 | # Quote filenames that may have spaces in them |
|
2376 | # Quote filenames that may have spaces in them | |
2377 | if ' ' in filename: |
|
2377 | if ' ' in filename: | |
2378 | filename = "%s" % filename |
|
2378 | filename = "%s" % filename | |
2379 | self.shell.hooks.editor(filename,lineno) |
|
2379 | self.shell.hooks.editor(filename,lineno) | |
2380 | except TryNext: |
|
2380 | except TryNext: | |
2381 | warn('Could not open editor') |
|
2381 | warn('Could not open editor') | |
2382 | return |
|
2382 | return | |
2383 |
|
2383 | |||
2384 | # XXX TODO: should this be generalized for all string vars? |
|
2384 | # XXX TODO: should this be generalized for all string vars? | |
2385 | # For now, this is special-cased to blocks created by cpaste |
|
2385 | # For now, this is special-cased to blocks created by cpaste | |
2386 | if args.strip() == 'pasted_block': |
|
2386 | if args.strip() == 'pasted_block': | |
2387 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2387 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2388 |
|
2388 | |||
2389 | if 'x' in opts: # -x prevents actual execution |
|
2389 | if 'x' in opts: # -x prevents actual execution | |
2390 |
|
2390 | |||
2391 | else: |
|
2391 | else: | |
2392 | print 'done. Executing edited code...' |
|
2392 | print 'done. Executing edited code...' | |
2393 | if opts_raw: |
|
2393 | if opts_raw: | |
2394 | self.shell.run_cell(file_read(filename), |
|
2394 | self.shell.run_cell(file_read(filename), | |
2395 | store_history=False) |
|
2395 | store_history=False) | |
2396 | else: |
|
2396 | else: | |
2397 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2397 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2398 | self.shell.user_ns) |
|
2398 | self.shell.user_ns) | |
2399 |
|
2399 | |||
2400 |
|
2400 | |||
2401 | if use_temp: |
|
2401 | if use_temp: | |
2402 | try: |
|
2402 | try: | |
2403 | return open(filename).read() |
|
2403 | return open(filename).read() | |
2404 | except IOError,msg: |
|
2404 | except IOError,msg: | |
2405 | if msg.filename == filename: |
|
2405 | if msg.filename == filename: | |
2406 | warn('File not found. Did you forget to save?') |
|
2406 | warn('File not found. Did you forget to save?') | |
2407 | return |
|
2407 | return | |
2408 | else: |
|
2408 | else: | |
2409 | self.shell.showtraceback() |
|
2409 | self.shell.showtraceback() | |
2410 |
|
2410 | |||
2411 | def magic_xmode(self,parameter_s = ''): |
|
2411 | def magic_xmode(self,parameter_s = ''): | |
2412 | """Switch modes for the exception handlers. |
|
2412 | """Switch modes for the exception handlers. | |
2413 |
|
2413 | |||
2414 | Valid modes: Plain, Context and Verbose. |
|
2414 | Valid modes: Plain, Context and Verbose. | |
2415 |
|
2415 | |||
2416 | If called without arguments, acts as a toggle.""" |
|
2416 | If called without arguments, acts as a toggle.""" | |
2417 |
|
2417 | |||
2418 | def xmode_switch_err(name): |
|
2418 | def xmode_switch_err(name): | |
2419 | warn('Error changing %s exception modes.\n%s' % |
|
2419 | warn('Error changing %s exception modes.\n%s' % | |
2420 | (name,sys.exc_info()[1])) |
|
2420 | (name,sys.exc_info()[1])) | |
2421 |
|
2421 | |||
2422 | shell = self.shell |
|
2422 | shell = self.shell | |
2423 | new_mode = parameter_s.strip().capitalize() |
|
2423 | new_mode = parameter_s.strip().capitalize() | |
2424 | try: |
|
2424 | try: | |
2425 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2425 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2426 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2426 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2427 | except: |
|
2427 | except: | |
2428 | xmode_switch_err('user') |
|
2428 | xmode_switch_err('user') | |
2429 |
|
2429 | |||
2430 | def magic_colors(self,parameter_s = ''): |
|
2430 | def magic_colors(self,parameter_s = ''): | |
2431 | """Switch color scheme for prompts, info system and exception handlers. |
|
2431 | """Switch color scheme for prompts, info system and exception handlers. | |
2432 |
|
2432 | |||
2433 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2433 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2434 |
|
2434 | |||
2435 | Color scheme names are not case-sensitive. |
|
2435 | Color scheme names are not case-sensitive. | |
2436 |
|
2436 | |||
2437 | Examples |
|
2437 | Examples | |
2438 | -------- |
|
2438 | -------- | |
2439 | To get a plain black and white terminal:: |
|
2439 | To get a plain black and white terminal:: | |
2440 |
|
2440 | |||
2441 | %colors nocolor |
|
2441 | %colors nocolor | |
2442 | """ |
|
2442 | """ | |
2443 |
|
2443 | |||
2444 | def color_switch_err(name): |
|
2444 | def color_switch_err(name): | |
2445 | warn('Error changing %s color schemes.\n%s' % |
|
2445 | warn('Error changing %s color schemes.\n%s' % | |
2446 | (name,sys.exc_info()[1])) |
|
2446 | (name,sys.exc_info()[1])) | |
2447 |
|
2447 | |||
2448 |
|
2448 | |||
2449 | new_scheme = parameter_s.strip() |
|
2449 | new_scheme = parameter_s.strip() | |
2450 | if not new_scheme: |
|
2450 | if not new_scheme: | |
2451 | raise UsageError( |
|
2451 | raise UsageError( | |
2452 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2452 | "%colors: you must specify a color scheme. See '%colors?'") | |
2453 | return |
|
2453 | return | |
2454 | # local shortcut |
|
2454 | # local shortcut | |
2455 | shell = self.shell |
|
2455 | shell = self.shell | |
2456 |
|
2456 | |||
2457 | import IPython.utils.rlineimpl as readline |
|
2457 | import IPython.utils.rlineimpl as readline | |
2458 |
|
2458 | |||
2459 | if not readline.have_readline and sys.platform == "win32": |
|
2459 | if not readline.have_readline and sys.platform == "win32": | |
2460 | msg = """\ |
|
2460 | msg = """\ | |
2461 | Proper color support under MS Windows requires the pyreadline library. |
|
2461 | Proper color support under MS Windows requires the pyreadline library. | |
2462 | You can find it at: |
|
2462 | You can find it at: | |
2463 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2463 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2464 | Gary's readline needs the ctypes module, from: |
|
2464 | Gary's readline needs the ctypes module, from: | |
2465 | http://starship.python.net/crew/theller/ctypes |
|
2465 | http://starship.python.net/crew/theller/ctypes | |
2466 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2466 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2467 |
|
2467 | |||
2468 | Defaulting color scheme to 'NoColor'""" |
|
2468 | Defaulting color scheme to 'NoColor'""" | |
2469 | new_scheme = 'NoColor' |
|
2469 | new_scheme = 'NoColor' | |
2470 | warn(msg) |
|
2470 | warn(msg) | |
2471 |
|
2471 | |||
2472 | # readline option is 0 |
|
2472 | # readline option is 0 | |
2473 | if not shell.has_readline: |
|
2473 | if not shell.has_readline: | |
2474 | new_scheme = 'NoColor' |
|
2474 | new_scheme = 'NoColor' | |
2475 |
|
2475 | |||
2476 | # Set prompt colors |
|
2476 | # Set prompt colors | |
2477 | try: |
|
2477 | try: | |
2478 | shell.displayhook.set_colors(new_scheme) |
|
2478 | shell.displayhook.set_colors(new_scheme) | |
2479 | except: |
|
2479 | except: | |
2480 | color_switch_err('prompt') |
|
2480 | color_switch_err('prompt') | |
2481 | else: |
|
2481 | else: | |
2482 | shell.colors = \ |
|
2482 | shell.colors = \ | |
2483 | shell.displayhook.color_table.active_scheme_name |
|
2483 | shell.displayhook.color_table.active_scheme_name | |
2484 | # Set exception colors |
|
2484 | # Set exception colors | |
2485 | try: |
|
2485 | try: | |
2486 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2486 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2487 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2487 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2488 | except: |
|
2488 | except: | |
2489 | color_switch_err('exception') |
|
2489 | color_switch_err('exception') | |
2490 |
|
2490 | |||
2491 | # Set info (for 'object?') colors |
|
2491 | # Set info (for 'object?') colors | |
2492 | if shell.color_info: |
|
2492 | if shell.color_info: | |
2493 | try: |
|
2493 | try: | |
2494 | shell.inspector.set_active_scheme(new_scheme) |
|
2494 | shell.inspector.set_active_scheme(new_scheme) | |
2495 | except: |
|
2495 | except: | |
2496 | color_switch_err('object inspector') |
|
2496 | color_switch_err('object inspector') | |
2497 | else: |
|
2497 | else: | |
2498 | shell.inspector.set_active_scheme('NoColor') |
|
2498 | shell.inspector.set_active_scheme('NoColor') | |
2499 |
|
2499 | |||
2500 | def magic_pprint(self, parameter_s=''): |
|
2500 | def magic_pprint(self, parameter_s=''): | |
2501 | """Toggle pretty printing on/off.""" |
|
2501 | """Toggle pretty printing on/off.""" | |
2502 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2502 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
2503 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2503 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2504 | print 'Pretty printing has been turned', \ |
|
2504 | print 'Pretty printing has been turned', \ | |
2505 | ['OFF','ON'][ptformatter.pprint] |
|
2505 | ['OFF','ON'][ptformatter.pprint] | |
2506 |
|
||||
2507 | def magic_Exit(self, parameter_s=''): |
|
|||
2508 | """Exit IPython.""" |
|
|||
2509 |
|
||||
2510 | self.shell.ask_exit() |
|
|||
2511 |
|
||||
2512 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
|||
2513 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
|||
2514 |
|
2506 | |||
2515 | #...................................................................... |
|
2507 | #...................................................................... | |
2516 | # Functions to implement unix shell-type things |
|
2508 | # Functions to implement unix shell-type things | |
2517 |
|
2509 | |||
2518 | @testdec.skip_doctest |
|
2510 | @testdec.skip_doctest | |
2519 | def magic_alias(self, parameter_s = ''): |
|
2511 | def magic_alias(self, parameter_s = ''): | |
2520 | """Define an alias for a system command. |
|
2512 | """Define an alias for a system command. | |
2521 |
|
2513 | |||
2522 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2514 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2523 |
|
2515 | |||
2524 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2516 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2525 | params' (from your underlying operating system). |
|
2517 | params' (from your underlying operating system). | |
2526 |
|
2518 | |||
2527 | Aliases have lower precedence than magic functions and Python normal |
|
2519 | Aliases have lower precedence than magic functions and Python normal | |
2528 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2520 | variables, so if 'foo' is both a Python variable and an alias, the | |
2529 | alias can not be executed until 'del foo' removes the Python variable. |
|
2521 | alias can not be executed until 'del foo' removes the Python variable. | |
2530 |
|
2522 | |||
2531 | You can use the %l specifier in an alias definition to represent the |
|
2523 | You can use the %l specifier in an alias definition to represent the | |
2532 | whole line when the alias is called. For example: |
|
2524 | whole line when the alias is called. For example: | |
2533 |
|
2525 | |||
2534 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2526 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2535 | In [3]: bracket hello world |
|
2527 | In [3]: bracket hello world | |
2536 | Input in brackets: <hello world> |
|
2528 | Input in brackets: <hello world> | |
2537 |
|
2529 | |||
2538 | You can also define aliases with parameters using %s specifiers (one |
|
2530 | You can also define aliases with parameters using %s specifiers (one | |
2539 | per parameter): |
|
2531 | per parameter): | |
2540 |
|
2532 | |||
2541 | In [1]: alias parts echo first %s second %s |
|
2533 | In [1]: alias parts echo first %s second %s | |
2542 | In [2]: %parts A B |
|
2534 | In [2]: %parts A B | |
2543 | first A second B |
|
2535 | first A second B | |
2544 | In [3]: %parts A |
|
2536 | In [3]: %parts A | |
2545 | Incorrect number of arguments: 2 expected. |
|
2537 | Incorrect number of arguments: 2 expected. | |
2546 | parts is an alias to: 'echo first %s second %s' |
|
2538 | parts is an alias to: 'echo first %s second %s' | |
2547 |
|
2539 | |||
2548 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2540 | Note that %l and %s are mutually exclusive. You can only use one or | |
2549 | the other in your aliases. |
|
2541 | the other in your aliases. | |
2550 |
|
2542 | |||
2551 | Aliases expand Python variables just like system calls using ! or !! |
|
2543 | Aliases expand Python variables just like system calls using ! or !! | |
2552 | do: all expressions prefixed with '$' get expanded. For details of |
|
2544 | do: all expressions prefixed with '$' get expanded. For details of | |
2553 | the semantic rules, see PEP-215: |
|
2545 | the semantic rules, see PEP-215: | |
2554 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2546 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2555 | IPython for variable expansion. If you want to access a true shell |
|
2547 | IPython for variable expansion. If you want to access a true shell | |
2556 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2548 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2557 |
|
2549 | |||
2558 | In [6]: alias show echo |
|
2550 | In [6]: alias show echo | |
2559 | In [7]: PATH='A Python string' |
|
2551 | In [7]: PATH='A Python string' | |
2560 | In [8]: show $PATH |
|
2552 | In [8]: show $PATH | |
2561 | A Python string |
|
2553 | A Python string | |
2562 | In [9]: show $$PATH |
|
2554 | In [9]: show $$PATH | |
2563 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2555 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2564 |
|
2556 | |||
2565 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2557 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2566 | and %rehashx functions, which automatically create aliases for the |
|
2558 | and %rehashx functions, which automatically create aliases for the | |
2567 | contents of your $PATH. |
|
2559 | contents of your $PATH. | |
2568 |
|
2560 | |||
2569 | If called with no parameters, %alias prints the current alias table.""" |
|
2561 | If called with no parameters, %alias prints the current alias table.""" | |
2570 |
|
2562 | |||
2571 | par = parameter_s.strip() |
|
2563 | par = parameter_s.strip() | |
2572 | if not par: |
|
2564 | if not par: | |
2573 | stored = self.db.get('stored_aliases', {} ) |
|
2565 | stored = self.db.get('stored_aliases', {} ) | |
2574 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2566 | aliases = sorted(self.shell.alias_manager.aliases) | |
2575 | # for k, v in stored: |
|
2567 | # for k, v in stored: | |
2576 | # atab.append(k, v[0]) |
|
2568 | # atab.append(k, v[0]) | |
2577 |
|
2569 | |||
2578 | print "Total number of aliases:", len(aliases) |
|
2570 | print "Total number of aliases:", len(aliases) | |
2579 | sys.stdout.flush() |
|
2571 | sys.stdout.flush() | |
2580 | return aliases |
|
2572 | return aliases | |
2581 |
|
2573 | |||
2582 | # Now try to define a new one |
|
2574 | # Now try to define a new one | |
2583 | try: |
|
2575 | try: | |
2584 | alias,cmd = par.split(None, 1) |
|
2576 | alias,cmd = par.split(None, 1) | |
2585 | except: |
|
2577 | except: | |
2586 | print oinspect.getdoc(self.magic_alias) |
|
2578 | print oinspect.getdoc(self.magic_alias) | |
2587 | else: |
|
2579 | else: | |
2588 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2580 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2589 | # end magic_alias |
|
2581 | # end magic_alias | |
2590 |
|
2582 | |||
2591 | def magic_unalias(self, parameter_s = ''): |
|
2583 | def magic_unalias(self, parameter_s = ''): | |
2592 | """Remove an alias""" |
|
2584 | """Remove an alias""" | |
2593 |
|
2585 | |||
2594 | aname = parameter_s.strip() |
|
2586 | aname = parameter_s.strip() | |
2595 | self.shell.alias_manager.undefine_alias(aname) |
|
2587 | self.shell.alias_manager.undefine_alias(aname) | |
2596 | stored = self.db.get('stored_aliases', {} ) |
|
2588 | stored = self.db.get('stored_aliases', {} ) | |
2597 | if aname in stored: |
|
2589 | if aname in stored: | |
2598 | print "Removing %stored alias",aname |
|
2590 | print "Removing %stored alias",aname | |
2599 | del stored[aname] |
|
2591 | del stored[aname] | |
2600 | self.db['stored_aliases'] = stored |
|
2592 | self.db['stored_aliases'] = stored | |
2601 |
|
2593 | |||
2602 | def magic_rehashx(self, parameter_s = ''): |
|
2594 | def magic_rehashx(self, parameter_s = ''): | |
2603 | """Update the alias table with all executable files in $PATH. |
|
2595 | """Update the alias table with all executable files in $PATH. | |
2604 |
|
2596 | |||
2605 | This version explicitly checks that every entry in $PATH is a file |
|
2597 | This version explicitly checks that every entry in $PATH is a file | |
2606 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2598 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2607 |
|
2599 | |||
2608 | Under Windows, it checks executability as a match agains a |
|
2600 | Under Windows, it checks executability as a match agains a | |
2609 | '|'-separated string of extensions, stored in the IPython config |
|
2601 | '|'-separated string of extensions, stored in the IPython config | |
2610 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2602 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2611 |
|
2603 | |||
2612 | This function also resets the root module cache of module completer, |
|
2604 | This function also resets the root module cache of module completer, | |
2613 | used on slow filesystems. |
|
2605 | used on slow filesystems. | |
2614 | """ |
|
2606 | """ | |
2615 | from IPython.core.alias import InvalidAliasError |
|
2607 | from IPython.core.alias import InvalidAliasError | |
2616 |
|
2608 | |||
2617 | # for the benefit of module completer in ipy_completers.py |
|
2609 | # for the benefit of module completer in ipy_completers.py | |
2618 | del self.db['rootmodules'] |
|
2610 | del self.db['rootmodules'] | |
2619 |
|
2611 | |||
2620 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2612 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2621 | os.environ.get('PATH','').split(os.pathsep)] |
|
2613 | os.environ.get('PATH','').split(os.pathsep)] | |
2622 | path = filter(os.path.isdir,path) |
|
2614 | path = filter(os.path.isdir,path) | |
2623 |
|
2615 | |||
2624 | syscmdlist = [] |
|
2616 | syscmdlist = [] | |
2625 | # Now define isexec in a cross platform manner. |
|
2617 | # Now define isexec in a cross platform manner. | |
2626 | if os.name == 'posix': |
|
2618 | if os.name == 'posix': | |
2627 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2619 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2628 | os.access(fname,os.X_OK) |
|
2620 | os.access(fname,os.X_OK) | |
2629 | else: |
|
2621 | else: | |
2630 | try: |
|
2622 | try: | |
2631 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2623 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2632 | except KeyError: |
|
2624 | except KeyError: | |
2633 | winext = 'exe|com|bat|py' |
|
2625 | winext = 'exe|com|bat|py' | |
2634 | if 'py' not in winext: |
|
2626 | if 'py' not in winext: | |
2635 | winext += '|py' |
|
2627 | winext += '|py' | |
2636 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2628 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2637 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2629 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2638 | savedir = os.getcwd() |
|
2630 | savedir = os.getcwd() | |
2639 |
|
2631 | |||
2640 | # Now walk the paths looking for executables to alias. |
|
2632 | # Now walk the paths looking for executables to alias. | |
2641 | try: |
|
2633 | try: | |
2642 | # write the whole loop for posix/Windows so we don't have an if in |
|
2634 | # write the whole loop for posix/Windows so we don't have an if in | |
2643 | # the innermost part |
|
2635 | # the innermost part | |
2644 | if os.name == 'posix': |
|
2636 | if os.name == 'posix': | |
2645 | for pdir in path: |
|
2637 | for pdir in path: | |
2646 | os.chdir(pdir) |
|
2638 | os.chdir(pdir) | |
2647 | for ff in os.listdir(pdir): |
|
2639 | for ff in os.listdir(pdir): | |
2648 | if isexec(ff): |
|
2640 | if isexec(ff): | |
2649 | try: |
|
2641 | try: | |
2650 | # Removes dots from the name since ipython |
|
2642 | # Removes dots from the name since ipython | |
2651 | # will assume names with dots to be python. |
|
2643 | # will assume names with dots to be python. | |
2652 | self.shell.alias_manager.define_alias( |
|
2644 | self.shell.alias_manager.define_alias( | |
2653 | ff.replace('.',''), ff) |
|
2645 | ff.replace('.',''), ff) | |
2654 | except InvalidAliasError: |
|
2646 | except InvalidAliasError: | |
2655 | pass |
|
2647 | pass | |
2656 | else: |
|
2648 | else: | |
2657 | syscmdlist.append(ff) |
|
2649 | syscmdlist.append(ff) | |
2658 | else: |
|
2650 | else: | |
2659 | no_alias = self.shell.alias_manager.no_alias |
|
2651 | no_alias = self.shell.alias_manager.no_alias | |
2660 | for pdir in path: |
|
2652 | for pdir in path: | |
2661 | os.chdir(pdir) |
|
2653 | os.chdir(pdir) | |
2662 | for ff in os.listdir(pdir): |
|
2654 | for ff in os.listdir(pdir): | |
2663 | base, ext = os.path.splitext(ff) |
|
2655 | base, ext = os.path.splitext(ff) | |
2664 | if isexec(ff) and base.lower() not in no_alias: |
|
2656 | if isexec(ff) and base.lower() not in no_alias: | |
2665 | if ext.lower() == '.exe': |
|
2657 | if ext.lower() == '.exe': | |
2666 | ff = base |
|
2658 | ff = base | |
2667 | try: |
|
2659 | try: | |
2668 | # Removes dots from the name since ipython |
|
2660 | # Removes dots from the name since ipython | |
2669 | # will assume names with dots to be python. |
|
2661 | # will assume names with dots to be python. | |
2670 | self.shell.alias_manager.define_alias( |
|
2662 | self.shell.alias_manager.define_alias( | |
2671 | base.lower().replace('.',''), ff) |
|
2663 | base.lower().replace('.',''), ff) | |
2672 | except InvalidAliasError: |
|
2664 | except InvalidAliasError: | |
2673 | pass |
|
2665 | pass | |
2674 | syscmdlist.append(ff) |
|
2666 | syscmdlist.append(ff) | |
2675 | db = self.db |
|
2667 | db = self.db | |
2676 | db['syscmdlist'] = syscmdlist |
|
2668 | db['syscmdlist'] = syscmdlist | |
2677 | finally: |
|
2669 | finally: | |
2678 | os.chdir(savedir) |
|
2670 | os.chdir(savedir) | |
2679 |
|
2671 | |||
2680 | @testdec.skip_doctest |
|
2672 | @testdec.skip_doctest | |
2681 | def magic_pwd(self, parameter_s = ''): |
|
2673 | def magic_pwd(self, parameter_s = ''): | |
2682 | """Return the current working directory path. |
|
2674 | """Return the current working directory path. | |
2683 |
|
2675 | |||
2684 | Examples |
|
2676 | Examples | |
2685 | -------- |
|
2677 | -------- | |
2686 | :: |
|
2678 | :: | |
2687 |
|
2679 | |||
2688 | In [9]: pwd |
|
2680 | In [9]: pwd | |
2689 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2681 | Out[9]: '/home/tsuser/sprint/ipython' | |
2690 | """ |
|
2682 | """ | |
2691 | return os.getcwd() |
|
2683 | return os.getcwd() | |
2692 |
|
2684 | |||
2693 | @testdec.skip_doctest |
|
2685 | @testdec.skip_doctest | |
2694 | def magic_cd(self, parameter_s=''): |
|
2686 | def magic_cd(self, parameter_s=''): | |
2695 | """Change the current working directory. |
|
2687 | """Change the current working directory. | |
2696 |
|
2688 | |||
2697 | This command automatically maintains an internal list of directories |
|
2689 | This command automatically maintains an internal list of directories | |
2698 | you visit during your IPython session, in the variable _dh. The |
|
2690 | you visit during your IPython session, in the variable _dh. The | |
2699 | command %dhist shows this history nicely formatted. You can also |
|
2691 | command %dhist shows this history nicely formatted. You can also | |
2700 | do 'cd -<tab>' to see directory history conveniently. |
|
2692 | do 'cd -<tab>' to see directory history conveniently. | |
2701 |
|
2693 | |||
2702 | Usage: |
|
2694 | Usage: | |
2703 |
|
2695 | |||
2704 | cd 'dir': changes to directory 'dir'. |
|
2696 | cd 'dir': changes to directory 'dir'. | |
2705 |
|
2697 | |||
2706 | cd -: changes to the last visited directory. |
|
2698 | cd -: changes to the last visited directory. | |
2707 |
|
2699 | |||
2708 | cd -<n>: changes to the n-th directory in the directory history. |
|
2700 | cd -<n>: changes to the n-th directory in the directory history. | |
2709 |
|
2701 | |||
2710 | cd --foo: change to directory that matches 'foo' in history |
|
2702 | cd --foo: change to directory that matches 'foo' in history | |
2711 |
|
2703 | |||
2712 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2704 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2713 | (note: cd <bookmark_name> is enough if there is no |
|
2705 | (note: cd <bookmark_name> is enough if there is no | |
2714 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2706 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2715 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2707 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2716 |
|
2708 | |||
2717 | Options: |
|
2709 | Options: | |
2718 |
|
2710 | |||
2719 | -q: quiet. Do not print the working directory after the cd command is |
|
2711 | -q: quiet. Do not print the working directory after the cd command is | |
2720 | executed. By default IPython's cd command does print this directory, |
|
2712 | executed. By default IPython's cd command does print this directory, | |
2721 | since the default prompts do not display path information. |
|
2713 | since the default prompts do not display path information. | |
2722 |
|
2714 | |||
2723 | Note that !cd doesn't work for this purpose because the shell where |
|
2715 | Note that !cd doesn't work for this purpose because the shell where | |
2724 | !command runs is immediately discarded after executing 'command'. |
|
2716 | !command runs is immediately discarded after executing 'command'. | |
2725 |
|
2717 | |||
2726 | Examples |
|
2718 | Examples | |
2727 | -------- |
|
2719 | -------- | |
2728 | :: |
|
2720 | :: | |
2729 |
|
2721 | |||
2730 | In [10]: cd parent/child |
|
2722 | In [10]: cd parent/child | |
2731 | /home/tsuser/parent/child |
|
2723 | /home/tsuser/parent/child | |
2732 | """ |
|
2724 | """ | |
2733 |
|
2725 | |||
2734 | parameter_s = parameter_s.strip() |
|
2726 | parameter_s = parameter_s.strip() | |
2735 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2727 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2736 |
|
2728 | |||
2737 | oldcwd = os.getcwd() |
|
2729 | oldcwd = os.getcwd() | |
2738 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2730 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2739 | # jump in directory history by number |
|
2731 | # jump in directory history by number | |
2740 | if numcd: |
|
2732 | if numcd: | |
2741 | nn = int(numcd.group(2)) |
|
2733 | nn = int(numcd.group(2)) | |
2742 | try: |
|
2734 | try: | |
2743 | ps = self.shell.user_ns['_dh'][nn] |
|
2735 | ps = self.shell.user_ns['_dh'][nn] | |
2744 | except IndexError: |
|
2736 | except IndexError: | |
2745 | print 'The requested directory does not exist in history.' |
|
2737 | print 'The requested directory does not exist in history.' | |
2746 | return |
|
2738 | return | |
2747 | else: |
|
2739 | else: | |
2748 | opts = {} |
|
2740 | opts = {} | |
2749 | elif parameter_s.startswith('--'): |
|
2741 | elif parameter_s.startswith('--'): | |
2750 | ps = None |
|
2742 | ps = None | |
2751 | fallback = None |
|
2743 | fallback = None | |
2752 | pat = parameter_s[2:] |
|
2744 | pat = parameter_s[2:] | |
2753 | dh = self.shell.user_ns['_dh'] |
|
2745 | dh = self.shell.user_ns['_dh'] | |
2754 | # first search only by basename (last component) |
|
2746 | # first search only by basename (last component) | |
2755 | for ent in reversed(dh): |
|
2747 | for ent in reversed(dh): | |
2756 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2748 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2757 | ps = ent |
|
2749 | ps = ent | |
2758 | break |
|
2750 | break | |
2759 |
|
2751 | |||
2760 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2752 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2761 | fallback = ent |
|
2753 | fallback = ent | |
2762 |
|
2754 | |||
2763 | # if we have no last part match, pick the first full path match |
|
2755 | # if we have no last part match, pick the first full path match | |
2764 | if ps is None: |
|
2756 | if ps is None: | |
2765 | ps = fallback |
|
2757 | ps = fallback | |
2766 |
|
2758 | |||
2767 | if ps is None: |
|
2759 | if ps is None: | |
2768 | print "No matching entry in directory history" |
|
2760 | print "No matching entry in directory history" | |
2769 | return |
|
2761 | return | |
2770 | else: |
|
2762 | else: | |
2771 | opts = {} |
|
2763 | opts = {} | |
2772 |
|
2764 | |||
2773 |
|
2765 | |||
2774 | else: |
|
2766 | else: | |
2775 | #turn all non-space-escaping backslashes to slashes, |
|
2767 | #turn all non-space-escaping backslashes to slashes, | |
2776 | # for c:\windows\directory\names\ |
|
2768 | # for c:\windows\directory\names\ | |
2777 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2769 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2778 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2770 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2779 | # jump to previous |
|
2771 | # jump to previous | |
2780 | if ps == '-': |
|
2772 | if ps == '-': | |
2781 | try: |
|
2773 | try: | |
2782 | ps = self.shell.user_ns['_dh'][-2] |
|
2774 | ps = self.shell.user_ns['_dh'][-2] | |
2783 | except IndexError: |
|
2775 | except IndexError: | |
2784 | raise UsageError('%cd -: No previous directory to change to.') |
|
2776 | raise UsageError('%cd -: No previous directory to change to.') | |
2785 | # jump to bookmark if needed |
|
2777 | # jump to bookmark if needed | |
2786 | else: |
|
2778 | else: | |
2787 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2779 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2788 | bkms = self.db.get('bookmarks', {}) |
|
2780 | bkms = self.db.get('bookmarks', {}) | |
2789 |
|
2781 | |||
2790 | if bkms.has_key(ps): |
|
2782 | if bkms.has_key(ps): | |
2791 | target = bkms[ps] |
|
2783 | target = bkms[ps] | |
2792 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2784 | print '(bookmark:%s) -> %s' % (ps,target) | |
2793 | ps = target |
|
2785 | ps = target | |
2794 | else: |
|
2786 | else: | |
2795 | if opts.has_key('b'): |
|
2787 | if opts.has_key('b'): | |
2796 | raise UsageError("Bookmark '%s' not found. " |
|
2788 | raise UsageError("Bookmark '%s' not found. " | |
2797 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2789 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2798 |
|
2790 | |||
2799 | # at this point ps should point to the target dir |
|
2791 | # at this point ps should point to the target dir | |
2800 | if ps: |
|
2792 | if ps: | |
2801 | try: |
|
2793 | try: | |
2802 | os.chdir(os.path.expanduser(ps)) |
|
2794 | os.chdir(os.path.expanduser(ps)) | |
2803 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2795 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2804 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2796 | set_term_title('IPython: ' + abbrev_cwd()) | |
2805 | except OSError: |
|
2797 | except OSError: | |
2806 | print sys.exc_info()[1] |
|
2798 | print sys.exc_info()[1] | |
2807 | else: |
|
2799 | else: | |
2808 | cwd = os.getcwd() |
|
2800 | cwd = os.getcwd() | |
2809 | dhist = self.shell.user_ns['_dh'] |
|
2801 | dhist = self.shell.user_ns['_dh'] | |
2810 | if oldcwd != cwd: |
|
2802 | if oldcwd != cwd: | |
2811 | dhist.append(cwd) |
|
2803 | dhist.append(cwd) | |
2812 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2804 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2813 |
|
2805 | |||
2814 | else: |
|
2806 | else: | |
2815 | os.chdir(self.shell.home_dir) |
|
2807 | os.chdir(self.shell.home_dir) | |
2816 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2808 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2817 | set_term_title('IPython: ' + '~') |
|
2809 | set_term_title('IPython: ' + '~') | |
2818 | cwd = os.getcwd() |
|
2810 | cwd = os.getcwd() | |
2819 | dhist = self.shell.user_ns['_dh'] |
|
2811 | dhist = self.shell.user_ns['_dh'] | |
2820 |
|
2812 | |||
2821 | if oldcwd != cwd: |
|
2813 | if oldcwd != cwd: | |
2822 | dhist.append(cwd) |
|
2814 | dhist.append(cwd) | |
2823 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2815 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2824 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2816 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2825 | print self.shell.user_ns['_dh'][-1] |
|
2817 | print self.shell.user_ns['_dh'][-1] | |
2826 |
|
2818 | |||
2827 |
|
2819 | |||
2828 | def magic_env(self, parameter_s=''): |
|
2820 | def magic_env(self, parameter_s=''): | |
2829 | """List environment variables.""" |
|
2821 | """List environment variables.""" | |
2830 |
|
2822 | |||
2831 | return os.environ.data |
|
2823 | return os.environ.data | |
2832 |
|
2824 | |||
2833 | def magic_pushd(self, parameter_s=''): |
|
2825 | def magic_pushd(self, parameter_s=''): | |
2834 | """Place the current dir on stack and change directory. |
|
2826 | """Place the current dir on stack and change directory. | |
2835 |
|
2827 | |||
2836 | Usage:\\ |
|
2828 | Usage:\\ | |
2837 | %pushd ['dirname'] |
|
2829 | %pushd ['dirname'] | |
2838 | """ |
|
2830 | """ | |
2839 |
|
2831 | |||
2840 | dir_s = self.shell.dir_stack |
|
2832 | dir_s = self.shell.dir_stack | |
2841 | tgt = os.path.expanduser(parameter_s) |
|
2833 | tgt = os.path.expanduser(parameter_s) | |
2842 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2834 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2843 | if tgt: |
|
2835 | if tgt: | |
2844 | self.magic_cd(parameter_s) |
|
2836 | self.magic_cd(parameter_s) | |
2845 | dir_s.insert(0,cwd) |
|
2837 | dir_s.insert(0,cwd) | |
2846 | return self.magic_dirs() |
|
2838 | return self.magic_dirs() | |
2847 |
|
2839 | |||
2848 | def magic_popd(self, parameter_s=''): |
|
2840 | def magic_popd(self, parameter_s=''): | |
2849 | """Change to directory popped off the top of the stack. |
|
2841 | """Change to directory popped off the top of the stack. | |
2850 | """ |
|
2842 | """ | |
2851 | if not self.shell.dir_stack: |
|
2843 | if not self.shell.dir_stack: | |
2852 | raise UsageError("%popd on empty stack") |
|
2844 | raise UsageError("%popd on empty stack") | |
2853 | top = self.shell.dir_stack.pop(0) |
|
2845 | top = self.shell.dir_stack.pop(0) | |
2854 | self.magic_cd(top) |
|
2846 | self.magic_cd(top) | |
2855 | print "popd ->",top |
|
2847 | print "popd ->",top | |
2856 |
|
2848 | |||
2857 | def magic_dirs(self, parameter_s=''): |
|
2849 | def magic_dirs(self, parameter_s=''): | |
2858 | """Return the current directory stack.""" |
|
2850 | """Return the current directory stack.""" | |
2859 |
|
2851 | |||
2860 | return self.shell.dir_stack |
|
2852 | return self.shell.dir_stack | |
2861 |
|
2853 | |||
2862 | def magic_dhist(self, parameter_s=''): |
|
2854 | def magic_dhist(self, parameter_s=''): | |
2863 | """Print your history of visited directories. |
|
2855 | """Print your history of visited directories. | |
2864 |
|
2856 | |||
2865 | %dhist -> print full history\\ |
|
2857 | %dhist -> print full history\\ | |
2866 | %dhist n -> print last n entries only\\ |
|
2858 | %dhist n -> print last n entries only\\ | |
2867 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2859 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2868 |
|
2860 | |||
2869 | This history is automatically maintained by the %cd command, and |
|
2861 | This history is automatically maintained by the %cd command, and | |
2870 | always available as the global list variable _dh. You can use %cd -<n> |
|
2862 | always available as the global list variable _dh. You can use %cd -<n> | |
2871 | to go to directory number <n>. |
|
2863 | to go to directory number <n>. | |
2872 |
|
2864 | |||
2873 | Note that most of time, you should view directory history by entering |
|
2865 | Note that most of time, you should view directory history by entering | |
2874 | cd -<TAB>. |
|
2866 | cd -<TAB>. | |
2875 |
|
2867 | |||
2876 | """ |
|
2868 | """ | |
2877 |
|
2869 | |||
2878 | dh = self.shell.user_ns['_dh'] |
|
2870 | dh = self.shell.user_ns['_dh'] | |
2879 | if parameter_s: |
|
2871 | if parameter_s: | |
2880 | try: |
|
2872 | try: | |
2881 | args = map(int,parameter_s.split()) |
|
2873 | args = map(int,parameter_s.split()) | |
2882 | except: |
|
2874 | except: | |
2883 | self.arg_err(Magic.magic_dhist) |
|
2875 | self.arg_err(Magic.magic_dhist) | |
2884 | return |
|
2876 | return | |
2885 | if len(args) == 1: |
|
2877 | if len(args) == 1: | |
2886 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2878 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2887 | elif len(args) == 2: |
|
2879 | elif len(args) == 2: | |
2888 | ini,fin = args |
|
2880 | ini,fin = args | |
2889 | else: |
|
2881 | else: | |
2890 | self.arg_err(Magic.magic_dhist) |
|
2882 | self.arg_err(Magic.magic_dhist) | |
2891 | return |
|
2883 | return | |
2892 | else: |
|
2884 | else: | |
2893 | ini,fin = 0,len(dh) |
|
2885 | ini,fin = 0,len(dh) | |
2894 | nlprint(dh, |
|
2886 | nlprint(dh, | |
2895 | header = 'Directory history (kept in _dh)', |
|
2887 | header = 'Directory history (kept in _dh)', | |
2896 | start=ini,stop=fin) |
|
2888 | start=ini,stop=fin) | |
2897 |
|
2889 | |||
2898 | @testdec.skip_doctest |
|
2890 | @testdec.skip_doctest | |
2899 | def magic_sc(self, parameter_s=''): |
|
2891 | def magic_sc(self, parameter_s=''): | |
2900 | """Shell capture - execute a shell command and capture its output. |
|
2892 | """Shell capture - execute a shell command and capture its output. | |
2901 |
|
2893 | |||
2902 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2894 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2903 |
|
2895 | |||
2904 | You should use the form 'var = !command' instead. Example: |
|
2896 | You should use the form 'var = !command' instead. Example: | |
2905 |
|
2897 | |||
2906 | "%sc -l myfiles = ls ~" should now be written as |
|
2898 | "%sc -l myfiles = ls ~" should now be written as | |
2907 |
|
2899 | |||
2908 | "myfiles = !ls ~" |
|
2900 | "myfiles = !ls ~" | |
2909 |
|
2901 | |||
2910 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2902 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2911 | below. |
|
2903 | below. | |
2912 |
|
2904 | |||
2913 | -- |
|
2905 | -- | |
2914 | %sc [options] varname=command |
|
2906 | %sc [options] varname=command | |
2915 |
|
2907 | |||
2916 | IPython will run the given command using commands.getoutput(), and |
|
2908 | IPython will run the given command using commands.getoutput(), and | |
2917 | will then update the user's interactive namespace with a variable |
|
2909 | will then update the user's interactive namespace with a variable | |
2918 | called varname, containing the value of the call. Your command can |
|
2910 | called varname, containing the value of the call. Your command can | |
2919 | contain shell wildcards, pipes, etc. |
|
2911 | contain shell wildcards, pipes, etc. | |
2920 |
|
2912 | |||
2921 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2913 | The '=' sign in the syntax is mandatory, and the variable name you | |
2922 | supply must follow Python's standard conventions for valid names. |
|
2914 | supply must follow Python's standard conventions for valid names. | |
2923 |
|
2915 | |||
2924 | (A special format without variable name exists for internal use) |
|
2916 | (A special format without variable name exists for internal use) | |
2925 |
|
2917 | |||
2926 | Options: |
|
2918 | Options: | |
2927 |
|
2919 | |||
2928 | -l: list output. Split the output on newlines into a list before |
|
2920 | -l: list output. Split the output on newlines into a list before | |
2929 | assigning it to the given variable. By default the output is stored |
|
2921 | assigning it to the given variable. By default the output is stored | |
2930 | as a single string. |
|
2922 | as a single string. | |
2931 |
|
2923 | |||
2932 | -v: verbose. Print the contents of the variable. |
|
2924 | -v: verbose. Print the contents of the variable. | |
2933 |
|
2925 | |||
2934 | In most cases you should not need to split as a list, because the |
|
2926 | In most cases you should not need to split as a list, because the | |
2935 | returned value is a special type of string which can automatically |
|
2927 | returned value is a special type of string which can automatically | |
2936 | provide its contents either as a list (split on newlines) or as a |
|
2928 | provide its contents either as a list (split on newlines) or as a | |
2937 | space-separated string. These are convenient, respectively, either |
|
2929 | space-separated string. These are convenient, respectively, either | |
2938 | for sequential processing or to be passed to a shell command. |
|
2930 | for sequential processing or to be passed to a shell command. | |
2939 |
|
2931 | |||
2940 | For example: |
|
2932 | For example: | |
2941 |
|
2933 | |||
2942 | # all-random |
|
2934 | # all-random | |
2943 |
|
2935 | |||
2944 | # Capture into variable a |
|
2936 | # Capture into variable a | |
2945 | In [1]: sc a=ls *py |
|
2937 | In [1]: sc a=ls *py | |
2946 |
|
2938 | |||
2947 | # a is a string with embedded newlines |
|
2939 | # a is a string with embedded newlines | |
2948 | In [2]: a |
|
2940 | In [2]: a | |
2949 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2941 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2950 |
|
2942 | |||
2951 | # which can be seen as a list: |
|
2943 | # which can be seen as a list: | |
2952 | In [3]: a.l |
|
2944 | In [3]: a.l | |
2953 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2945 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2954 |
|
2946 | |||
2955 | # or as a whitespace-separated string: |
|
2947 | # or as a whitespace-separated string: | |
2956 | In [4]: a.s |
|
2948 | In [4]: a.s | |
2957 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2949 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2958 |
|
2950 | |||
2959 | # a.s is useful to pass as a single command line: |
|
2951 | # a.s is useful to pass as a single command line: | |
2960 | In [5]: !wc -l $a.s |
|
2952 | In [5]: !wc -l $a.s | |
2961 | 146 setup.py |
|
2953 | 146 setup.py | |
2962 | 130 win32_manual_post_install.py |
|
2954 | 130 win32_manual_post_install.py | |
2963 | 276 total |
|
2955 | 276 total | |
2964 |
|
2956 | |||
2965 | # while the list form is useful to loop over: |
|
2957 | # while the list form is useful to loop over: | |
2966 | In [6]: for f in a.l: |
|
2958 | In [6]: for f in a.l: | |
2967 | ...: !wc -l $f |
|
2959 | ...: !wc -l $f | |
2968 | ...: |
|
2960 | ...: | |
2969 | 146 setup.py |
|
2961 | 146 setup.py | |
2970 | 130 win32_manual_post_install.py |
|
2962 | 130 win32_manual_post_install.py | |
2971 |
|
2963 | |||
2972 | Similiarly, the lists returned by the -l option are also special, in |
|
2964 | Similiarly, the lists returned by the -l option are also special, in | |
2973 | the sense that you can equally invoke the .s attribute on them to |
|
2965 | the sense that you can equally invoke the .s attribute on them to | |
2974 | automatically get a whitespace-separated string from their contents: |
|
2966 | automatically get a whitespace-separated string from their contents: | |
2975 |
|
2967 | |||
2976 | In [7]: sc -l b=ls *py |
|
2968 | In [7]: sc -l b=ls *py | |
2977 |
|
2969 | |||
2978 | In [8]: b |
|
2970 | In [8]: b | |
2979 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2971 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2980 |
|
2972 | |||
2981 | In [9]: b.s |
|
2973 | In [9]: b.s | |
2982 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2974 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2983 |
|
2975 | |||
2984 | In summary, both the lists and strings used for ouptut capture have |
|
2976 | In summary, both the lists and strings used for ouptut capture have | |
2985 | the following special attributes: |
|
2977 | the following special attributes: | |
2986 |
|
2978 | |||
2987 | .l (or .list) : value as list. |
|
2979 | .l (or .list) : value as list. | |
2988 | .n (or .nlstr): value as newline-separated string. |
|
2980 | .n (or .nlstr): value as newline-separated string. | |
2989 | .s (or .spstr): value as space-separated string. |
|
2981 | .s (or .spstr): value as space-separated string. | |
2990 | """ |
|
2982 | """ | |
2991 |
|
2983 | |||
2992 | opts,args = self.parse_options(parameter_s,'lv') |
|
2984 | opts,args = self.parse_options(parameter_s,'lv') | |
2993 | # Try to get a variable name and command to run |
|
2985 | # Try to get a variable name and command to run | |
2994 | try: |
|
2986 | try: | |
2995 | # the variable name must be obtained from the parse_options |
|
2987 | # the variable name must be obtained from the parse_options | |
2996 | # output, which uses shlex.split to strip options out. |
|
2988 | # output, which uses shlex.split to strip options out. | |
2997 | var,_ = args.split('=',1) |
|
2989 | var,_ = args.split('=',1) | |
2998 | var = var.strip() |
|
2990 | var = var.strip() | |
2999 | # But the the command has to be extracted from the original input |
|
2991 | # But the the command has to be extracted from the original input | |
3000 | # parameter_s, not on what parse_options returns, to avoid the |
|
2992 | # parameter_s, not on what parse_options returns, to avoid the | |
3001 | # quote stripping which shlex.split performs on it. |
|
2993 | # quote stripping which shlex.split performs on it. | |
3002 | _,cmd = parameter_s.split('=',1) |
|
2994 | _,cmd = parameter_s.split('=',1) | |
3003 | except ValueError: |
|
2995 | except ValueError: | |
3004 | var,cmd = '','' |
|
2996 | var,cmd = '','' | |
3005 | # If all looks ok, proceed |
|
2997 | # If all looks ok, proceed | |
3006 | split = 'l' in opts |
|
2998 | split = 'l' in opts | |
3007 | out = self.shell.getoutput(cmd, split=split) |
|
2999 | out = self.shell.getoutput(cmd, split=split) | |
3008 | if opts.has_key('v'): |
|
3000 | if opts.has_key('v'): | |
3009 | print '%s ==\n%s' % (var,pformat(out)) |
|
3001 | print '%s ==\n%s' % (var,pformat(out)) | |
3010 | if var: |
|
3002 | if var: | |
3011 | self.shell.user_ns.update({var:out}) |
|
3003 | self.shell.user_ns.update({var:out}) | |
3012 | else: |
|
3004 | else: | |
3013 | return out |
|
3005 | return out | |
3014 |
|
3006 | |||
3015 | def magic_sx(self, parameter_s=''): |
|
3007 | def magic_sx(self, parameter_s=''): | |
3016 | """Shell execute - run a shell command and capture its output. |
|
3008 | """Shell execute - run a shell command and capture its output. | |
3017 |
|
3009 | |||
3018 | %sx command |
|
3010 | %sx command | |
3019 |
|
3011 | |||
3020 | IPython will run the given command using commands.getoutput(), and |
|
3012 | IPython will run the given command using commands.getoutput(), and | |
3021 | return the result formatted as a list (split on '\\n'). Since the |
|
3013 | return the result formatted as a list (split on '\\n'). Since the | |
3022 | output is _returned_, it will be stored in ipython's regular output |
|
3014 | output is _returned_, it will be stored in ipython's regular output | |
3023 | cache Out[N] and in the '_N' automatic variables. |
|
3015 | cache Out[N] and in the '_N' automatic variables. | |
3024 |
|
3016 | |||
3025 | Notes: |
|
3017 | Notes: | |
3026 |
|
3018 | |||
3027 | 1) If an input line begins with '!!', then %sx is automatically |
|
3019 | 1) If an input line begins with '!!', then %sx is automatically | |
3028 | invoked. That is, while: |
|
3020 | invoked. That is, while: | |
3029 | !ls |
|
3021 | !ls | |
3030 | causes ipython to simply issue system('ls'), typing |
|
3022 | causes ipython to simply issue system('ls'), typing | |
3031 | !!ls |
|
3023 | !!ls | |
3032 | is a shorthand equivalent to: |
|
3024 | is a shorthand equivalent to: | |
3033 | %sx ls |
|
3025 | %sx ls | |
3034 |
|
3026 | |||
3035 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3027 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3036 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3028 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3037 | to process line-oriented shell output via further python commands. |
|
3029 | to process line-oriented shell output via further python commands. | |
3038 | %sc is meant to provide much finer control, but requires more |
|
3030 | %sc is meant to provide much finer control, but requires more | |
3039 | typing. |
|
3031 | typing. | |
3040 |
|
3032 | |||
3041 | 3) Just like %sc -l, this is a list with special attributes: |
|
3033 | 3) Just like %sc -l, this is a list with special attributes: | |
3042 |
|
3034 | |||
3043 | .l (or .list) : value as list. |
|
3035 | .l (or .list) : value as list. | |
3044 | .n (or .nlstr): value as newline-separated string. |
|
3036 | .n (or .nlstr): value as newline-separated string. | |
3045 | .s (or .spstr): value as whitespace-separated string. |
|
3037 | .s (or .spstr): value as whitespace-separated string. | |
3046 |
|
3038 | |||
3047 | This is very useful when trying to use such lists as arguments to |
|
3039 | This is very useful when trying to use such lists as arguments to | |
3048 | system commands.""" |
|
3040 | system commands.""" | |
3049 |
|
3041 | |||
3050 | if parameter_s: |
|
3042 | if parameter_s: | |
3051 | return self.shell.getoutput(parameter_s) |
|
3043 | return self.shell.getoutput(parameter_s) | |
3052 |
|
3044 | |||
3053 |
|
3045 | |||
3054 | def magic_bookmark(self, parameter_s=''): |
|
3046 | def magic_bookmark(self, parameter_s=''): | |
3055 | """Manage IPython's bookmark system. |
|
3047 | """Manage IPython's bookmark system. | |
3056 |
|
3048 | |||
3057 | %bookmark <name> - set bookmark to current dir |
|
3049 | %bookmark <name> - set bookmark to current dir | |
3058 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3050 | %bookmark <name> <dir> - set bookmark to <dir> | |
3059 | %bookmark -l - list all bookmarks |
|
3051 | %bookmark -l - list all bookmarks | |
3060 | %bookmark -d <name> - remove bookmark |
|
3052 | %bookmark -d <name> - remove bookmark | |
3061 | %bookmark -r - remove all bookmarks |
|
3053 | %bookmark -r - remove all bookmarks | |
3062 |
|
3054 | |||
3063 | You can later on access a bookmarked folder with: |
|
3055 | You can later on access a bookmarked folder with: | |
3064 | %cd -b <name> |
|
3056 | %cd -b <name> | |
3065 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3057 | or simply '%cd <name>' if there is no directory called <name> AND | |
3066 | there is such a bookmark defined. |
|
3058 | there is such a bookmark defined. | |
3067 |
|
3059 | |||
3068 | Your bookmarks persist through IPython sessions, but they are |
|
3060 | Your bookmarks persist through IPython sessions, but they are | |
3069 | associated with each profile.""" |
|
3061 | associated with each profile.""" | |
3070 |
|
3062 | |||
3071 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3063 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3072 | if len(args) > 2: |
|
3064 | if len(args) > 2: | |
3073 | raise UsageError("%bookmark: too many arguments") |
|
3065 | raise UsageError("%bookmark: too many arguments") | |
3074 |
|
3066 | |||
3075 | bkms = self.db.get('bookmarks',{}) |
|
3067 | bkms = self.db.get('bookmarks',{}) | |
3076 |
|
3068 | |||
3077 | if opts.has_key('d'): |
|
3069 | if opts.has_key('d'): | |
3078 | try: |
|
3070 | try: | |
3079 | todel = args[0] |
|
3071 | todel = args[0] | |
3080 | except IndexError: |
|
3072 | except IndexError: | |
3081 | raise UsageError( |
|
3073 | raise UsageError( | |
3082 | "%bookmark -d: must provide a bookmark to delete") |
|
3074 | "%bookmark -d: must provide a bookmark to delete") | |
3083 | else: |
|
3075 | else: | |
3084 | try: |
|
3076 | try: | |
3085 | del bkms[todel] |
|
3077 | del bkms[todel] | |
3086 | except KeyError: |
|
3078 | except KeyError: | |
3087 | raise UsageError( |
|
3079 | raise UsageError( | |
3088 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3080 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3089 |
|
3081 | |||
3090 | elif opts.has_key('r'): |
|
3082 | elif opts.has_key('r'): | |
3091 | bkms = {} |
|
3083 | bkms = {} | |
3092 | elif opts.has_key('l'): |
|
3084 | elif opts.has_key('l'): | |
3093 | bks = bkms.keys() |
|
3085 | bks = bkms.keys() | |
3094 | bks.sort() |
|
3086 | bks.sort() | |
3095 | if bks: |
|
3087 | if bks: | |
3096 | size = max(map(len,bks)) |
|
3088 | size = max(map(len,bks)) | |
3097 | else: |
|
3089 | else: | |
3098 | size = 0 |
|
3090 | size = 0 | |
3099 | fmt = '%-'+str(size)+'s -> %s' |
|
3091 | fmt = '%-'+str(size)+'s -> %s' | |
3100 | print 'Current bookmarks:' |
|
3092 | print 'Current bookmarks:' | |
3101 | for bk in bks: |
|
3093 | for bk in bks: | |
3102 | print fmt % (bk,bkms[bk]) |
|
3094 | print fmt % (bk,bkms[bk]) | |
3103 | else: |
|
3095 | else: | |
3104 | if not args: |
|
3096 | if not args: | |
3105 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3097 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3106 | elif len(args)==1: |
|
3098 | elif len(args)==1: | |
3107 | bkms[args[0]] = os.getcwd() |
|
3099 | bkms[args[0]] = os.getcwd() | |
3108 | elif len(args)==2: |
|
3100 | elif len(args)==2: | |
3109 | bkms[args[0]] = args[1] |
|
3101 | bkms[args[0]] = args[1] | |
3110 | self.db['bookmarks'] = bkms |
|
3102 | self.db['bookmarks'] = bkms | |
3111 |
|
3103 | |||
3112 | def magic_pycat(self, parameter_s=''): |
|
3104 | def magic_pycat(self, parameter_s=''): | |
3113 | """Show a syntax-highlighted file through a pager. |
|
3105 | """Show a syntax-highlighted file through a pager. | |
3114 |
|
3106 | |||
3115 | This magic is similar to the cat utility, but it will assume the file |
|
3107 | This magic is similar to the cat utility, but it will assume the file | |
3116 | to be Python source and will show it with syntax highlighting. """ |
|
3108 | to be Python source and will show it with syntax highlighting. """ | |
3117 |
|
3109 | |||
3118 | try: |
|
3110 | try: | |
3119 | filename = get_py_filename(parameter_s) |
|
3111 | filename = get_py_filename(parameter_s) | |
3120 | cont = file_read(filename) |
|
3112 | cont = file_read(filename) | |
3121 | except IOError: |
|
3113 | except IOError: | |
3122 | try: |
|
3114 | try: | |
3123 | cont = eval(parameter_s,self.user_ns) |
|
3115 | cont = eval(parameter_s,self.user_ns) | |
3124 | except NameError: |
|
3116 | except NameError: | |
3125 | cont = None |
|
3117 | cont = None | |
3126 | if cont is None: |
|
3118 | if cont is None: | |
3127 | print "Error: no such file or variable" |
|
3119 | print "Error: no such file or variable" | |
3128 | return |
|
3120 | return | |
3129 |
|
3121 | |||
3130 | page.page(self.shell.pycolorize(cont)) |
|
3122 | page.page(self.shell.pycolorize(cont)) | |
3131 |
|
3123 | |||
3132 | def _rerun_pasted(self): |
|
3124 | def _rerun_pasted(self): | |
3133 | """ Rerun a previously pasted command. |
|
3125 | """ Rerun a previously pasted command. | |
3134 | """ |
|
3126 | """ | |
3135 | b = self.user_ns.get('pasted_block', None) |
|
3127 | b = self.user_ns.get('pasted_block', None) | |
3136 | if b is None: |
|
3128 | if b is None: | |
3137 | raise UsageError('No previous pasted block available') |
|
3129 | raise UsageError('No previous pasted block available') | |
3138 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3130 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3139 | exec b in self.user_ns |
|
3131 | exec b in self.user_ns | |
3140 |
|
3132 | |||
3141 | def _get_pasted_lines(self, sentinel): |
|
3133 | def _get_pasted_lines(self, sentinel): | |
3142 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3134 | """ Yield pasted lines until the user enters the given sentinel value. | |
3143 | """ |
|
3135 | """ | |
3144 | from IPython.core import interactiveshell |
|
3136 | from IPython.core import interactiveshell | |
3145 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3137 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3146 | while True: |
|
3138 | while True: | |
3147 | l = interactiveshell.raw_input_original(':') |
|
3139 | l = interactiveshell.raw_input_original(':') | |
3148 | if l == sentinel: |
|
3140 | if l == sentinel: | |
3149 | return |
|
3141 | return | |
3150 | else: |
|
3142 | else: | |
3151 | yield l |
|
3143 | yield l | |
3152 |
|
3144 | |||
3153 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3145 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3154 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3146 | """ Strip non-code parts of a sequence of lines to return a block of | |
3155 | code. |
|
3147 | code. | |
3156 | """ |
|
3148 | """ | |
3157 | # Regular expressions that declare text we strip from the input: |
|
3149 | # Regular expressions that declare text we strip from the input: | |
3158 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3150 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3159 | r'^\s*(\s?>)+', # Python input prompt |
|
3151 | r'^\s*(\s?>)+', # Python input prompt | |
3160 | r'^\s*\.{3,}', # Continuation prompts |
|
3152 | r'^\s*\.{3,}', # Continuation prompts | |
3161 | r'^\++', |
|
3153 | r'^\++', | |
3162 | ] |
|
3154 | ] | |
3163 |
|
3155 | |||
3164 | strip_from_start = map(re.compile,strip_re) |
|
3156 | strip_from_start = map(re.compile,strip_re) | |
3165 |
|
3157 | |||
3166 | lines = [] |
|
3158 | lines = [] | |
3167 | for l in raw_lines: |
|
3159 | for l in raw_lines: | |
3168 | for pat in strip_from_start: |
|
3160 | for pat in strip_from_start: | |
3169 | l = pat.sub('',l) |
|
3161 | l = pat.sub('',l) | |
3170 | lines.append(l) |
|
3162 | lines.append(l) | |
3171 |
|
3163 | |||
3172 | block = "\n".join(lines) + '\n' |
|
3164 | block = "\n".join(lines) + '\n' | |
3173 | #print "block:\n",block |
|
3165 | #print "block:\n",block | |
3174 | return block |
|
3166 | return block | |
3175 |
|
3167 | |||
3176 | def _execute_block(self, block, par): |
|
3168 | def _execute_block(self, block, par): | |
3177 | """ Execute a block, or store it in a variable, per the user's request. |
|
3169 | """ Execute a block, or store it in a variable, per the user's request. | |
3178 | """ |
|
3170 | """ | |
3179 | if not par: |
|
3171 | if not par: | |
3180 | b = textwrap.dedent(block) |
|
3172 | b = textwrap.dedent(block) | |
3181 | self.user_ns['pasted_block'] = b |
|
3173 | self.user_ns['pasted_block'] = b | |
3182 | exec b in self.user_ns |
|
3174 | exec b in self.user_ns | |
3183 | else: |
|
3175 | else: | |
3184 | self.user_ns[par] = SList(block.splitlines()) |
|
3176 | self.user_ns[par] = SList(block.splitlines()) | |
3185 | print "Block assigned to '%s'" % par |
|
3177 | print "Block assigned to '%s'" % par | |
3186 |
|
3178 | |||
3187 | def magic_quickref(self,arg): |
|
3179 | def magic_quickref(self,arg): | |
3188 | """ Show a quick reference sheet """ |
|
3180 | """ Show a quick reference sheet """ | |
3189 | import IPython.core.usage |
|
3181 | import IPython.core.usage | |
3190 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3182 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3191 |
|
3183 | |||
3192 | page.page(qr) |
|
3184 | page.page(qr) | |
3193 |
|
3185 | |||
3194 | def magic_doctest_mode(self,parameter_s=''): |
|
3186 | def magic_doctest_mode(self,parameter_s=''): | |
3195 | """Toggle doctest mode on and off. |
|
3187 | """Toggle doctest mode on and off. | |
3196 |
|
3188 | |||
3197 | This mode is intended to make IPython behave as much as possible like a |
|
3189 | This mode is intended to make IPython behave as much as possible like a | |
3198 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3190 | plain Python shell, from the perspective of how its prompts, exceptions | |
3199 | and output look. This makes it easy to copy and paste parts of a |
|
3191 | and output look. This makes it easy to copy and paste parts of a | |
3200 | session into doctests. It does so by: |
|
3192 | session into doctests. It does so by: | |
3201 |
|
3193 | |||
3202 | - Changing the prompts to the classic ``>>>`` ones. |
|
3194 | - Changing the prompts to the classic ``>>>`` ones. | |
3203 | - Changing the exception reporting mode to 'Plain'. |
|
3195 | - Changing the exception reporting mode to 'Plain'. | |
3204 | - Disabling pretty-printing of output. |
|
3196 | - Disabling pretty-printing of output. | |
3205 |
|
3197 | |||
3206 | Note that IPython also supports the pasting of code snippets that have |
|
3198 | Note that IPython also supports the pasting of code snippets that have | |
3207 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3199 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3208 | doctests from files or docstrings (even if they have leading |
|
3200 | doctests from files or docstrings (even if they have leading | |
3209 | whitespace), and the code will execute correctly. You can then use |
|
3201 | whitespace), and the code will execute correctly. You can then use | |
3210 | '%history -t' to see the translated history; this will give you the |
|
3202 | '%history -t' to see the translated history; this will give you the | |
3211 | input after removal of all the leading prompts and whitespace, which |
|
3203 | input after removal of all the leading prompts and whitespace, which | |
3212 | can be pasted back into an editor. |
|
3204 | can be pasted back into an editor. | |
3213 |
|
3205 | |||
3214 | With these features, you can switch into this mode easily whenever you |
|
3206 | With these features, you can switch into this mode easily whenever you | |
3215 | need to do testing and changes to doctests, without having to leave |
|
3207 | need to do testing and changes to doctests, without having to leave | |
3216 | your existing IPython session. |
|
3208 | your existing IPython session. | |
3217 | """ |
|
3209 | """ | |
3218 |
|
3210 | |||
3219 | from IPython.utils.ipstruct import Struct |
|
3211 | from IPython.utils.ipstruct import Struct | |
3220 |
|
3212 | |||
3221 | # Shorthands |
|
3213 | # Shorthands | |
3222 | shell = self.shell |
|
3214 | shell = self.shell | |
3223 | oc = shell.displayhook |
|
3215 | oc = shell.displayhook | |
3224 | meta = shell.meta |
|
3216 | meta = shell.meta | |
3225 | disp_formatter = self.shell.display_formatter |
|
3217 | disp_formatter = self.shell.display_formatter | |
3226 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3218 | ptformatter = disp_formatter.formatters['text/plain'] | |
3227 | # dstore is a data store kept in the instance metadata bag to track any |
|
3219 | # dstore is a data store kept in the instance metadata bag to track any | |
3228 | # changes we make, so we can undo them later. |
|
3220 | # changes we make, so we can undo them later. | |
3229 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3221 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3230 | save_dstore = dstore.setdefault |
|
3222 | save_dstore = dstore.setdefault | |
3231 |
|
3223 | |||
3232 | # save a few values we'll need to recover later |
|
3224 | # save a few values we'll need to recover later | |
3233 | mode = save_dstore('mode',False) |
|
3225 | mode = save_dstore('mode',False) | |
3234 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3226 | save_dstore('rc_pprint',ptformatter.pprint) | |
3235 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3227 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3236 | save_dstore('rc_separate_out',shell.separate_out) |
|
3228 | save_dstore('rc_separate_out',shell.separate_out) | |
3237 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3229 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3238 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3230 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3239 | save_dstore('rc_separate_in',shell.separate_in) |
|
3231 | save_dstore('rc_separate_in',shell.separate_in) | |
3240 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3232 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
3241 |
|
3233 | |||
3242 | if mode == False: |
|
3234 | if mode == False: | |
3243 | # turn on |
|
3235 | # turn on | |
3244 | oc.prompt1.p_template = '>>> ' |
|
3236 | oc.prompt1.p_template = '>>> ' | |
3245 | oc.prompt2.p_template = '... ' |
|
3237 | oc.prompt2.p_template = '... ' | |
3246 | oc.prompt_out.p_template = '' |
|
3238 | oc.prompt_out.p_template = '' | |
3247 |
|
3239 | |||
3248 | # Prompt separators like plain python |
|
3240 | # Prompt separators like plain python | |
3249 | oc.input_sep = oc.prompt1.sep = '' |
|
3241 | oc.input_sep = oc.prompt1.sep = '' | |
3250 | oc.output_sep = '' |
|
3242 | oc.output_sep = '' | |
3251 | oc.output_sep2 = '' |
|
3243 | oc.output_sep2 = '' | |
3252 |
|
3244 | |||
3253 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3245 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3254 | oc.prompt_out.pad_left = False |
|
3246 | oc.prompt_out.pad_left = False | |
3255 |
|
3247 | |||
3256 | ptformatter.pprint = False |
|
3248 | ptformatter.pprint = False | |
3257 | disp_formatter.plain_text_only = True |
|
3249 | disp_formatter.plain_text_only = True | |
3258 |
|
3250 | |||
3259 | shell.magic_xmode('Plain') |
|
3251 | shell.magic_xmode('Plain') | |
3260 | else: |
|
3252 | else: | |
3261 | # turn off |
|
3253 | # turn off | |
3262 | oc.prompt1.p_template = shell.prompt_in1 |
|
3254 | oc.prompt1.p_template = shell.prompt_in1 | |
3263 | oc.prompt2.p_template = shell.prompt_in2 |
|
3255 | oc.prompt2.p_template = shell.prompt_in2 | |
3264 | oc.prompt_out.p_template = shell.prompt_out |
|
3256 | oc.prompt_out.p_template = shell.prompt_out | |
3265 |
|
3257 | |||
3266 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3258 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3267 |
|
3259 | |||
3268 | oc.output_sep = dstore.rc_separate_out |
|
3260 | oc.output_sep = dstore.rc_separate_out | |
3269 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3261 | oc.output_sep2 = dstore.rc_separate_out2 | |
3270 |
|
3262 | |||
3271 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3263 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3272 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3264 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3273 |
|
3265 | |||
3274 | ptformatter.pprint = dstore.rc_pprint |
|
3266 | ptformatter.pprint = dstore.rc_pprint | |
3275 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3267 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
3276 |
|
3268 | |||
3277 | shell.magic_xmode(dstore.xmode) |
|
3269 | shell.magic_xmode(dstore.xmode) | |
3278 |
|
3270 | |||
3279 | # Store new mode and inform |
|
3271 | # Store new mode and inform | |
3280 | dstore.mode = bool(1-int(mode)) |
|
3272 | dstore.mode = bool(1-int(mode)) | |
3281 | mode_label = ['OFF','ON'][dstore.mode] |
|
3273 | mode_label = ['OFF','ON'][dstore.mode] | |
3282 | print 'Doctest mode is:', mode_label |
|
3274 | print 'Doctest mode is:', mode_label | |
3283 |
|
3275 | |||
3284 | def magic_gui(self, parameter_s=''): |
|
3276 | def magic_gui(self, parameter_s=''): | |
3285 | """Enable or disable IPython GUI event loop integration. |
|
3277 | """Enable or disable IPython GUI event loop integration. | |
3286 |
|
3278 | |||
3287 | %gui [GUINAME] |
|
3279 | %gui [GUINAME] | |
3288 |
|
3280 | |||
3289 | This magic replaces IPython's threaded shells that were activated |
|
3281 | This magic replaces IPython's threaded shells that were activated | |
3290 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3282 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3291 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3283 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3292 | interrupts should work without any problems. The following toolkits |
|
3284 | interrupts should work without any problems. The following toolkits | |
3293 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3285 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3294 |
|
3286 | |||
3295 | %gui wx # enable wxPython event loop integration |
|
3287 | %gui wx # enable wxPython event loop integration | |
3296 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3288 | %gui qt4|qt # enable PyQt4 event loop integration | |
3297 | %gui gtk # enable PyGTK event loop integration |
|
3289 | %gui gtk # enable PyGTK event loop integration | |
3298 | %gui tk # enable Tk event loop integration |
|
3290 | %gui tk # enable Tk event loop integration | |
3299 | %gui # disable all event loop integration |
|
3291 | %gui # disable all event loop integration | |
3300 |
|
3292 | |||
3301 | WARNING: after any of these has been called you can simply create |
|
3293 | WARNING: after any of these has been called you can simply create | |
3302 | an application object, but DO NOT start the event loop yourself, as |
|
3294 | an application object, but DO NOT start the event loop yourself, as | |
3303 | we have already handled that. |
|
3295 | we have already handled that. | |
3304 | """ |
|
3296 | """ | |
3305 | from IPython.lib.inputhook import enable_gui |
|
3297 | from IPython.lib.inputhook import enable_gui | |
3306 | opts, arg = self.parse_options(parameter_s, '') |
|
3298 | opts, arg = self.parse_options(parameter_s, '') | |
3307 | if arg=='': arg = None |
|
3299 | if arg=='': arg = None | |
3308 | return enable_gui(arg) |
|
3300 | return enable_gui(arg) | |
3309 |
|
3301 | |||
3310 | def magic_load_ext(self, module_str): |
|
3302 | def magic_load_ext(self, module_str): | |
3311 | """Load an IPython extension by its module name.""" |
|
3303 | """Load an IPython extension by its module name.""" | |
3312 | return self.extension_manager.load_extension(module_str) |
|
3304 | return self.extension_manager.load_extension(module_str) | |
3313 |
|
3305 | |||
3314 | def magic_unload_ext(self, module_str): |
|
3306 | def magic_unload_ext(self, module_str): | |
3315 | """Unload an IPython extension by its module name.""" |
|
3307 | """Unload an IPython extension by its module name.""" | |
3316 | self.extension_manager.unload_extension(module_str) |
|
3308 | self.extension_manager.unload_extension(module_str) | |
3317 |
|
3309 | |||
3318 | def magic_reload_ext(self, module_str): |
|
3310 | def magic_reload_ext(self, module_str): | |
3319 | """Reload an IPython extension by its module name.""" |
|
3311 | """Reload an IPython extension by its module name.""" | |
3320 | self.extension_manager.reload_extension(module_str) |
|
3312 | self.extension_manager.reload_extension(module_str) | |
3321 |
|
3313 | |||
3322 | @testdec.skip_doctest |
|
3314 | @testdec.skip_doctest | |
3323 | def magic_install_profiles(self, s): |
|
3315 | def magic_install_profiles(self, s): | |
3324 | """Install the default IPython profiles into the .ipython dir. |
|
3316 | """Install the default IPython profiles into the .ipython dir. | |
3325 |
|
3317 | |||
3326 | If the default profiles have already been installed, they will not |
|
3318 | If the default profiles have already been installed, they will not | |
3327 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3319 | be overwritten. You can force overwriting them by using the ``-o`` | |
3328 | option:: |
|
3320 | option:: | |
3329 |
|
3321 | |||
3330 | In [1]: %install_profiles -o |
|
3322 | In [1]: %install_profiles -o | |
3331 | """ |
|
3323 | """ | |
3332 | if '-o' in s: |
|
3324 | if '-o' in s: | |
3333 | overwrite = True |
|
3325 | overwrite = True | |
3334 | else: |
|
3326 | else: | |
3335 | overwrite = False |
|
3327 | overwrite = False | |
3336 | from IPython.config import profile |
|
3328 | from IPython.config import profile | |
3337 | profile_dir = os.path.split(profile.__file__)[0] |
|
3329 | profile_dir = os.path.split(profile.__file__)[0] | |
3338 | ipython_dir = self.ipython_dir |
|
3330 | ipython_dir = self.ipython_dir | |
3339 | files = os.listdir(profile_dir) |
|
3331 | files = os.listdir(profile_dir) | |
3340 |
|
3332 | |||
3341 | to_install = [] |
|
3333 | to_install = [] | |
3342 | for f in files: |
|
3334 | for f in files: | |
3343 | if f.startswith('ipython_config'): |
|
3335 | if f.startswith('ipython_config'): | |
3344 | src = os.path.join(profile_dir, f) |
|
3336 | src = os.path.join(profile_dir, f) | |
3345 | dst = os.path.join(ipython_dir, f) |
|
3337 | dst = os.path.join(ipython_dir, f) | |
3346 | if (not os.path.isfile(dst)) or overwrite: |
|
3338 | if (not os.path.isfile(dst)) or overwrite: | |
3347 | to_install.append((f, src, dst)) |
|
3339 | to_install.append((f, src, dst)) | |
3348 | if len(to_install)>0: |
|
3340 | if len(to_install)>0: | |
3349 | print "Installing profiles to: ", ipython_dir |
|
3341 | print "Installing profiles to: ", ipython_dir | |
3350 | for (f, src, dst) in to_install: |
|
3342 | for (f, src, dst) in to_install: | |
3351 | shutil.copy(src, dst) |
|
3343 | shutil.copy(src, dst) | |
3352 | print " %s" % f |
|
3344 | print " %s" % f | |
3353 |
|
3345 | |||
3354 | def magic_install_default_config(self, s): |
|
3346 | def magic_install_default_config(self, s): | |
3355 | """Install IPython's default config file into the .ipython dir. |
|
3347 | """Install IPython's default config file into the .ipython dir. | |
3356 |
|
3348 | |||
3357 | If the default config file (:file:`ipython_config.py`) is already |
|
3349 | If the default config file (:file:`ipython_config.py`) is already | |
3358 | installed, it will not be overwritten. You can force overwriting |
|
3350 | installed, it will not be overwritten. You can force overwriting | |
3359 | by using the ``-o`` option:: |
|
3351 | by using the ``-o`` option:: | |
3360 |
|
3352 | |||
3361 | In [1]: %install_default_config |
|
3353 | In [1]: %install_default_config | |
3362 | """ |
|
3354 | """ | |
3363 | if '-o' in s: |
|
3355 | if '-o' in s: | |
3364 | overwrite = True |
|
3356 | overwrite = True | |
3365 | else: |
|
3357 | else: | |
3366 | overwrite = False |
|
3358 | overwrite = False | |
3367 | from IPython.config import default |
|
3359 | from IPython.config import default | |
3368 | config_dir = os.path.split(default.__file__)[0] |
|
3360 | config_dir = os.path.split(default.__file__)[0] | |
3369 | ipython_dir = self.ipython_dir |
|
3361 | ipython_dir = self.ipython_dir | |
3370 | default_config_file_name = 'ipython_config.py' |
|
3362 | default_config_file_name = 'ipython_config.py' | |
3371 | src = os.path.join(config_dir, default_config_file_name) |
|
3363 | src = os.path.join(config_dir, default_config_file_name) | |
3372 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3364 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3373 | if (not os.path.isfile(dst)) or overwrite: |
|
3365 | if (not os.path.isfile(dst)) or overwrite: | |
3374 | shutil.copy(src, dst) |
|
3366 | shutil.copy(src, dst) | |
3375 | print "Installing default config file: %s" % dst |
|
3367 | print "Installing default config file: %s" % dst | |
3376 |
|
3368 | |||
3377 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3369 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3378 | # handling and modify slightly %run |
|
3370 | # handling and modify slightly %run | |
3379 |
|
3371 | |||
3380 | @testdec.skip_doctest |
|
3372 | @testdec.skip_doctest | |
3381 | def _pylab_magic_run(self, parameter_s=''): |
|
3373 | def _pylab_magic_run(self, parameter_s=''): | |
3382 | Magic.magic_run(self, parameter_s, |
|
3374 | Magic.magic_run(self, parameter_s, | |
3383 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3375 | runner=mpl_runner(self.shell.safe_execfile)) | |
3384 |
|
3376 | |||
3385 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3377 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3386 |
|
3378 | |||
3387 | @testdec.skip_doctest |
|
3379 | @testdec.skip_doctest | |
3388 | def magic_pylab(self, s): |
|
3380 | def magic_pylab(self, s): | |
3389 | """Load numpy and matplotlib to work interactively. |
|
3381 | """Load numpy and matplotlib to work interactively. | |
3390 |
|
3382 | |||
3391 | %pylab [GUINAME] |
|
3383 | %pylab [GUINAME] | |
3392 |
|
3384 | |||
3393 | This function lets you activate pylab (matplotlib, numpy and |
|
3385 | This function lets you activate pylab (matplotlib, numpy and | |
3394 | interactive support) at any point during an IPython session. |
|
3386 | interactive support) at any point during an IPython session. | |
3395 |
|
3387 | |||
3396 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3388 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3397 | pylab and mlab, as well as all names from numpy and pylab. |
|
3389 | pylab and mlab, as well as all names from numpy and pylab. | |
3398 |
|
3390 | |||
3399 | Parameters |
|
3391 | Parameters | |
3400 | ---------- |
|
3392 | ---------- | |
3401 | guiname : optional |
|
3393 | guiname : optional | |
3402 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or |
|
3394 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or | |
3403 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3395 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3404 | otherwise matplotlib's default (which you can override in your |
|
3396 | otherwise matplotlib's default (which you can override in your | |
3405 | matplotlib config file) is used. |
|
3397 | matplotlib config file) is used. | |
3406 |
|
3398 | |||
3407 | Examples |
|
3399 | Examples | |
3408 | -------- |
|
3400 | -------- | |
3409 | In this case, where the MPL default is TkAgg: |
|
3401 | In this case, where the MPL default is TkAgg: | |
3410 | In [2]: %pylab |
|
3402 | In [2]: %pylab | |
3411 |
|
3403 | |||
3412 | Welcome to pylab, a matplotlib-based Python environment. |
|
3404 | Welcome to pylab, a matplotlib-based Python environment. | |
3413 | Backend in use: TkAgg |
|
3405 | Backend in use: TkAgg | |
3414 | For more information, type 'help(pylab)'. |
|
3406 | For more information, type 'help(pylab)'. | |
3415 |
|
3407 | |||
3416 | But you can explicitly request a different backend: |
|
3408 | But you can explicitly request a different backend: | |
3417 | In [3]: %pylab qt |
|
3409 | In [3]: %pylab qt | |
3418 |
|
3410 | |||
3419 | Welcome to pylab, a matplotlib-based Python environment. |
|
3411 | Welcome to pylab, a matplotlib-based Python environment. | |
3420 | Backend in use: Qt4Agg |
|
3412 | Backend in use: Qt4Agg | |
3421 | For more information, type 'help(pylab)'. |
|
3413 | For more information, type 'help(pylab)'. | |
3422 | """ |
|
3414 | """ | |
3423 | self.shell.enable_pylab(s) |
|
3415 | self.shell.enable_pylab(s) | |
3424 |
|
3416 | |||
3425 | def magic_tb(self, s): |
|
3417 | def magic_tb(self, s): | |
3426 | """Print the last traceback with the currently active exception mode. |
|
3418 | """Print the last traceback with the currently active exception mode. | |
3427 |
|
3419 | |||
3428 | See %xmode for changing exception reporting modes.""" |
|
3420 | See %xmode for changing exception reporting modes.""" | |
3429 | self.shell.showtraceback() |
|
3421 | self.shell.showtraceback() | |
3430 |
|
3422 | |||
3431 | @testdec.skip_doctest |
|
3423 | @testdec.skip_doctest | |
3432 | def magic_precision(self, s=''): |
|
3424 | def magic_precision(self, s=''): | |
3433 | """Set floating point precision for pretty printing. |
|
3425 | """Set floating point precision for pretty printing. | |
3434 |
|
3426 | |||
3435 | Can set either integer precision or a format string. |
|
3427 | Can set either integer precision or a format string. | |
3436 |
|
3428 | |||
3437 | If numpy has been imported and precision is an int, |
|
3429 | If numpy has been imported and precision is an int, | |
3438 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3430 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
3439 |
|
3431 | |||
3440 | If no argument is given, defaults will be restored. |
|
3432 | If no argument is given, defaults will be restored. | |
3441 |
|
3433 | |||
3442 | Examples |
|
3434 | Examples | |
3443 | -------- |
|
3435 | -------- | |
3444 | :: |
|
3436 | :: | |
3445 |
|
3437 | |||
3446 | In [1]: from math import pi |
|
3438 | In [1]: from math import pi | |
3447 |
|
3439 | |||
3448 | In [2]: %precision 3 |
|
3440 | In [2]: %precision 3 | |
3449 | Out[2]: '%.3f' |
|
3441 | Out[2]: '%.3f' | |
3450 |
|
3442 | |||
3451 | In [3]: pi |
|
3443 | In [3]: pi | |
3452 | Out[3]: 3.142 |
|
3444 | Out[3]: 3.142 | |
3453 |
|
3445 | |||
3454 | In [4]: %precision %i |
|
3446 | In [4]: %precision %i | |
3455 | Out[4]: '%i' |
|
3447 | Out[4]: '%i' | |
3456 |
|
3448 | |||
3457 | In [5]: pi |
|
3449 | In [5]: pi | |
3458 | Out[5]: 3 |
|
3450 | Out[5]: 3 | |
3459 |
|
3451 | |||
3460 | In [6]: %precision %e |
|
3452 | In [6]: %precision %e | |
3461 | Out[6]: '%e' |
|
3453 | Out[6]: '%e' | |
3462 |
|
3454 | |||
3463 | In [7]: pi**10 |
|
3455 | In [7]: pi**10 | |
3464 | Out[7]: 9.364805e+04 |
|
3456 | Out[7]: 9.364805e+04 | |
3465 |
|
3457 | |||
3466 | In [8]: %precision |
|
3458 | In [8]: %precision | |
3467 | Out[8]: '%r' |
|
3459 | Out[8]: '%r' | |
3468 |
|
3460 | |||
3469 | In [9]: pi**10 |
|
3461 | In [9]: pi**10 | |
3470 | Out[9]: 93648.047476082982 |
|
3462 | Out[9]: 93648.047476082982 | |
3471 |
|
3463 | |||
3472 | """ |
|
3464 | """ | |
3473 |
|
3465 | |||
3474 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3466 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
3475 | ptformatter.float_precision = s |
|
3467 | ptformatter.float_precision = s | |
3476 | return ptformatter.float_format |
|
3468 | return ptformatter.float_format | |
3477 |
|
3469 | |||
3478 | # end Magic |
|
3470 | # end Magic |
@@ -1,1025 +1,1025 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | Prefiltering components. |
|
4 | Prefiltering components. | |
5 |
|
5 | |||
6 | Prefilters transform user input before it is exec'd by Python. These |
|
6 | Prefilters transform user input before it is exec'd by Python. These | |
7 | transforms are used to implement additional syntax such as !ls and %magic. |
|
7 | transforms are used to implement additional syntax such as !ls and %magic. | |
8 |
|
8 | |||
9 | Authors: |
|
9 | Authors: | |
10 |
|
10 | |||
11 | * Brian Granger |
|
11 | * Brian Granger | |
12 | * Fernando Perez |
|
12 | * Fernando Perez | |
13 | * Dan Milstein |
|
13 | * Dan Milstein | |
14 | * Ville Vainio |
|
14 | * Ville Vainio | |
15 | """ |
|
15 | """ | |
16 |
|
16 | |||
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Copyright (C) 2008-2009 The IPython Development Team |
|
18 | # Copyright (C) 2008-2009 The IPython Development Team | |
19 | # |
|
19 | # | |
20 | # Distributed under the terms of the BSD License. The full license is in |
|
20 | # Distributed under the terms of the BSD License. The full license is in | |
21 | # the file COPYING, distributed as part of this software. |
|
21 | # the file COPYING, distributed as part of this software. | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Imports |
|
25 | # Imports | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 | import __builtin__ |
|
28 | import __builtin__ | |
29 | import codeop |
|
29 | import codeop | |
30 | import re |
|
30 | import re | |
31 |
|
31 | |||
32 | from IPython.core.alias import AliasManager |
|
32 | from IPython.core.alias import AliasManager | |
33 | from IPython.core.autocall import IPyAutocall |
|
33 | from IPython.core.autocall import IPyAutocall | |
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.core.macro import Macro |
|
35 | from IPython.core.macro import Macro | |
36 | from IPython.core.splitinput import split_user_input |
|
36 | from IPython.core.splitinput import split_user_input | |
37 | from IPython.core import page |
|
37 | from IPython.core import page | |
38 |
|
38 | |||
39 | from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance |
|
39 | from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance | |
40 | import IPython.utils.io |
|
40 | import IPython.utils.io | |
41 | from IPython.utils.text import make_quoted_expr |
|
41 | from IPython.utils.text import make_quoted_expr | |
42 | from IPython.utils.autoattr import auto_attr |
|
42 | from IPython.utils.autoattr import auto_attr | |
43 |
|
43 | |||
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 | # Global utilities, errors and constants |
|
45 | # Global utilities, errors and constants | |
46 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
47 |
|
47 | |||
48 | # Warning, these cannot be changed unless various regular expressions |
|
48 | # Warning, these cannot be changed unless various regular expressions | |
49 | # are updated in a number of places. Not great, but at least we told you. |
|
49 | # are updated in a number of places. Not great, but at least we told you. | |
50 | ESC_SHELL = '!' |
|
50 | ESC_SHELL = '!' | |
51 | ESC_SH_CAP = '!!' |
|
51 | ESC_SH_CAP = '!!' | |
52 | ESC_HELP = '?' |
|
52 | ESC_HELP = '?' | |
53 | ESC_MAGIC = '%' |
|
53 | ESC_MAGIC = '%' | |
54 | ESC_QUOTE = ',' |
|
54 | ESC_QUOTE = ',' | |
55 | ESC_QUOTE2 = ';' |
|
55 | ESC_QUOTE2 = ';' | |
56 | ESC_PAREN = '/' |
|
56 | ESC_PAREN = '/' | |
57 |
|
57 | |||
58 |
|
58 | |||
59 | class PrefilterError(Exception): |
|
59 | class PrefilterError(Exception): | |
60 | pass |
|
60 | pass | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | # RegExp to identify potential function names |
|
63 | # RegExp to identify potential function names | |
64 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
64 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
65 |
|
65 | |||
66 | # RegExp to exclude strings with this start from autocalling. In |
|
66 | # RegExp to exclude strings with this start from autocalling. In | |
67 | # particular, all binary operators should be excluded, so that if foo is |
|
67 | # particular, all binary operators should be excluded, so that if foo is | |
68 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
68 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The | |
69 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
69 | # characters '!=()' don't need to be checked for, as the checkPythonChars | |
70 | # routine explicitely does so, to catch direct calls and rebindings of |
|
70 | # routine explicitely does so, to catch direct calls and rebindings of | |
71 | # existing names. |
|
71 | # existing names. | |
72 |
|
72 | |||
73 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
73 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
74 | # it affects the rest of the group in square brackets. |
|
74 | # it affects the rest of the group in square brackets. | |
75 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
75 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' | |
76 | r'|^is |^not |^in |^and |^or ') |
|
76 | r'|^is |^not |^in |^and |^or ') | |
77 |
|
77 | |||
78 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
78 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
79 | # (experimental). For this to work, the line_split regexp would need |
|
79 | # (experimental). For this to work, the line_split regexp would need | |
80 | # to be modified so it wouldn't break things at '['. That line is |
|
80 | # to be modified so it wouldn't break things at '['. That line is | |
81 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
81 | # nasty enough that I shouldn't change it until I can test it _well_. | |
82 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
82 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
83 |
|
83 | |||
84 |
|
84 | |||
85 | # Handler Check Utilities |
|
85 | # Handler Check Utilities | |
86 | def is_shadowed(identifier, ip): |
|
86 | def is_shadowed(identifier, ip): | |
87 | """Is the given identifier defined in one of the namespaces which shadow |
|
87 | """Is the given identifier defined in one of the namespaces which shadow | |
88 | the alias and magic namespaces? Note that an identifier is different |
|
88 | the alias and magic namespaces? Note that an identifier is different | |
89 | than ifun, because it can not contain a '.' character.""" |
|
89 | than ifun, because it can not contain a '.' character.""" | |
90 | # This is much safer than calling ofind, which can change state |
|
90 | # This is much safer than calling ofind, which can change state | |
91 | return (identifier in ip.user_ns \ |
|
91 | return (identifier in ip.user_ns \ | |
92 | or identifier in ip.internal_ns \ |
|
92 | or identifier in ip.internal_ns \ | |
93 | or identifier in ip.ns_table['builtin']) |
|
93 | or identifier in ip.ns_table['builtin']) | |
94 |
|
94 | |||
95 |
|
95 | |||
96 | #----------------------------------------------------------------------------- |
|
96 | #----------------------------------------------------------------------------- | |
97 | # The LineInfo class used throughout |
|
97 | # The LineInfo class used throughout | |
98 | #----------------------------------------------------------------------------- |
|
98 | #----------------------------------------------------------------------------- | |
99 |
|
99 | |||
100 |
|
100 | |||
101 | class LineInfo(object): |
|
101 | class LineInfo(object): | |
102 | """A single line of input and associated info. |
|
102 | """A single line of input and associated info. | |
103 |
|
103 | |||
104 | Includes the following as properties: |
|
104 | Includes the following as properties: | |
105 |
|
105 | |||
106 | line |
|
106 | line | |
107 | The original, raw line |
|
107 | The original, raw line | |
108 |
|
108 | |||
109 | continue_prompt |
|
109 | continue_prompt | |
110 | Is this line a continuation in a sequence of multiline input? |
|
110 | Is this line a continuation in a sequence of multiline input? | |
111 |
|
111 | |||
112 | pre |
|
112 | pre | |
113 | The initial esc character or whitespace. |
|
113 | The initial esc character or whitespace. | |
114 |
|
114 | |||
115 | pre_char |
|
115 | pre_char | |
116 | The escape character(s) in pre or the empty string if there isn't one. |
|
116 | The escape character(s) in pre or the empty string if there isn't one. | |
117 | Note that '!!' is a possible value for pre_char. Otherwise it will |
|
117 | Note that '!!' is a possible value for pre_char. Otherwise it will | |
118 | always be a single character. |
|
118 | always be a single character. | |
119 |
|
119 | |||
120 | pre_whitespace |
|
120 | pre_whitespace | |
121 | The leading whitespace from pre if it exists. If there is a pre_char, |
|
121 | The leading whitespace from pre if it exists. If there is a pre_char, | |
122 | this is just ''. |
|
122 | this is just ''. | |
123 |
|
123 | |||
124 | ifun |
|
124 | ifun | |
125 | The 'function part', which is basically the maximal initial sequence |
|
125 | The 'function part', which is basically the maximal initial sequence | |
126 | of valid python identifiers and the '.' character. This is what is |
|
126 | of valid python identifiers and the '.' character. This is what is | |
127 | checked for alias and magic transformations, used for auto-calling, |
|
127 | checked for alias and magic transformations, used for auto-calling, | |
128 | etc. |
|
128 | etc. | |
129 |
|
129 | |||
130 | the_rest |
|
130 | the_rest | |
131 | Everything else on the line. |
|
131 | Everything else on the line. | |
132 | """ |
|
132 | """ | |
133 | def __init__(self, line, continue_prompt): |
|
133 | def __init__(self, line, continue_prompt): | |
134 | self.line = line |
|
134 | self.line = line | |
135 | self.continue_prompt = continue_prompt |
|
135 | self.continue_prompt = continue_prompt | |
136 | self.pre, self.ifun, self.the_rest = split_user_input(line) |
|
136 | self.pre, self.ifun, self.the_rest = split_user_input(line) | |
137 |
|
137 | |||
138 | self.pre_char = self.pre.strip() |
|
138 | self.pre_char = self.pre.strip() | |
139 | if self.pre_char: |
|
139 | if self.pre_char: | |
140 | self.pre_whitespace = '' # No whitespace allowd before esc chars |
|
140 | self.pre_whitespace = '' # No whitespace allowd before esc chars | |
141 | else: |
|
141 | else: | |
142 | self.pre_whitespace = self.pre |
|
142 | self.pre_whitespace = self.pre | |
143 |
|
143 | |||
144 | self._oinfo = None |
|
144 | self._oinfo = None | |
145 |
|
145 | |||
146 | def ofind(self, ip): |
|
146 | def ofind(self, ip): | |
147 | """Do a full, attribute-walking lookup of the ifun in the various |
|
147 | """Do a full, attribute-walking lookup of the ifun in the various | |
148 | namespaces for the given IPython InteractiveShell instance. |
|
148 | namespaces for the given IPython InteractiveShell instance. | |
149 |
|
149 | |||
150 | Return a dict with keys: found,obj,ospace,ismagic |
|
150 | Return a dict with keys: found,obj,ospace,ismagic | |
151 |
|
151 | |||
152 | Note: can cause state changes because of calling getattr, but should |
|
152 | Note: can cause state changes because of calling getattr, but should | |
153 | only be run if autocall is on and if the line hasn't matched any |
|
153 | only be run if autocall is on and if the line hasn't matched any | |
154 | other, less dangerous handlers. |
|
154 | other, less dangerous handlers. | |
155 |
|
155 | |||
156 | Does cache the results of the call, so can be called multiple times |
|
156 | Does cache the results of the call, so can be called multiple times | |
157 | without worrying about *further* damaging state. |
|
157 | without worrying about *further* damaging state. | |
158 | """ |
|
158 | """ | |
159 | if not self._oinfo: |
|
159 | if not self._oinfo: | |
160 | # ip.shell._ofind is actually on the Magic class! |
|
160 | # ip.shell._ofind is actually on the Magic class! | |
161 | self._oinfo = ip.shell._ofind(self.ifun) |
|
161 | self._oinfo = ip.shell._ofind(self.ifun) | |
162 | return self._oinfo |
|
162 | return self._oinfo | |
163 |
|
163 | |||
164 | def __str__(self): |
|
164 | def __str__(self): | |
165 | return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest) |
|
165 | return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest) | |
166 |
|
166 | |||
167 |
|
167 | |||
168 | #----------------------------------------------------------------------------- |
|
168 | #----------------------------------------------------------------------------- | |
169 | # Main Prefilter manager |
|
169 | # Main Prefilter manager | |
170 | #----------------------------------------------------------------------------- |
|
170 | #----------------------------------------------------------------------------- | |
171 |
|
171 | |||
172 |
|
172 | |||
173 | class PrefilterManager(Configurable): |
|
173 | class PrefilterManager(Configurable): | |
174 | """Main prefilter component. |
|
174 | """Main prefilter component. | |
175 |
|
175 | |||
176 | The IPython prefilter is run on all user input before it is run. The |
|
176 | The IPython prefilter is run on all user input before it is run. The | |
177 | prefilter consumes lines of input and produces transformed lines of |
|
177 | prefilter consumes lines of input and produces transformed lines of | |
178 | input. |
|
178 | input. | |
179 |
|
179 | |||
180 | The iplementation consists of two phases: |
|
180 | The iplementation consists of two phases: | |
181 |
|
181 | |||
182 | 1. Transformers |
|
182 | 1. Transformers | |
183 | 2. Checkers and handlers |
|
183 | 2. Checkers and handlers | |
184 |
|
184 | |||
185 | Over time, we plan on deprecating the checkers and handlers and doing |
|
185 | Over time, we plan on deprecating the checkers and handlers and doing | |
186 | everything in the transformers. |
|
186 | everything in the transformers. | |
187 |
|
187 | |||
188 | The transformers are instances of :class:`PrefilterTransformer` and have |
|
188 | The transformers are instances of :class:`PrefilterTransformer` and have | |
189 | a single method :meth:`transform` that takes a line and returns a |
|
189 | a single method :meth:`transform` that takes a line and returns a | |
190 | transformed line. The transformation can be accomplished using any |
|
190 | transformed line. The transformation can be accomplished using any | |
191 | tool, but our current ones use regular expressions for speed. We also |
|
191 | tool, but our current ones use regular expressions for speed. We also | |
192 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. |
|
192 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. | |
193 |
|
193 | |||
194 | After all the transformers have been run, the line is fed to the checkers, |
|
194 | After all the transformers have been run, the line is fed to the checkers, | |
195 | which are instances of :class:`PrefilterChecker`. The line is passed to |
|
195 | which are instances of :class:`PrefilterChecker`. The line is passed to | |
196 | the :meth:`check` method, which either returns `None` or a |
|
196 | the :meth:`check` method, which either returns `None` or a | |
197 | :class:`PrefilterHandler` instance. If `None` is returned, the other |
|
197 | :class:`PrefilterHandler` instance. If `None` is returned, the other | |
198 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, |
|
198 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, | |
199 | the line is passed to the :meth:`handle` method of the returned |
|
199 | the line is passed to the :meth:`handle` method of the returned | |
200 | handler and no further checkers are tried. |
|
200 | handler and no further checkers are tried. | |
201 |
|
201 | |||
202 | Both transformers and checkers have a `priority` attribute, that determines |
|
202 | Both transformers and checkers have a `priority` attribute, that determines | |
203 | the order in which they are called. Smaller priorities are tried first. |
|
203 | the order in which they are called. Smaller priorities are tried first. | |
204 |
|
204 | |||
205 | Both transformers and checkers also have `enabled` attribute, which is |
|
205 | Both transformers and checkers also have `enabled` attribute, which is | |
206 | a boolean that determines if the instance is used. |
|
206 | a boolean that determines if the instance is used. | |
207 |
|
207 | |||
208 | Users or developers can change the priority or enabled attribute of |
|
208 | Users or developers can change the priority or enabled attribute of | |
209 | transformers or checkers, but they must call the :meth:`sort_checkers` |
|
209 | transformers or checkers, but they must call the :meth:`sort_checkers` | |
210 | or :meth:`sort_transformers` method after changing the priority. |
|
210 | or :meth:`sort_transformers` method after changing the priority. | |
211 | """ |
|
211 | """ | |
212 |
|
212 | |||
213 | multi_line_specials = CBool(True, config=True) |
|
213 | multi_line_specials = CBool(True, config=True) | |
214 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
214 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
215 |
|
215 | |||
216 | def __init__(self, shell=None, config=None): |
|
216 | def __init__(self, shell=None, config=None): | |
217 | super(PrefilterManager, self).__init__(shell=shell, config=config) |
|
217 | super(PrefilterManager, self).__init__(shell=shell, config=config) | |
218 | self.shell = shell |
|
218 | self.shell = shell | |
219 | self.init_transformers() |
|
219 | self.init_transformers() | |
220 | self.init_handlers() |
|
220 | self.init_handlers() | |
221 | self.init_checkers() |
|
221 | self.init_checkers() | |
222 |
|
222 | |||
223 | #------------------------------------------------------------------------- |
|
223 | #------------------------------------------------------------------------- | |
224 | # API for managing transformers |
|
224 | # API for managing transformers | |
225 | #------------------------------------------------------------------------- |
|
225 | #------------------------------------------------------------------------- | |
226 |
|
226 | |||
227 | def init_transformers(self): |
|
227 | def init_transformers(self): | |
228 | """Create the default transformers.""" |
|
228 | """Create the default transformers.""" | |
229 | self._transformers = [] |
|
229 | self._transformers = [] | |
230 | for transformer_cls in _default_transformers: |
|
230 | for transformer_cls in _default_transformers: | |
231 | transformer_cls( |
|
231 | transformer_cls( | |
232 | shell=self.shell, prefilter_manager=self, config=self.config |
|
232 | shell=self.shell, prefilter_manager=self, config=self.config | |
233 | ) |
|
233 | ) | |
234 |
|
234 | |||
235 | def sort_transformers(self): |
|
235 | def sort_transformers(self): | |
236 | """Sort the transformers by priority. |
|
236 | """Sort the transformers by priority. | |
237 |
|
237 | |||
238 | This must be called after the priority of a transformer is changed. |
|
238 | This must be called after the priority of a transformer is changed. | |
239 | The :meth:`register_transformer` method calls this automatically. |
|
239 | The :meth:`register_transformer` method calls this automatically. | |
240 | """ |
|
240 | """ | |
241 | self._transformers.sort(key=lambda x: x.priority) |
|
241 | self._transformers.sort(key=lambda x: x.priority) | |
242 |
|
242 | |||
243 | @property |
|
243 | @property | |
244 | def transformers(self): |
|
244 | def transformers(self): | |
245 | """Return a list of checkers, sorted by priority.""" |
|
245 | """Return a list of checkers, sorted by priority.""" | |
246 | return self._transformers |
|
246 | return self._transformers | |
247 |
|
247 | |||
248 | def register_transformer(self, transformer): |
|
248 | def register_transformer(self, transformer): | |
249 | """Register a transformer instance.""" |
|
249 | """Register a transformer instance.""" | |
250 | if transformer not in self._transformers: |
|
250 | if transformer not in self._transformers: | |
251 | self._transformers.append(transformer) |
|
251 | self._transformers.append(transformer) | |
252 | self.sort_transformers() |
|
252 | self.sort_transformers() | |
253 |
|
253 | |||
254 | def unregister_transformer(self, transformer): |
|
254 | def unregister_transformer(self, transformer): | |
255 | """Unregister a transformer instance.""" |
|
255 | """Unregister a transformer instance.""" | |
256 | if transformer in self._transformers: |
|
256 | if transformer in self._transformers: | |
257 | self._transformers.remove(transformer) |
|
257 | self._transformers.remove(transformer) | |
258 |
|
258 | |||
259 | #------------------------------------------------------------------------- |
|
259 | #------------------------------------------------------------------------- | |
260 | # API for managing checkers |
|
260 | # API for managing checkers | |
261 | #------------------------------------------------------------------------- |
|
261 | #------------------------------------------------------------------------- | |
262 |
|
262 | |||
263 | def init_checkers(self): |
|
263 | def init_checkers(self): | |
264 | """Create the default checkers.""" |
|
264 | """Create the default checkers.""" | |
265 | self._checkers = [] |
|
265 | self._checkers = [] | |
266 | for checker in _default_checkers: |
|
266 | for checker in _default_checkers: | |
267 | checker( |
|
267 | checker( | |
268 | shell=self.shell, prefilter_manager=self, config=self.config |
|
268 | shell=self.shell, prefilter_manager=self, config=self.config | |
269 | ) |
|
269 | ) | |
270 |
|
270 | |||
271 | def sort_checkers(self): |
|
271 | def sort_checkers(self): | |
272 | """Sort the checkers by priority. |
|
272 | """Sort the checkers by priority. | |
273 |
|
273 | |||
274 | This must be called after the priority of a checker is changed. |
|
274 | This must be called after the priority of a checker is changed. | |
275 | The :meth:`register_checker` method calls this automatically. |
|
275 | The :meth:`register_checker` method calls this automatically. | |
276 | """ |
|
276 | """ | |
277 | self._checkers.sort(key=lambda x: x.priority) |
|
277 | self._checkers.sort(key=lambda x: x.priority) | |
278 |
|
278 | |||
279 | @property |
|
279 | @property | |
280 | def checkers(self): |
|
280 | def checkers(self): | |
281 | """Return a list of checkers, sorted by priority.""" |
|
281 | """Return a list of checkers, sorted by priority.""" | |
282 | return self._checkers |
|
282 | return self._checkers | |
283 |
|
283 | |||
284 | def register_checker(self, checker): |
|
284 | def register_checker(self, checker): | |
285 | """Register a checker instance.""" |
|
285 | """Register a checker instance.""" | |
286 | if checker not in self._checkers: |
|
286 | if checker not in self._checkers: | |
287 | self._checkers.append(checker) |
|
287 | self._checkers.append(checker) | |
288 | self.sort_checkers() |
|
288 | self.sort_checkers() | |
289 |
|
289 | |||
290 | def unregister_checker(self, checker): |
|
290 | def unregister_checker(self, checker): | |
291 | """Unregister a checker instance.""" |
|
291 | """Unregister a checker instance.""" | |
292 | if checker in self._checkers: |
|
292 | if checker in self._checkers: | |
293 | self._checkers.remove(checker) |
|
293 | self._checkers.remove(checker) | |
294 |
|
294 | |||
295 | #------------------------------------------------------------------------- |
|
295 | #------------------------------------------------------------------------- | |
296 | # API for managing checkers |
|
296 | # API for managing checkers | |
297 | #------------------------------------------------------------------------- |
|
297 | #------------------------------------------------------------------------- | |
298 |
|
298 | |||
299 | def init_handlers(self): |
|
299 | def init_handlers(self): | |
300 | """Create the default handlers.""" |
|
300 | """Create the default handlers.""" | |
301 | self._handlers = {} |
|
301 | self._handlers = {} | |
302 | self._esc_handlers = {} |
|
302 | self._esc_handlers = {} | |
303 | for handler in _default_handlers: |
|
303 | for handler in _default_handlers: | |
304 | handler( |
|
304 | handler( | |
305 | shell=self.shell, prefilter_manager=self, config=self.config |
|
305 | shell=self.shell, prefilter_manager=self, config=self.config | |
306 | ) |
|
306 | ) | |
307 |
|
307 | |||
308 | @property |
|
308 | @property | |
309 | def handlers(self): |
|
309 | def handlers(self): | |
310 | """Return a dict of all the handlers.""" |
|
310 | """Return a dict of all the handlers.""" | |
311 | return self._handlers |
|
311 | return self._handlers | |
312 |
|
312 | |||
313 | def register_handler(self, name, handler, esc_strings): |
|
313 | def register_handler(self, name, handler, esc_strings): | |
314 | """Register a handler instance by name with esc_strings.""" |
|
314 | """Register a handler instance by name with esc_strings.""" | |
315 | self._handlers[name] = handler |
|
315 | self._handlers[name] = handler | |
316 | for esc_str in esc_strings: |
|
316 | for esc_str in esc_strings: | |
317 | self._esc_handlers[esc_str] = handler |
|
317 | self._esc_handlers[esc_str] = handler | |
318 |
|
318 | |||
319 | def unregister_handler(self, name, handler, esc_strings): |
|
319 | def unregister_handler(self, name, handler, esc_strings): | |
320 | """Unregister a handler instance by name with esc_strings.""" |
|
320 | """Unregister a handler instance by name with esc_strings.""" | |
321 | try: |
|
321 | try: | |
322 | del self._handlers[name] |
|
322 | del self._handlers[name] | |
323 | except KeyError: |
|
323 | except KeyError: | |
324 | pass |
|
324 | pass | |
325 | for esc_str in esc_strings: |
|
325 | for esc_str in esc_strings: | |
326 | h = self._esc_handlers.get(esc_str) |
|
326 | h = self._esc_handlers.get(esc_str) | |
327 | if h is handler: |
|
327 | if h is handler: | |
328 | del self._esc_handlers[esc_str] |
|
328 | del self._esc_handlers[esc_str] | |
329 |
|
329 | |||
330 | def get_handler_by_name(self, name): |
|
330 | def get_handler_by_name(self, name): | |
331 | """Get a handler by its name.""" |
|
331 | """Get a handler by its name.""" | |
332 | return self._handlers.get(name) |
|
332 | return self._handlers.get(name) | |
333 |
|
333 | |||
334 | def get_handler_by_esc(self, esc_str): |
|
334 | def get_handler_by_esc(self, esc_str): | |
335 | """Get a handler by its escape string.""" |
|
335 | """Get a handler by its escape string.""" | |
336 | return self._esc_handlers.get(esc_str) |
|
336 | return self._esc_handlers.get(esc_str) | |
337 |
|
337 | |||
338 | #------------------------------------------------------------------------- |
|
338 | #------------------------------------------------------------------------- | |
339 | # Main prefiltering API |
|
339 | # Main prefiltering API | |
340 | #------------------------------------------------------------------------- |
|
340 | #------------------------------------------------------------------------- | |
341 |
|
341 | |||
342 | def prefilter_line_info(self, line_info): |
|
342 | def prefilter_line_info(self, line_info): | |
343 | """Prefilter a line that has been converted to a LineInfo object. |
|
343 | """Prefilter a line that has been converted to a LineInfo object. | |
344 |
|
344 | |||
345 | This implements the checker/handler part of the prefilter pipe. |
|
345 | This implements the checker/handler part of the prefilter pipe. | |
346 | """ |
|
346 | """ | |
347 | # print "prefilter_line_info: ", line_info |
|
347 | # print "prefilter_line_info: ", line_info | |
348 | handler = self.find_handler(line_info) |
|
348 | handler = self.find_handler(line_info) | |
349 | return handler.handle(line_info) |
|
349 | return handler.handle(line_info) | |
350 |
|
350 | |||
351 | def find_handler(self, line_info): |
|
351 | def find_handler(self, line_info): | |
352 | """Find a handler for the line_info by trying checkers.""" |
|
352 | """Find a handler for the line_info by trying checkers.""" | |
353 | for checker in self.checkers: |
|
353 | for checker in self.checkers: | |
354 | if checker.enabled: |
|
354 | if checker.enabled: | |
355 | handler = checker.check(line_info) |
|
355 | handler = checker.check(line_info) | |
356 | if handler: |
|
356 | if handler: | |
357 | return handler |
|
357 | return handler | |
358 | return self.get_handler_by_name('normal') |
|
358 | return self.get_handler_by_name('normal') | |
359 |
|
359 | |||
360 | def transform_line(self, line, continue_prompt): |
|
360 | def transform_line(self, line, continue_prompt): | |
361 | """Calls the enabled transformers in order of increasing priority.""" |
|
361 | """Calls the enabled transformers in order of increasing priority.""" | |
362 | for transformer in self.transformers: |
|
362 | for transformer in self.transformers: | |
363 | if transformer.enabled: |
|
363 | if transformer.enabled: | |
364 | line = transformer.transform(line, continue_prompt) |
|
364 | line = transformer.transform(line, continue_prompt) | |
365 | return line |
|
365 | return line | |
366 |
|
366 | |||
367 | def prefilter_line(self, line, continue_prompt=False): |
|
367 | def prefilter_line(self, line, continue_prompt=False): | |
368 | """Prefilter a single input line as text. |
|
368 | """Prefilter a single input line as text. | |
369 |
|
369 | |||
370 | This method prefilters a single line of text by calling the |
|
370 | This method prefilters a single line of text by calling the | |
371 | transformers and then the checkers/handlers. |
|
371 | transformers and then the checkers/handlers. | |
372 | """ |
|
372 | """ | |
373 |
|
373 | |||
374 | # print "prefilter_line: ", line, continue_prompt |
|
374 | # print "prefilter_line: ", line, continue_prompt | |
375 | # All handlers *must* return a value, even if it's blank (''). |
|
375 | # All handlers *must* return a value, even if it's blank (''). | |
376 |
|
376 | |||
377 | # save the line away in case we crash, so the post-mortem handler can |
|
377 | # save the line away in case we crash, so the post-mortem handler can | |
378 | # record it |
|
378 | # record it | |
379 | self.shell._last_input_line = line |
|
379 | self.shell._last_input_line = line | |
380 |
|
380 | |||
381 | if not line: |
|
381 | if not line: | |
382 | # Return immediately on purely empty lines, so that if the user |
|
382 | # Return immediately on purely empty lines, so that if the user | |
383 | # previously typed some whitespace that started a continuation |
|
383 | # previously typed some whitespace that started a continuation | |
384 | # prompt, he can break out of that loop with just an empty line. |
|
384 | # prompt, he can break out of that loop with just an empty line. | |
385 | # This is how the default python prompt works. |
|
385 | # This is how the default python prompt works. | |
386 |
|
386 | |||
387 | # Only return if the accumulated input buffer was just whitespace! |
|
387 | # Only return if the accumulated input buffer was just whitespace! | |
388 | if ''.join(self.shell.buffer).isspace(): |
|
388 | if ''.join(self.shell.buffer).isspace(): | |
389 | self.shell.buffer[:] = [] |
|
389 | self.shell.buffer[:] = [] | |
390 | return '' |
|
390 | return '' | |
391 |
|
391 | |||
392 | # At this point, we invoke our transformers. |
|
392 | # At this point, we invoke our transformers. | |
393 | if not continue_prompt or (continue_prompt and self.multi_line_specials): |
|
393 | if not continue_prompt or (continue_prompt and self.multi_line_specials): | |
394 | line = self.transform_line(line, continue_prompt) |
|
394 | line = self.transform_line(line, continue_prompt) | |
395 |
|
395 | |||
396 | # Now we compute line_info for the checkers and handlers |
|
396 | # Now we compute line_info for the checkers and handlers | |
397 | line_info = LineInfo(line, continue_prompt) |
|
397 | line_info = LineInfo(line, continue_prompt) | |
398 |
|
398 | |||
399 | # the input history needs to track even empty lines |
|
399 | # the input history needs to track even empty lines | |
400 | stripped = line.strip() |
|
400 | stripped = line.strip() | |
401 |
|
401 | |||
402 | normal_handler = self.get_handler_by_name('normal') |
|
402 | normal_handler = self.get_handler_by_name('normal') | |
403 | if not stripped: |
|
403 | if not stripped: | |
404 | if not continue_prompt: |
|
404 | if not continue_prompt: | |
405 | self.shell.displayhook.prompt_count -= 1 |
|
405 | self.shell.displayhook.prompt_count -= 1 | |
406 |
|
406 | |||
407 | return normal_handler.handle(line_info) |
|
407 | return normal_handler.handle(line_info) | |
408 |
|
408 | |||
409 | # special handlers are only allowed for single line statements |
|
409 | # special handlers are only allowed for single line statements | |
410 | if continue_prompt and not self.multi_line_specials: |
|
410 | if continue_prompt and not self.multi_line_specials: | |
411 | return normal_handler.handle(line_info) |
|
411 | return normal_handler.handle(line_info) | |
412 |
|
412 | |||
413 | prefiltered = self.prefilter_line_info(line_info) |
|
413 | prefiltered = self.prefilter_line_info(line_info) | |
414 | # print "prefiltered line: %r" % prefiltered |
|
414 | # print "prefiltered line: %r" % prefiltered | |
415 | return prefiltered |
|
415 | return prefiltered | |
416 |
|
416 | |||
417 | def prefilter_lines(self, lines, continue_prompt=False): |
|
417 | def prefilter_lines(self, lines, continue_prompt=False): | |
418 | """Prefilter multiple input lines of text. |
|
418 | """Prefilter multiple input lines of text. | |
419 |
|
419 | |||
420 | This is the main entry point for prefiltering multiple lines of |
|
420 | This is the main entry point for prefiltering multiple lines of | |
421 | input. This simply calls :meth:`prefilter_line` for each line of |
|
421 | input. This simply calls :meth:`prefilter_line` for each line of | |
422 | input. |
|
422 | input. | |
423 |
|
423 | |||
424 | This covers cases where there are multiple lines in the user entry, |
|
424 | This covers cases where there are multiple lines in the user entry, | |
425 | which is the case when the user goes back to a multiline history |
|
425 | which is the case when the user goes back to a multiline history | |
426 | entry and presses enter. |
|
426 | entry and presses enter. | |
427 | """ |
|
427 | """ | |
428 | llines = lines.rstrip('\n').split('\n') |
|
428 | llines = lines.rstrip('\n').split('\n') | |
429 | # We can get multiple lines in one shot, where multiline input 'blends' |
|
429 | # We can get multiple lines in one shot, where multiline input 'blends' | |
430 | # into one line, in cases like recalling from the readline history |
|
430 | # into one line, in cases like recalling from the readline history | |
431 | # buffer. We need to make sure that in such cases, we correctly |
|
431 | # buffer. We need to make sure that in such cases, we correctly | |
432 | # communicate downstream which line is first and which are continuation |
|
432 | # communicate downstream which line is first and which are continuation | |
433 | # ones. |
|
433 | # ones. | |
434 | if len(llines) > 1: |
|
434 | if len(llines) > 1: | |
435 | out = '\n'.join([self.prefilter_line(line, lnum>0) |
|
435 | out = '\n'.join([self.prefilter_line(line, lnum>0) | |
436 | for lnum, line in enumerate(llines) ]) |
|
436 | for lnum, line in enumerate(llines) ]) | |
437 | else: |
|
437 | else: | |
438 | out = self.prefilter_line(llines[0], continue_prompt) |
|
438 | out = self.prefilter_line(llines[0], continue_prompt) | |
439 |
|
439 | |||
440 | return out |
|
440 | return out | |
441 |
|
441 | |||
442 | #----------------------------------------------------------------------------- |
|
442 | #----------------------------------------------------------------------------- | |
443 | # Prefilter transformers |
|
443 | # Prefilter transformers | |
444 | #----------------------------------------------------------------------------- |
|
444 | #----------------------------------------------------------------------------- | |
445 |
|
445 | |||
446 |
|
446 | |||
447 | class PrefilterTransformer(Configurable): |
|
447 | class PrefilterTransformer(Configurable): | |
448 | """Transform a line of user input.""" |
|
448 | """Transform a line of user input.""" | |
449 |
|
449 | |||
450 | priority = Int(100, config=True) |
|
450 | priority = Int(100, config=True) | |
451 | # Transformers don't currently use shell or prefilter_manager, but as we |
|
451 | # Transformers don't currently use shell or prefilter_manager, but as we | |
452 | # move away from checkers and handlers, they will need them. |
|
452 | # move away from checkers and handlers, they will need them. | |
453 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
453 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
454 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
454 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
455 | enabled = Bool(True, config=True) |
|
455 | enabled = Bool(True, config=True) | |
456 |
|
456 | |||
457 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
457 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
458 | super(PrefilterTransformer, self).__init__( |
|
458 | super(PrefilterTransformer, self).__init__( | |
459 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
459 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
460 | ) |
|
460 | ) | |
461 | self.prefilter_manager.register_transformer(self) |
|
461 | self.prefilter_manager.register_transformer(self) | |
462 |
|
462 | |||
463 | def transform(self, line, continue_prompt): |
|
463 | def transform(self, line, continue_prompt): | |
464 | """Transform a line, returning the new one.""" |
|
464 | """Transform a line, returning the new one.""" | |
465 | return None |
|
465 | return None | |
466 |
|
466 | |||
467 | def __repr__(self): |
|
467 | def __repr__(self): | |
468 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
468 | return "<%s(priority=%r, enabled=%r)>" % ( | |
469 | self.__class__.__name__, self.priority, self.enabled) |
|
469 | self.__class__.__name__, self.priority, self.enabled) | |
470 |
|
470 | |||
471 |
|
471 | |||
472 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
472 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
473 | r'\s*=\s*!(?P<cmd>.*)') |
|
473 | r'\s*=\s*!(?P<cmd>.*)') | |
474 |
|
474 | |||
475 |
|
475 | |||
476 | class AssignSystemTransformer(PrefilterTransformer): |
|
476 | class AssignSystemTransformer(PrefilterTransformer): | |
477 | """Handle the `files = !ls` syntax.""" |
|
477 | """Handle the `files = !ls` syntax.""" | |
478 |
|
478 | |||
479 | priority = Int(100, config=True) |
|
479 | priority = Int(100, config=True) | |
480 |
|
480 | |||
481 | def transform(self, line, continue_prompt): |
|
481 | def transform(self, line, continue_prompt): | |
482 | m = _assign_system_re.match(line) |
|
482 | m = _assign_system_re.match(line) | |
483 | if m is not None: |
|
483 | if m is not None: | |
484 | cmd = m.group('cmd') |
|
484 | cmd = m.group('cmd') | |
485 | lhs = m.group('lhs') |
|
485 | lhs = m.group('lhs') | |
486 | expr = make_quoted_expr("sc =%s" % cmd) |
|
486 | expr = make_quoted_expr("sc =%s" % cmd) | |
487 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
487 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
488 | return new_line |
|
488 | return new_line | |
489 | return line |
|
489 | return line | |
490 |
|
490 | |||
491 |
|
491 | |||
492 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
492 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
493 | r'\s*=\s*%(?P<cmd>.*)') |
|
493 | r'\s*=\s*%(?P<cmd>.*)') | |
494 |
|
494 | |||
495 | class AssignMagicTransformer(PrefilterTransformer): |
|
495 | class AssignMagicTransformer(PrefilterTransformer): | |
496 | """Handle the `a = %who` syntax.""" |
|
496 | """Handle the `a = %who` syntax.""" | |
497 |
|
497 | |||
498 | priority = Int(200, config=True) |
|
498 | priority = Int(200, config=True) | |
499 |
|
499 | |||
500 | def transform(self, line, continue_prompt): |
|
500 | def transform(self, line, continue_prompt): | |
501 | m = _assign_magic_re.match(line) |
|
501 | m = _assign_magic_re.match(line) | |
502 | if m is not None: |
|
502 | if m is not None: | |
503 | cmd = m.group('cmd') |
|
503 | cmd = m.group('cmd') | |
504 | lhs = m.group('lhs') |
|
504 | lhs = m.group('lhs') | |
505 | expr = make_quoted_expr(cmd) |
|
505 | expr = make_quoted_expr(cmd) | |
506 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
506 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
507 | return new_line |
|
507 | return new_line | |
508 | return line |
|
508 | return line | |
509 |
|
509 | |||
510 |
|
510 | |||
511 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') |
|
511 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') | |
512 |
|
512 | |||
513 | class PyPromptTransformer(PrefilterTransformer): |
|
513 | class PyPromptTransformer(PrefilterTransformer): | |
514 | """Handle inputs that start with '>>> ' syntax.""" |
|
514 | """Handle inputs that start with '>>> ' syntax.""" | |
515 |
|
515 | |||
516 | priority = Int(50, config=True) |
|
516 | priority = Int(50, config=True) | |
517 |
|
517 | |||
518 | def transform(self, line, continue_prompt): |
|
518 | def transform(self, line, continue_prompt): | |
519 |
|
519 | |||
520 | if not line or line.isspace() or line.strip() == '...': |
|
520 | if not line or line.isspace() or line.strip() == '...': | |
521 | # This allows us to recognize multiple input prompts separated by |
|
521 | # This allows us to recognize multiple input prompts separated by | |
522 | # blank lines and pasted in a single chunk, very common when |
|
522 | # blank lines and pasted in a single chunk, very common when | |
523 | # pasting doctests or long tutorial passages. |
|
523 | # pasting doctests or long tutorial passages. | |
524 | return '' |
|
524 | return '' | |
525 | m = _classic_prompt_re.match(line) |
|
525 | m = _classic_prompt_re.match(line) | |
526 | if m: |
|
526 | if m: | |
527 | return line[len(m.group(0)):] |
|
527 | return line[len(m.group(0)):] | |
528 | else: |
|
528 | else: | |
529 | return line |
|
529 | return line | |
530 |
|
530 | |||
531 |
|
531 | |||
532 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') |
|
532 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') | |
533 |
|
533 | |||
534 | class IPyPromptTransformer(PrefilterTransformer): |
|
534 | class IPyPromptTransformer(PrefilterTransformer): | |
535 | """Handle inputs that start classic IPython prompt syntax.""" |
|
535 | """Handle inputs that start classic IPython prompt syntax.""" | |
536 |
|
536 | |||
537 | priority = Int(50, config=True) |
|
537 | priority = Int(50, config=True) | |
538 |
|
538 | |||
539 | def transform(self, line, continue_prompt): |
|
539 | def transform(self, line, continue_prompt): | |
540 |
|
540 | |||
541 | if not line or line.isspace() or line.strip() == '...': |
|
541 | if not line or line.isspace() or line.strip() == '...': | |
542 | # This allows us to recognize multiple input prompts separated by |
|
542 | # This allows us to recognize multiple input prompts separated by | |
543 | # blank lines and pasted in a single chunk, very common when |
|
543 | # blank lines and pasted in a single chunk, very common when | |
544 | # pasting doctests or long tutorial passages. |
|
544 | # pasting doctests or long tutorial passages. | |
545 | return '' |
|
545 | return '' | |
546 | m = _ipy_prompt_re.match(line) |
|
546 | m = _ipy_prompt_re.match(line) | |
547 | if m: |
|
547 | if m: | |
548 | return line[len(m.group(0)):] |
|
548 | return line[len(m.group(0)):] | |
549 | else: |
|
549 | else: | |
550 | return line |
|
550 | return line | |
551 |
|
551 | |||
552 | #----------------------------------------------------------------------------- |
|
552 | #----------------------------------------------------------------------------- | |
553 | # Prefilter checkers |
|
553 | # Prefilter checkers | |
554 | #----------------------------------------------------------------------------- |
|
554 | #----------------------------------------------------------------------------- | |
555 |
|
555 | |||
556 |
|
556 | |||
557 | class PrefilterChecker(Configurable): |
|
557 | class PrefilterChecker(Configurable): | |
558 | """Inspect an input line and return a handler for that line.""" |
|
558 | """Inspect an input line and return a handler for that line.""" | |
559 |
|
559 | |||
560 | priority = Int(100, config=True) |
|
560 | priority = Int(100, config=True) | |
561 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
561 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
562 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
562 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
563 | enabled = Bool(True, config=True) |
|
563 | enabled = Bool(True, config=True) | |
564 |
|
564 | |||
565 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
565 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
566 | super(PrefilterChecker, self).__init__( |
|
566 | super(PrefilterChecker, self).__init__( | |
567 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
567 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
568 | ) |
|
568 | ) | |
569 | self.prefilter_manager.register_checker(self) |
|
569 | self.prefilter_manager.register_checker(self) | |
570 |
|
570 | |||
571 | def check(self, line_info): |
|
571 | def check(self, line_info): | |
572 | """Inspect line_info and return a handler instance or None.""" |
|
572 | """Inspect line_info and return a handler instance or None.""" | |
573 | return None |
|
573 | return None | |
574 |
|
574 | |||
575 | def __repr__(self): |
|
575 | def __repr__(self): | |
576 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
576 | return "<%s(priority=%r, enabled=%r)>" % ( | |
577 | self.__class__.__name__, self.priority, self.enabled) |
|
577 | self.__class__.__name__, self.priority, self.enabled) | |
578 |
|
578 | |||
579 |
|
579 | |||
580 | class EmacsChecker(PrefilterChecker): |
|
580 | class EmacsChecker(PrefilterChecker): | |
581 |
|
581 | |||
582 | priority = Int(100, config=True) |
|
582 | priority = Int(100, config=True) | |
583 | enabled = Bool(False, config=True) |
|
583 | enabled = Bool(False, config=True) | |
584 |
|
584 | |||
585 | def check(self, line_info): |
|
585 | def check(self, line_info): | |
586 | "Emacs ipython-mode tags certain input lines." |
|
586 | "Emacs ipython-mode tags certain input lines." | |
587 | if line_info.line.endswith('# PYTHON-MODE'): |
|
587 | if line_info.line.endswith('# PYTHON-MODE'): | |
588 | return self.prefilter_manager.get_handler_by_name('emacs') |
|
588 | return self.prefilter_manager.get_handler_by_name('emacs') | |
589 | else: |
|
589 | else: | |
590 | return None |
|
590 | return None | |
591 |
|
591 | |||
592 |
|
592 | |||
593 | class ShellEscapeChecker(PrefilterChecker): |
|
593 | class ShellEscapeChecker(PrefilterChecker): | |
594 |
|
594 | |||
595 | priority = Int(200, config=True) |
|
595 | priority = Int(200, config=True) | |
596 |
|
596 | |||
597 | def check(self, line_info): |
|
597 | def check(self, line_info): | |
598 | if line_info.line.lstrip().startswith(ESC_SHELL): |
|
598 | if line_info.line.lstrip().startswith(ESC_SHELL): | |
599 | return self.prefilter_manager.get_handler_by_name('shell') |
|
599 | return self.prefilter_manager.get_handler_by_name('shell') | |
600 |
|
600 | |||
601 |
|
601 | |||
602 | class MacroChecker(PrefilterChecker): |
|
602 | class MacroChecker(PrefilterChecker): | |
603 |
|
603 | |||
604 | priority = Int(250, config=True) |
|
604 | priority = Int(250, config=True) | |
605 |
|
605 | |||
606 | def check(self, line_info): |
|
606 | def check(self, line_info): | |
607 | obj = self.shell.user_ns.get(line_info.ifun) |
|
607 | obj = self.shell.user_ns.get(line_info.ifun) | |
608 | if isinstance(obj, Macro): |
|
608 | if isinstance(obj, Macro): | |
609 | return self.prefilter_manager.get_handler_by_name('macro') |
|
609 | return self.prefilter_manager.get_handler_by_name('macro') | |
610 | else: |
|
610 | else: | |
611 | return None |
|
611 | return None | |
612 |
|
612 | |||
613 |
|
613 | |||
614 | class IPyAutocallChecker(PrefilterChecker): |
|
614 | class IPyAutocallChecker(PrefilterChecker): | |
615 |
|
615 | |||
616 | priority = Int(300, config=True) |
|
616 | priority = Int(300, config=True) | |
617 |
|
617 | |||
618 | def check(self, line_info): |
|
618 | def check(self, line_info): | |
619 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
619 | "Instances of IPyAutocall in user_ns get autocalled immediately" | |
620 | obj = self.shell.user_ns.get(line_info.ifun, None) |
|
620 | obj = self.shell.user_ns.get(line_info.ifun, None) | |
621 | if isinstance(obj, IPyAutocall): |
|
621 | if isinstance(obj, IPyAutocall): | |
622 | obj.set_ip(self.shell) |
|
622 | obj.set_ip(self.shell) | |
623 | return self.prefilter_manager.get_handler_by_name('auto') |
|
623 | return self.prefilter_manager.get_handler_by_name('auto') | |
624 | else: |
|
624 | else: | |
625 | return None |
|
625 | return None | |
626 |
|
626 | |||
627 |
|
627 | |||
628 | class MultiLineMagicChecker(PrefilterChecker): |
|
628 | class MultiLineMagicChecker(PrefilterChecker): | |
629 |
|
629 | |||
630 | priority = Int(400, config=True) |
|
630 | priority = Int(400, config=True) | |
631 |
|
631 | |||
632 | def check(self, line_info): |
|
632 | def check(self, line_info): | |
633 | "Allow ! and !! in multi-line statements if multi_line_specials is on" |
|
633 | "Allow ! and !! in multi-line statements if multi_line_specials is on" | |
634 | # Note that this one of the only places we check the first character of |
|
634 | # Note that this one of the only places we check the first character of | |
635 | # ifun and *not* the pre_char. Also note that the below test matches |
|
635 | # ifun and *not* the pre_char. Also note that the below test matches | |
636 | # both ! and !!. |
|
636 | # both ! and !!. | |
637 | if line_info.continue_prompt \ |
|
637 | if line_info.continue_prompt \ | |
638 | and self.prefilter_manager.multi_line_specials: |
|
638 | and self.prefilter_manager.multi_line_specials: | |
639 | if line_info.ifun.startswith(ESC_MAGIC): |
|
639 | if line_info.ifun.startswith(ESC_MAGIC): | |
640 | return self.prefilter_manager.get_handler_by_name('magic') |
|
640 | return self.prefilter_manager.get_handler_by_name('magic') | |
641 | else: |
|
641 | else: | |
642 | return None |
|
642 | return None | |
643 |
|
643 | |||
644 |
|
644 | |||
645 | class EscCharsChecker(PrefilterChecker): |
|
645 | class EscCharsChecker(PrefilterChecker): | |
646 |
|
646 | |||
647 | priority = Int(500, config=True) |
|
647 | priority = Int(500, config=True) | |
648 |
|
648 | |||
649 | def check(self, line_info): |
|
649 | def check(self, line_info): | |
650 | """Check for escape character and return either a handler to handle it, |
|
650 | """Check for escape character and return either a handler to handle it, | |
651 | or None if there is no escape char.""" |
|
651 | or None if there is no escape char.""" | |
652 | if line_info.line[-1] == ESC_HELP \ |
|
652 | if line_info.line[-1] == ESC_HELP \ | |
653 | and line_info.pre_char != ESC_SHELL \ |
|
653 | and line_info.pre_char != ESC_SHELL \ | |
654 | and line_info.pre_char != ESC_SH_CAP: |
|
654 | and line_info.pre_char != ESC_SH_CAP: | |
655 | # the ? can be at the end, but *not* for either kind of shell escape, |
|
655 | # the ? can be at the end, but *not* for either kind of shell escape, | |
656 | # because a ? can be a vaild final char in a shell cmd |
|
656 | # because a ? can be a vaild final char in a shell cmd | |
657 | return self.prefilter_manager.get_handler_by_name('help') |
|
657 | return self.prefilter_manager.get_handler_by_name('help') | |
658 | else: |
|
658 | else: | |
659 | # This returns None like it should if no handler exists |
|
659 | # This returns None like it should if no handler exists | |
660 | return self.prefilter_manager.get_handler_by_esc(line_info.pre_char) |
|
660 | return self.prefilter_manager.get_handler_by_esc(line_info.pre_char) | |
661 |
|
661 | |||
662 |
|
662 | |||
663 | class AssignmentChecker(PrefilterChecker): |
|
663 | class AssignmentChecker(PrefilterChecker): | |
664 |
|
664 | |||
665 | priority = Int(600, config=True) |
|
665 | priority = Int(600, config=True) | |
666 |
|
666 | |||
667 | def check(self, line_info): |
|
667 | def check(self, line_info): | |
668 | """Check to see if user is assigning to a var for the first time, in |
|
668 | """Check to see if user is assigning to a var for the first time, in | |
669 | which case we want to avoid any sort of automagic / autocall games. |
|
669 | which case we want to avoid any sort of automagic / autocall games. | |
670 |
|
670 | |||
671 | This allows users to assign to either alias or magic names true python |
|
671 | This allows users to assign to either alias or magic names true python | |
672 | variables (the magic/alias systems always take second seat to true |
|
672 | variables (the magic/alias systems always take second seat to true | |
673 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
673 | python code). E.g. ls='hi', or ls,that=1,2""" | |
674 | if line_info.the_rest: |
|
674 | if line_info.the_rest: | |
675 | if line_info.the_rest[0] in '=,': |
|
675 | if line_info.the_rest[0] in '=,': | |
676 | return self.prefilter_manager.get_handler_by_name('normal') |
|
676 | return self.prefilter_manager.get_handler_by_name('normal') | |
677 | else: |
|
677 | else: | |
678 | return None |
|
678 | return None | |
679 |
|
679 | |||
680 |
|
680 | |||
681 | class AutoMagicChecker(PrefilterChecker): |
|
681 | class AutoMagicChecker(PrefilterChecker): | |
682 |
|
682 | |||
683 | priority = Int(700, config=True) |
|
683 | priority = Int(700, config=True) | |
684 |
|
684 | |||
685 | def check(self, line_info): |
|
685 | def check(self, line_info): | |
686 | """If the ifun is magic, and automagic is on, run it. Note: normal, |
|
686 | """If the ifun is magic, and automagic is on, run it. Note: normal, | |
687 | non-auto magic would already have been triggered via '%' in |
|
687 | non-auto magic would already have been triggered via '%' in | |
688 | check_esc_chars. This just checks for automagic. Also, before |
|
688 | check_esc_chars. This just checks for automagic. Also, before | |
689 | triggering the magic handler, make sure that there is nothing in the |
|
689 | triggering the magic handler, make sure that there is nothing in the | |
690 | user namespace which could shadow it.""" |
|
690 | user namespace which could shadow it.""" | |
691 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): |
|
691 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): | |
692 | return None |
|
692 | return None | |
693 |
|
693 | |||
694 | # We have a likely magic method. Make sure we should actually call it. |
|
694 | # We have a likely magic method. Make sure we should actually call it. | |
695 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: |
|
695 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: | |
696 | return None |
|
696 | return None | |
697 |
|
697 | |||
698 | head = line_info.ifun.split('.',1)[0] |
|
698 | head = line_info.ifun.split('.',1)[0] | |
699 | if is_shadowed(head, self.shell): |
|
699 | if is_shadowed(head, self.shell): | |
700 | return None |
|
700 | return None | |
701 |
|
701 | |||
702 | return self.prefilter_manager.get_handler_by_name('magic') |
|
702 | return self.prefilter_manager.get_handler_by_name('magic') | |
703 |
|
703 | |||
704 |
|
704 | |||
705 | class AliasChecker(PrefilterChecker): |
|
705 | class AliasChecker(PrefilterChecker): | |
706 |
|
706 | |||
707 | priority = Int(800, config=True) |
|
707 | priority = Int(800, config=True) | |
708 |
|
708 | |||
709 | def check(self, line_info): |
|
709 | def check(self, line_info): | |
710 | "Check if the initital identifier on the line is an alias." |
|
710 | "Check if the initital identifier on the line is an alias." | |
711 | # Note: aliases can not contain '.' |
|
711 | # Note: aliases can not contain '.' | |
712 | head = line_info.ifun.split('.',1)[0] |
|
712 | head = line_info.ifun.split('.',1)[0] | |
713 | if line_info.ifun not in self.shell.alias_manager \ |
|
713 | if line_info.ifun not in self.shell.alias_manager \ | |
714 | or head not in self.shell.alias_manager \ |
|
714 | or head not in self.shell.alias_manager \ | |
715 | or is_shadowed(head, self.shell): |
|
715 | or is_shadowed(head, self.shell): | |
716 | return None |
|
716 | return None | |
717 |
|
717 | |||
718 | return self.prefilter_manager.get_handler_by_name('alias') |
|
718 | return self.prefilter_manager.get_handler_by_name('alias') | |
719 |
|
719 | |||
720 |
|
720 | |||
721 | class PythonOpsChecker(PrefilterChecker): |
|
721 | class PythonOpsChecker(PrefilterChecker): | |
722 |
|
722 | |||
723 | priority = Int(900, config=True) |
|
723 | priority = Int(900, config=True) | |
724 |
|
724 | |||
725 | def check(self, line_info): |
|
725 | def check(self, line_info): | |
726 | """If the 'rest' of the line begins with a function call or pretty much |
|
726 | """If the 'rest' of the line begins with a function call or pretty much | |
727 | any python operator, we should simply execute the line (regardless of |
|
727 | any python operator, we should simply execute the line (regardless of | |
728 | whether or not there's a possible autocall expansion). This avoids |
|
728 | whether or not there's a possible autocall expansion). This avoids | |
729 | spurious (and very confusing) geattr() accesses.""" |
|
729 | spurious (and very confusing) geattr() accesses.""" | |
730 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': |
|
730 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': | |
731 | return self.prefilter_manager.get_handler_by_name('normal') |
|
731 | return self.prefilter_manager.get_handler_by_name('normal') | |
732 | else: |
|
732 | else: | |
733 | return None |
|
733 | return None | |
734 |
|
734 | |||
735 |
|
735 | |||
736 | class AutocallChecker(PrefilterChecker): |
|
736 | class AutocallChecker(PrefilterChecker): | |
737 |
|
737 | |||
738 | priority = Int(1000, config=True) |
|
738 | priority = Int(1000, config=True) | |
739 |
|
739 | |||
740 | def check(self, line_info): |
|
740 | def check(self, line_info): | |
741 | "Check if the initial word/function is callable and autocall is on." |
|
741 | "Check if the initial word/function is callable and autocall is on." | |
742 | if not self.shell.autocall: |
|
742 | if not self.shell.autocall: | |
743 | return None |
|
743 | return None | |
744 |
|
744 | |||
745 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr |
|
745 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr | |
746 | if not oinfo['found']: |
|
746 | if not oinfo['found']: | |
747 | return None |
|
747 | return None | |
748 |
|
748 | |||
749 | if callable(oinfo['obj']) \ |
|
749 | if callable(oinfo['obj']) \ | |
750 | and (not re_exclude_auto.match(line_info.the_rest)) \ |
|
750 | and (not re_exclude_auto.match(line_info.the_rest)) \ | |
751 | and re_fun_name.match(line_info.ifun): |
|
751 | and re_fun_name.match(line_info.ifun): | |
752 | return self.prefilter_manager.get_handler_by_name('auto') |
|
752 | return self.prefilter_manager.get_handler_by_name('auto') | |
753 | else: |
|
753 | else: | |
754 | return None |
|
754 | return None | |
755 |
|
755 | |||
756 |
|
756 | |||
757 | #----------------------------------------------------------------------------- |
|
757 | #----------------------------------------------------------------------------- | |
758 | # Prefilter handlers |
|
758 | # Prefilter handlers | |
759 | #----------------------------------------------------------------------------- |
|
759 | #----------------------------------------------------------------------------- | |
760 |
|
760 | |||
761 |
|
761 | |||
762 | class PrefilterHandler(Configurable): |
|
762 | class PrefilterHandler(Configurable): | |
763 |
|
763 | |||
764 | handler_name = Str('normal') |
|
764 | handler_name = Str('normal') | |
765 | esc_strings = List([]) |
|
765 | esc_strings = List([]) | |
766 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
766 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
767 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
767 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
768 |
|
768 | |||
769 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
769 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
770 | super(PrefilterHandler, self).__init__( |
|
770 | super(PrefilterHandler, self).__init__( | |
771 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
771 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
772 | ) |
|
772 | ) | |
773 | self.prefilter_manager.register_handler( |
|
773 | self.prefilter_manager.register_handler( | |
774 | self.handler_name, |
|
774 | self.handler_name, | |
775 | self, |
|
775 | self, | |
776 | self.esc_strings |
|
776 | self.esc_strings | |
777 | ) |
|
777 | ) | |
778 |
|
778 | |||
779 | def handle(self, line_info): |
|
779 | def handle(self, line_info): | |
780 | # print "normal: ", line_info |
|
780 | # print "normal: ", line_info | |
781 | """Handle normal input lines. Use as a template for handlers.""" |
|
781 | """Handle normal input lines. Use as a template for handlers.""" | |
782 |
|
782 | |||
783 | # With autoindent on, we need some way to exit the input loop, and I |
|
783 | # With autoindent on, we need some way to exit the input loop, and I | |
784 | # don't want to force the user to have to backspace all the way to |
|
784 | # don't want to force the user to have to backspace all the way to | |
785 | # clear the line. The rule will be in this case, that either two |
|
785 | # clear the line. The rule will be in this case, that either two | |
786 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
786 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
787 | # of a size different to the indent level, will exit the input loop. |
|
787 | # of a size different to the indent level, will exit the input loop. | |
788 | line = line_info.line |
|
788 | line = line_info.line | |
789 | continue_prompt = line_info.continue_prompt |
|
789 | continue_prompt = line_info.continue_prompt | |
790 |
|
790 | |||
791 | if (continue_prompt and |
|
791 | if (continue_prompt and | |
792 | self.shell.autoindent and |
|
792 | self.shell.autoindent and | |
793 | line.isspace() and |
|
793 | line.isspace() and | |
794 |
|
794 | |||
795 | (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 |
|
795 | (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 | |
796 | or |
|
796 | or | |
797 | not self.shell.buffer |
|
797 | not self.shell.buffer | |
798 | or |
|
798 | or | |
799 | (self.shell.buffer[-1]).isspace() |
|
799 | (self.shell.buffer[-1]).isspace() | |
800 | ) |
|
800 | ) | |
801 | ): |
|
801 | ): | |
802 | line = '' |
|
802 | line = '' | |
803 |
|
803 | |||
804 | return line |
|
804 | return line | |
805 |
|
805 | |||
806 | def __str__(self): |
|
806 | def __str__(self): | |
807 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) |
|
807 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) | |
808 |
|
808 | |||
809 |
|
809 | |||
810 | class AliasHandler(PrefilterHandler): |
|
810 | class AliasHandler(PrefilterHandler): | |
811 |
|
811 | |||
812 | handler_name = Str('alias') |
|
812 | handler_name = Str('alias') | |
813 |
|
813 | |||
814 | def handle(self, line_info): |
|
814 | def handle(self, line_info): | |
815 | """Handle alias input lines. """ |
|
815 | """Handle alias input lines. """ | |
816 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) |
|
816 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) | |
817 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
817 | # pre is needed, because it carries the leading whitespace. Otherwise | |
818 | # aliases won't work in indented sections. |
|
818 | # aliases won't work in indented sections. | |
819 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
819 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, | |
820 | make_quoted_expr(transformed)) |
|
820 | make_quoted_expr(transformed)) | |
821 |
|
821 | |||
822 | return line_out |
|
822 | return line_out | |
823 |
|
823 | |||
824 |
|
824 | |||
825 | class ShellEscapeHandler(PrefilterHandler): |
|
825 | class ShellEscapeHandler(PrefilterHandler): | |
826 |
|
826 | |||
827 | handler_name = Str('shell') |
|
827 | handler_name = Str('shell') | |
828 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) |
|
828 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) | |
829 |
|
829 | |||
830 | def handle(self, line_info): |
|
830 | def handle(self, line_info): | |
831 | """Execute the line in a shell, empty return value""" |
|
831 | """Execute the line in a shell, empty return value""" | |
832 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') |
|
832 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') | |
833 |
|
833 | |||
834 | line = line_info.line |
|
834 | line = line_info.line | |
835 | if line.lstrip().startswith(ESC_SH_CAP): |
|
835 | if line.lstrip().startswith(ESC_SH_CAP): | |
836 | # rewrite LineInfo's line, ifun and the_rest to properly hold the |
|
836 | # rewrite LineInfo's line, ifun and the_rest to properly hold the | |
837 | # call to %sx and the actual command to be executed, so |
|
837 | # call to %sx and the actual command to be executed, so | |
838 | # handle_magic can work correctly. Note that this works even if |
|
838 | # handle_magic can work correctly. Note that this works even if | |
839 | # the line is indented, so it handles multi_line_specials |
|
839 | # the line is indented, so it handles multi_line_specials | |
840 | # properly. |
|
840 | # properly. | |
841 | new_rest = line.lstrip()[2:] |
|
841 | new_rest = line.lstrip()[2:] | |
842 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) |
|
842 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) | |
843 | line_info.ifun = 'sx' |
|
843 | line_info.ifun = 'sx' | |
844 | line_info.the_rest = new_rest |
|
844 | line_info.the_rest = new_rest | |
845 | return magic_handler.handle(line_info) |
|
845 | return magic_handler.handle(line_info) | |
846 | else: |
|
846 | else: | |
847 | cmd = line.lstrip().lstrip(ESC_SHELL) |
|
847 | cmd = line.lstrip().lstrip(ESC_SHELL) | |
848 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
848 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, | |
849 | make_quoted_expr(cmd)) |
|
849 | make_quoted_expr(cmd)) | |
850 | return line_out |
|
850 | return line_out | |
851 |
|
851 | |||
852 |
|
852 | |||
853 | class MacroHandler(PrefilterHandler): |
|
853 | class MacroHandler(PrefilterHandler): | |
854 | handler_name = Str("macro") |
|
854 | handler_name = Str("macro") | |
855 |
|
855 | |||
856 | def handle(self, line_info): |
|
856 | def handle(self, line_info): | |
857 | obj = self.shell.user_ns.get(line_info.ifun) |
|
857 | obj = self.shell.user_ns.get(line_info.ifun) | |
858 | pre_space = line_info.pre_whitespace |
|
858 | pre_space = line_info.pre_whitespace | |
859 | line_sep = "\n" + pre_space |
|
859 | line_sep = "\n" + pre_space | |
860 | return pre_space + line_sep.join(obj.value.splitlines()) |
|
860 | return pre_space + line_sep.join(obj.value.splitlines()) | |
861 |
|
861 | |||
862 |
|
862 | |||
863 | class MagicHandler(PrefilterHandler): |
|
863 | class MagicHandler(PrefilterHandler): | |
864 |
|
864 | |||
865 | handler_name = Str('magic') |
|
865 | handler_name = Str('magic') | |
866 | esc_strings = List([ESC_MAGIC]) |
|
866 | esc_strings = List([ESC_MAGIC]) | |
867 |
|
867 | |||
868 | def handle(self, line_info): |
|
868 | def handle(self, line_info): | |
869 | """Execute magic functions.""" |
|
869 | """Execute magic functions.""" | |
870 | ifun = line_info.ifun |
|
870 | ifun = line_info.ifun | |
871 | the_rest = line_info.the_rest |
|
871 | the_rest = line_info.the_rest | |
872 | cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace, |
|
872 | cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace, | |
873 | make_quoted_expr(ifun + " " + the_rest)) |
|
873 | make_quoted_expr(ifun + " " + the_rest)) | |
874 | return cmd |
|
874 | return cmd | |
875 |
|
875 | |||
876 |
|
876 | |||
877 | class AutoHandler(PrefilterHandler): |
|
877 | class AutoHandler(PrefilterHandler): | |
878 |
|
878 | |||
879 | handler_name = Str('auto') |
|
879 | handler_name = Str('auto') | |
880 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) |
|
880 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) | |
881 |
|
881 | |||
882 | def handle(self, line_info): |
|
882 | def handle(self, line_info): | |
883 | """Handle lines which can be auto-executed, quoting if requested.""" |
|
883 | """Handle lines which can be auto-executed, quoting if requested.""" | |
884 | line = line_info.line |
|
884 | line = line_info.line | |
885 | ifun = line_info.ifun |
|
885 | ifun = line_info.ifun | |
886 | the_rest = line_info.the_rest |
|
886 | the_rest = line_info.the_rest | |
887 | pre = line_info.pre |
|
887 | pre = line_info.pre | |
888 | continue_prompt = line_info.continue_prompt |
|
888 | continue_prompt = line_info.continue_prompt | |
889 | obj = line_info.ofind(self)['obj'] |
|
889 | obj = line_info.ofind(self)['obj'] | |
890 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg |
|
890 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg | |
891 |
|
891 | |||
892 | # This should only be active for single-line input! |
|
892 | # This should only be active for single-line input! | |
893 | if continue_prompt: |
|
893 | if continue_prompt: | |
894 | return line |
|
894 | return line | |
895 |
|
895 | |||
896 | force_auto = isinstance(obj, IPyAutocall) |
|
896 | force_auto = isinstance(obj, IPyAutocall) | |
897 | auto_rewrite = True |
|
897 | auto_rewrite = getattr(obj, 'rewrite', True) | |
898 |
|
898 | |||
899 | if pre == ESC_QUOTE: |
|
899 | if pre == ESC_QUOTE: | |
900 | # Auto-quote splitting on whitespace |
|
900 | # Auto-quote splitting on whitespace | |
901 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) |
|
901 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) | |
902 | elif pre == ESC_QUOTE2: |
|
902 | elif pre == ESC_QUOTE2: | |
903 | # Auto-quote whole string |
|
903 | # Auto-quote whole string | |
904 | newcmd = '%s("%s")' % (ifun,the_rest) |
|
904 | newcmd = '%s("%s")' % (ifun,the_rest) | |
905 | elif pre == ESC_PAREN: |
|
905 | elif pre == ESC_PAREN: | |
906 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) |
|
906 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) | |
907 | else: |
|
907 | else: | |
908 | # Auto-paren. |
|
908 | # Auto-paren. | |
909 | # We only apply it to argument-less calls if the autocall |
|
909 | # We only apply it to argument-less calls if the autocall | |
910 | # parameter is set to 2. We only need to check that autocall is < |
|
910 | # parameter is set to 2. We only need to check that autocall is < | |
911 | # 2, since this function isn't called unless it's at least 1. |
|
911 | # 2, since this function isn't called unless it's at least 1. | |
912 | if not the_rest and (self.shell.autocall < 2) and not force_auto: |
|
912 | if not the_rest and (self.shell.autocall < 2) and not force_auto: | |
913 | newcmd = '%s %s' % (ifun,the_rest) |
|
913 | newcmd = '%s %s' % (ifun,the_rest) | |
914 | auto_rewrite = False |
|
914 | auto_rewrite = False | |
915 | else: |
|
915 | else: | |
916 | if not force_auto and the_rest.startswith('['): |
|
916 | if not force_auto and the_rest.startswith('['): | |
917 | if hasattr(obj,'__getitem__'): |
|
917 | if hasattr(obj,'__getitem__'): | |
918 | # Don't autocall in this case: item access for an object |
|
918 | # Don't autocall in this case: item access for an object | |
919 | # which is BOTH callable and implements __getitem__. |
|
919 | # which is BOTH callable and implements __getitem__. | |
920 | newcmd = '%s %s' % (ifun,the_rest) |
|
920 | newcmd = '%s %s' % (ifun,the_rest) | |
921 | auto_rewrite = False |
|
921 | auto_rewrite = False | |
922 | else: |
|
922 | else: | |
923 | # if the object doesn't support [] access, go ahead and |
|
923 | # if the object doesn't support [] access, go ahead and | |
924 | # autocall |
|
924 | # autocall | |
925 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) |
|
925 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) | |
926 | elif the_rest.endswith(';'): |
|
926 | elif the_rest.endswith(';'): | |
927 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) |
|
927 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) | |
928 | else: |
|
928 | else: | |
929 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) |
|
929 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) | |
930 |
|
930 | |||
931 | if auto_rewrite: |
|
931 | if auto_rewrite: | |
932 | self.shell.auto_rewrite_input(newcmd) |
|
932 | self.shell.auto_rewrite_input(newcmd) | |
933 |
|
933 | |||
934 | return newcmd |
|
934 | return newcmd | |
935 |
|
935 | |||
936 |
|
936 | |||
937 | class HelpHandler(PrefilterHandler): |
|
937 | class HelpHandler(PrefilterHandler): | |
938 |
|
938 | |||
939 | handler_name = Str('help') |
|
939 | handler_name = Str('help') | |
940 | esc_strings = List([ESC_HELP]) |
|
940 | esc_strings = List([ESC_HELP]) | |
941 |
|
941 | |||
942 | def handle(self, line_info): |
|
942 | def handle(self, line_info): | |
943 | """Try to get some help for the object. |
|
943 | """Try to get some help for the object. | |
944 |
|
944 | |||
945 | obj? or ?obj -> basic information. |
|
945 | obj? or ?obj -> basic information. | |
946 | obj?? or ??obj -> more details. |
|
946 | obj?? or ??obj -> more details. | |
947 | """ |
|
947 | """ | |
948 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') |
|
948 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') | |
949 | line = line_info.line |
|
949 | line = line_info.line | |
950 | # We need to make sure that we don't process lines which would be |
|
950 | # We need to make sure that we don't process lines which would be | |
951 | # otherwise valid python, such as "x=1 # what?" |
|
951 | # otherwise valid python, such as "x=1 # what?" | |
952 | try: |
|
952 | try: | |
953 | codeop.compile_command(line) |
|
953 | codeop.compile_command(line) | |
954 | except SyntaxError: |
|
954 | except SyntaxError: | |
955 | # We should only handle as help stuff which is NOT valid syntax |
|
955 | # We should only handle as help stuff which is NOT valid syntax | |
956 | if line[0]==ESC_HELP: |
|
956 | if line[0]==ESC_HELP: | |
957 | line = line[1:] |
|
957 | line = line[1:] | |
958 | elif line[-1]==ESC_HELP: |
|
958 | elif line[-1]==ESC_HELP: | |
959 | line = line[:-1] |
|
959 | line = line[:-1] | |
960 | if line: |
|
960 | if line: | |
961 | #print 'line:<%r>' % line # dbg |
|
961 | #print 'line:<%r>' % line # dbg | |
962 | self.shell.magic_pinfo(line) |
|
962 | self.shell.magic_pinfo(line) | |
963 | else: |
|
963 | else: | |
964 | self.shell.show_usage() |
|
964 | self.shell.show_usage() | |
965 | return '' # Empty string is needed here! |
|
965 | return '' # Empty string is needed here! | |
966 | except: |
|
966 | except: | |
967 | raise |
|
967 | raise | |
968 | # Pass any other exceptions through to the normal handler |
|
968 | # Pass any other exceptions through to the normal handler | |
969 | return normal_handler.handle(line_info) |
|
969 | return normal_handler.handle(line_info) | |
970 | else: |
|
970 | else: | |
971 | # If the code compiles ok, we should handle it normally |
|
971 | # If the code compiles ok, we should handle it normally | |
972 | return normal_handler.handle(line_info) |
|
972 | return normal_handler.handle(line_info) | |
973 |
|
973 | |||
974 |
|
974 | |||
975 | class EmacsHandler(PrefilterHandler): |
|
975 | class EmacsHandler(PrefilterHandler): | |
976 |
|
976 | |||
977 | handler_name = Str('emacs') |
|
977 | handler_name = Str('emacs') | |
978 | esc_strings = List([]) |
|
978 | esc_strings = List([]) | |
979 |
|
979 | |||
980 | def handle(self, line_info): |
|
980 | def handle(self, line_info): | |
981 | """Handle input lines marked by python-mode.""" |
|
981 | """Handle input lines marked by python-mode.""" | |
982 |
|
982 | |||
983 | # Currently, nothing is done. Later more functionality can be added |
|
983 | # Currently, nothing is done. Later more functionality can be added | |
984 | # here if needed. |
|
984 | # here if needed. | |
985 |
|
985 | |||
986 | # The input cache shouldn't be updated |
|
986 | # The input cache shouldn't be updated | |
987 | return line_info.line |
|
987 | return line_info.line | |
988 |
|
988 | |||
989 |
|
989 | |||
990 | #----------------------------------------------------------------------------- |
|
990 | #----------------------------------------------------------------------------- | |
991 | # Defaults |
|
991 | # Defaults | |
992 | #----------------------------------------------------------------------------- |
|
992 | #----------------------------------------------------------------------------- | |
993 |
|
993 | |||
994 |
|
994 | |||
995 | _default_transformers = [ |
|
995 | _default_transformers = [ | |
996 | AssignSystemTransformer, |
|
996 | AssignSystemTransformer, | |
997 | AssignMagicTransformer, |
|
997 | AssignMagicTransformer, | |
998 | PyPromptTransformer, |
|
998 | PyPromptTransformer, | |
999 | IPyPromptTransformer, |
|
999 | IPyPromptTransformer, | |
1000 | ] |
|
1000 | ] | |
1001 |
|
1001 | |||
1002 | _default_checkers = [ |
|
1002 | _default_checkers = [ | |
1003 | EmacsChecker, |
|
1003 | EmacsChecker, | |
1004 | ShellEscapeChecker, |
|
1004 | ShellEscapeChecker, | |
1005 | MacroChecker, |
|
1005 | MacroChecker, | |
1006 | IPyAutocallChecker, |
|
1006 | IPyAutocallChecker, | |
1007 | MultiLineMagicChecker, |
|
1007 | MultiLineMagicChecker, | |
1008 | EscCharsChecker, |
|
1008 | EscCharsChecker, | |
1009 | AssignmentChecker, |
|
1009 | AssignmentChecker, | |
1010 | AutoMagicChecker, |
|
1010 | AutoMagicChecker, | |
1011 | AliasChecker, |
|
1011 | AliasChecker, | |
1012 | PythonOpsChecker, |
|
1012 | PythonOpsChecker, | |
1013 | AutocallChecker |
|
1013 | AutocallChecker | |
1014 | ] |
|
1014 | ] | |
1015 |
|
1015 | |||
1016 | _default_handlers = [ |
|
1016 | _default_handlers = [ | |
1017 | PrefilterHandler, |
|
1017 | PrefilterHandler, | |
1018 | AliasHandler, |
|
1018 | AliasHandler, | |
1019 | ShellEscapeHandler, |
|
1019 | ShellEscapeHandler, | |
1020 | MacroHandler, |
|
1020 | MacroHandler, | |
1021 | MagicHandler, |
|
1021 | MagicHandler, | |
1022 | AutoHandler, |
|
1022 | AutoHandler, | |
1023 | HelpHandler, |
|
1023 | HelpHandler, | |
1024 | EmacsHandler |
|
1024 | EmacsHandler | |
1025 | ] |
|
1025 | ] |
@@ -1,170 +1,170 b'' | |||||
1 | """Test suite for the irunner module. |
|
1 | """Test suite for the irunner module. | |
2 |
|
2 | |||
3 | Not the most elegant or fine-grained, but it does cover at least the bulk |
|
3 | Not the most elegant or fine-grained, but it does cover at least the bulk | |
4 | functionality.""" |
|
4 | functionality.""" | |
5 |
|
5 | |||
6 | # Global to make tests extra verbose and help debugging |
|
6 | # Global to make tests extra verbose and help debugging | |
7 | VERBOSE = True |
|
7 | VERBOSE = True | |
8 |
|
8 | |||
9 | # stdlib imports |
|
9 | # stdlib imports | |
10 | import cStringIO as StringIO |
|
10 | import cStringIO as StringIO | |
11 | import sys |
|
11 | import sys | |
12 | import unittest |
|
12 | import unittest | |
13 |
|
13 | |||
14 | # IPython imports |
|
14 | # IPython imports | |
15 | from IPython.lib import irunner |
|
15 | from IPython.lib import irunner | |
16 |
|
16 | |||
17 | # Testing code begins |
|
17 | # Testing code begins | |
18 | class RunnerTestCase(unittest.TestCase): |
|
18 | class RunnerTestCase(unittest.TestCase): | |
19 |
|
19 | |||
20 | def setUp(self): |
|
20 | def setUp(self): | |
21 | self.out = StringIO.StringIO() |
|
21 | self.out = StringIO.StringIO() | |
22 | #self.out = sys.stdout |
|
22 | #self.out = sys.stdout | |
23 |
|
23 | |||
24 | def _test_runner(self,runner,source,output): |
|
24 | def _test_runner(self,runner,source,output): | |
25 | """Test that a given runner's input/output match.""" |
|
25 | """Test that a given runner's input/output match.""" | |
26 |
|
26 | |||
27 | runner.run_source(source) |
|
27 | runner.run_source(source) | |
28 | out = self.out.getvalue() |
|
28 | out = self.out.getvalue() | |
29 | #out = '' |
|
29 | #out = '' | |
30 | # this output contains nasty \r\n lineends, and the initial ipython |
|
30 | # this output contains nasty \r\n lineends, and the initial ipython | |
31 | # banner. clean it up for comparison, removing lines of whitespace |
|
31 | # banner. clean it up for comparison, removing lines of whitespace | |
32 | output_l = [l for l in output.splitlines() if l and not l.isspace()] |
|
32 | output_l = [l for l in output.splitlines() if l and not l.isspace()] | |
33 | out_l = [l for l in out.splitlines() if l and not l.isspace()] |
|
33 | out_l = [l for l in out.splitlines() if l and not l.isspace()] | |
34 | mismatch = 0 |
|
34 | mismatch = 0 | |
35 | if len(output_l) != len(out_l): |
|
35 | if len(output_l) != len(out_l): | |
36 | message = ("Mismatch in number of lines\n\n" |
|
36 | message = ("Mismatch in number of lines\n\n" | |
37 | "Expected:\n" |
|
37 | "Expected:\n" | |
38 | "~~~~~~~~~\n" |
|
38 | "~~~~~~~~~\n" | |
39 | "%s\n\n" |
|
39 | "%s\n\n" | |
40 | "Got:\n" |
|
40 | "Got:\n" | |
41 | "~~~~~~~~~\n" |
|
41 | "~~~~~~~~~\n" | |
42 | "%s" |
|
42 | "%s" | |
43 | ) % ("\n".join(output_l), "\n".join(out_l)) |
|
43 | ) % ("\n".join(output_l), "\n".join(out_l)) | |
44 | self.fail(message) |
|
44 | self.fail(message) | |
45 | for n in range(len(output_l)): |
|
45 | for n in range(len(output_l)): | |
46 | # Do a line-by-line comparison |
|
46 | # Do a line-by-line comparison | |
47 | ol1 = output_l[n].strip() |
|
47 | ol1 = output_l[n].strip() | |
48 | ol2 = out_l[n].strip() |
|
48 | ol2 = out_l[n].strip() | |
49 | if ol1 != ol2: |
|
49 | if ol1 != ol2: | |
50 | mismatch += 1 |
|
50 | mismatch += 1 | |
51 | if VERBOSE: |
|
51 | if VERBOSE: | |
52 | print '<<< line %s does not match:' % n |
|
52 | print '<<< line %s does not match:' % n | |
53 | print repr(ol1) |
|
53 | print repr(ol1) | |
54 | print repr(ol2) |
|
54 | print repr(ol2) | |
55 | print '>>>' |
|
55 | print '>>>' | |
56 | self.assert_(mismatch==0,'Number of mismatched lines: %s' % |
|
56 | self.assert_(mismatch==0,'Number of mismatched lines: %s' % | |
57 | mismatch) |
|
57 | mismatch) | |
58 |
|
58 | |||
59 | def testIPython(self): |
|
59 | def testIPython(self): | |
60 | """Test the IPython runner.""" |
|
60 | """Test the IPython runner.""" | |
61 | source = """ |
|
61 | source = """ | |
62 | print 'hello, this is python' |
|
62 | print 'hello, this is python' | |
63 | # some more code |
|
63 | # some more code | |
64 | x=1;y=2 |
|
64 | x=1;y=2 | |
65 | x+y**2 |
|
65 | x+y**2 | |
66 |
|
66 | |||
67 | # An example of autocall functionality |
|
67 | # An example of autocall functionality | |
68 | from math import * |
|
68 | from math import * | |
69 | autocall 1 |
|
69 | autocall 1 | |
70 | cos pi |
|
70 | cos pi | |
71 | autocall 0 |
|
71 | autocall 0 | |
72 | cos pi |
|
72 | cos pi | |
73 | cos(pi) |
|
73 | cos(pi) | |
74 |
|
74 | |||
75 | for i in range(5): |
|
75 | for i in range(5): | |
76 | print i, |
|
76 | print i, | |
77 |
|
77 | |||
78 | print "that's all folks!" |
|
78 | print "that's all folks!" | |
79 |
|
79 | |||
80 |
|
|
80 | exit | |
81 | """ |
|
81 | """ | |
82 | output = """\ |
|
82 | output = """\ | |
83 | In [1]: print 'hello, this is python' |
|
83 | In [1]: print 'hello, this is python' | |
84 | hello, this is python |
|
84 | hello, this is python | |
85 |
|
85 | |||
86 |
|
86 | |||
87 | # some more code |
|
87 | # some more code | |
88 | In [2]: x=1;y=2 |
|
88 | In [2]: x=1;y=2 | |
89 |
|
89 | |||
90 | In [3]: x+y**2 |
|
90 | In [3]: x+y**2 | |
91 | Out[3]: 5 |
|
91 | Out[3]: 5 | |
92 |
|
92 | |||
93 |
|
93 | |||
94 | # An example of autocall functionality |
|
94 | # An example of autocall functionality | |
95 | In [4]: from math import * |
|
95 | In [4]: from math import * | |
96 |
|
96 | |||
97 | In [5]: autocall 1 |
|
97 | In [5]: autocall 1 | |
98 | Automatic calling is: Smart |
|
98 | Automatic calling is: Smart | |
99 |
|
99 | |||
100 | In [6]: cos pi |
|
100 | In [6]: cos pi | |
101 | ------> cos(pi) |
|
101 | ------> cos(pi) | |
102 | Out[6]: -1.0 |
|
102 | Out[6]: -1.0 | |
103 |
|
103 | |||
104 | In [7]: autocall 0 |
|
104 | In [7]: autocall 0 | |
105 | Automatic calling is: OFF |
|
105 | Automatic calling is: OFF | |
106 |
|
106 | |||
107 | In [8]: cos pi |
|
107 | In [8]: cos pi | |
108 | File "<ipython-input-8-586f1104ea44>", line 1 |
|
108 | File "<ipython-input-8-586f1104ea44>", line 1 | |
109 | cos pi |
|
109 | cos pi | |
110 | ^ |
|
110 | ^ | |
111 | SyntaxError: unexpected EOF while parsing |
|
111 | SyntaxError: unexpected EOF while parsing | |
112 |
|
112 | |||
113 |
|
113 | |||
114 | In [9]: cos(pi) |
|
114 | In [9]: cos(pi) | |
115 | Out[9]: -1.0 |
|
115 | Out[9]: -1.0 | |
116 |
|
116 | |||
117 |
|
117 | |||
118 | In [10]: for i in range(5): |
|
118 | In [10]: for i in range(5): | |
119 | ....: print i, |
|
119 | ....: print i, | |
120 | ....: |
|
120 | ....: | |
121 | 0 1 2 3 4 |
|
121 | 0 1 2 3 4 | |
122 |
|
122 | |||
123 | In [11]: print "that's all folks!" |
|
123 | In [11]: print "that's all folks!" | |
124 | that's all folks! |
|
124 | that's all folks! | |
125 |
|
125 | |||
126 |
|
126 | |||
127 |
In [12]: |
|
127 | In [12]: exit | |
128 | """ |
|
128 | """ | |
129 | runner = irunner.IPythonRunner(out=self.out) |
|
129 | runner = irunner.IPythonRunner(out=self.out) | |
130 | self._test_runner(runner,source,output) |
|
130 | self._test_runner(runner,source,output) | |
131 |
|
131 | |||
132 | def testPython(self): |
|
132 | def testPython(self): | |
133 | """Test the Python runner.""" |
|
133 | """Test the Python runner.""" | |
134 | runner = irunner.PythonRunner(out=self.out) |
|
134 | runner = irunner.PythonRunner(out=self.out) | |
135 | source = """ |
|
135 | source = """ | |
136 | print 'hello, this is python' |
|
136 | print 'hello, this is python' | |
137 |
|
137 | |||
138 | # some more code |
|
138 | # some more code | |
139 | x=1;y=2 |
|
139 | x=1;y=2 | |
140 | x+y**2 |
|
140 | x+y**2 | |
141 |
|
141 | |||
142 | from math import * |
|
142 | from math import * | |
143 | cos(pi) |
|
143 | cos(pi) | |
144 |
|
144 | |||
145 | for i in range(5): |
|
145 | for i in range(5): | |
146 | print i, |
|
146 | print i, | |
147 |
|
147 | |||
148 | print "that's all folks!" |
|
148 | print "that's all folks!" | |
149 | """ |
|
149 | """ | |
150 | output = """\ |
|
150 | output = """\ | |
151 | >>> print 'hello, this is python' |
|
151 | >>> print 'hello, this is python' | |
152 | hello, this is python |
|
152 | hello, this is python | |
153 |
|
153 | |||
154 | # some more code |
|
154 | # some more code | |
155 | >>> x=1;y=2 |
|
155 | >>> x=1;y=2 | |
156 | >>> x+y**2 |
|
156 | >>> x+y**2 | |
157 | 5 |
|
157 | 5 | |
158 |
|
158 | |||
159 | >>> from math import * |
|
159 | >>> from math import * | |
160 | >>> cos(pi) |
|
160 | >>> cos(pi) | |
161 | -1.0 |
|
161 | -1.0 | |
162 |
|
162 | |||
163 | >>> for i in range(5): |
|
163 | >>> for i in range(5): | |
164 | ... print i, |
|
164 | ... print i, | |
165 | ... |
|
165 | ... | |
166 | 0 1 2 3 4 |
|
166 | 0 1 2 3 4 | |
167 | >>> print "that's all folks!" |
|
167 | >>> print "that's all folks!" | |
168 | that's all folks! |
|
168 | that's all folks! | |
169 | """ |
|
169 | """ | |
170 | self._test_runner(runner,source,output) |
|
170 | self._test_runner(runner,source,output) |
@@ -1,607 +1,601 b'' | |||||
1 | """A ZMQ-based subclass of InteractiveShell. |
|
1 | """A ZMQ-based subclass of InteractiveShell. | |
2 |
|
2 | |||
3 | This code is meant to ease the refactoring of the base InteractiveShell into |
|
3 | This code is meant to ease the refactoring of the base InteractiveShell into | |
4 | something with a cleaner architecture for 2-process use, without actually |
|
4 | something with a cleaner architecture for 2-process use, without actually | |
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where |
|
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where | |
6 | we subclass and override what we want to fix. Once this is working well, we |
|
6 | we subclass and override what we want to fix. Once this is working well, we | |
7 | can go back to the base class and refactor the code for a cleaner inheritance |
|
7 | can go back to the base class and refactor the code for a cleaner inheritance | |
8 | implementation that doesn't rely on so much monkeypatching. |
|
8 | implementation that doesn't rely on so much monkeypatching. | |
9 |
|
9 | |||
10 | But this lets us maintain a fully working IPython as we develop the new |
|
10 | But this lets us maintain a fully working IPython as we develop the new | |
11 | machinery. This should thus be thought of as scaffolding. |
|
11 | machinery. This should thus be thought of as scaffolding. | |
12 | """ |
|
12 | """ | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 |
|
21 | |||
22 | # Our own |
|
22 | # Our own | |
23 | from IPython.core.interactiveshell import ( |
|
23 | from IPython.core.interactiveshell import ( | |
24 | InteractiveShell, InteractiveShellABC |
|
24 | InteractiveShell, InteractiveShellABC | |
25 | ) |
|
25 | ) | |
26 | from IPython.core import page |
|
26 | from IPython.core import page | |
|
27 | from IPython.core.autocall import ZMQExitAutocall | |||
27 | from IPython.core.displayhook import DisplayHook |
|
28 | from IPython.core.displayhook import DisplayHook | |
28 | from IPython.core.displaypub import DisplayPublisher |
|
29 | from IPython.core.displaypub import DisplayPublisher | |
29 | from IPython.core.macro import Macro |
|
30 | from IPython.core.macro import Macro | |
30 | from IPython.core.payloadpage import install_payload_page |
|
31 | from IPython.core.payloadpage import install_payload_page | |
31 | from IPython.utils import io |
|
32 | from IPython.utils import io | |
32 | from IPython.utils.path import get_py_filename |
|
33 | from IPython.utils.path import get_py_filename | |
33 | from IPython.utils.traitlets import Instance, Type, Dict |
|
34 | from IPython.utils.traitlets import Instance, Type, Dict | |
34 | from IPython.utils.warn import warn |
|
35 | from IPython.utils.warn import warn | |
35 | from IPython.zmq.session import extract_header |
|
36 | from IPython.zmq.session import extract_header | |
36 | from session import Session |
|
37 | from session import Session | |
37 |
|
38 | |||
38 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
39 | # Globals and side-effects |
|
40 | # Globals and side-effects | |
40 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
41 |
|
42 | |||
42 | # Install the payload version of page. |
|
43 | # Install the payload version of page. | |
43 | install_payload_page() |
|
44 | install_payload_page() | |
44 |
|
45 | |||
45 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
46 | # Functions and classes |
|
47 | # Functions and classes | |
47 | #----------------------------------------------------------------------------- |
|
48 | #----------------------------------------------------------------------------- | |
48 |
|
49 | |||
49 | class ZMQDisplayHook(DisplayHook): |
|
50 | class ZMQDisplayHook(DisplayHook): | |
50 | """A displayhook subclass that publishes data using ZeroMQ.""" |
|
51 | """A displayhook subclass that publishes data using ZeroMQ.""" | |
51 |
|
52 | |||
52 | session = Instance(Session) |
|
53 | session = Instance(Session) | |
53 | pub_socket = Instance('zmq.Socket') |
|
54 | pub_socket = Instance('zmq.Socket') | |
54 | parent_header = Dict({}) |
|
55 | parent_header = Dict({}) | |
55 |
|
56 | |||
56 | def set_parent(self, parent): |
|
57 | def set_parent(self, parent): | |
57 | """Set the parent for outbound messages.""" |
|
58 | """Set the parent for outbound messages.""" | |
58 | self.parent_header = extract_header(parent) |
|
59 | self.parent_header = extract_header(parent) | |
59 |
|
60 | |||
60 | def start_displayhook(self): |
|
61 | def start_displayhook(self): | |
61 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
62 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) | |
62 |
|
63 | |||
63 | def write_output_prompt(self): |
|
64 | def write_output_prompt(self): | |
64 | """Write the output prompt.""" |
|
65 | """Write the output prompt.""" | |
65 | if self.do_full_cache: |
|
66 | if self.do_full_cache: | |
66 | self.msg['content']['execution_count'] = self.prompt_count |
|
67 | self.msg['content']['execution_count'] = self.prompt_count | |
67 |
|
68 | |||
68 | def write_format_data(self, format_dict): |
|
69 | def write_format_data(self, format_dict): | |
69 | self.msg['content']['data'] = format_dict |
|
70 | self.msg['content']['data'] = format_dict | |
70 |
|
71 | |||
71 | def finish_displayhook(self): |
|
72 | def finish_displayhook(self): | |
72 | """Finish up all displayhook activities.""" |
|
73 | """Finish up all displayhook activities.""" | |
73 | self.session.send(self.pub_socket, self.msg) |
|
74 | self.session.send(self.pub_socket, self.msg) | |
74 | self.msg = None |
|
75 | self.msg = None | |
75 |
|
76 | |||
76 |
|
77 | |||
77 | class ZMQDisplayPublisher(DisplayPublisher): |
|
78 | class ZMQDisplayPublisher(DisplayPublisher): | |
78 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" |
|
79 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" | |
79 |
|
80 | |||
80 | session = Instance(Session) |
|
81 | session = Instance(Session) | |
81 | pub_socket = Instance('zmq.Socket') |
|
82 | pub_socket = Instance('zmq.Socket') | |
82 | parent_header = Dict({}) |
|
83 | parent_header = Dict({}) | |
83 |
|
84 | |||
84 | def set_parent(self, parent): |
|
85 | def set_parent(self, parent): | |
85 | """Set the parent for outbound messages.""" |
|
86 | """Set the parent for outbound messages.""" | |
86 | self.parent_header = extract_header(parent) |
|
87 | self.parent_header = extract_header(parent) | |
87 |
|
88 | |||
88 | def publish(self, source, data, metadata=None): |
|
89 | def publish(self, source, data, metadata=None): | |
89 | if metadata is None: |
|
90 | if metadata is None: | |
90 | metadata = {} |
|
91 | metadata = {} | |
91 | self._validate_data(source, data, metadata) |
|
92 | self._validate_data(source, data, metadata) | |
92 | content = {} |
|
93 | content = {} | |
93 | content['source'] = source |
|
94 | content['source'] = source | |
94 | content['data'] = data |
|
95 | content['data'] = data | |
95 | content['metadata'] = metadata |
|
96 | content['metadata'] = metadata | |
96 | self.session.send( |
|
97 | self.session.send( | |
97 | self.pub_socket, u'display_data', content, |
|
98 | self.pub_socket, u'display_data', content, | |
98 | parent=self.parent_header |
|
99 | parent=self.parent_header | |
99 | ) |
|
100 | ) | |
100 |
|
101 | |||
101 |
|
102 | |||
102 | class ZMQInteractiveShell(InteractiveShell): |
|
103 | class ZMQInteractiveShell(InteractiveShell): | |
103 | """A subclass of InteractiveShell for ZMQ.""" |
|
104 | """A subclass of InteractiveShell for ZMQ.""" | |
104 |
|
105 | |||
105 | displayhook_class = Type(ZMQDisplayHook) |
|
106 | displayhook_class = Type(ZMQDisplayHook) | |
106 | display_pub_class = Type(ZMQDisplayPublisher) |
|
107 | display_pub_class = Type(ZMQDisplayPublisher) | |
|
108 | ||||
|
109 | exiter = Instance(ZMQExitAutocall) | |||
|
110 | def _exiter_default(self): | |||
|
111 | return ZMQExitAutocall(self) | |||
107 |
|
112 | |||
108 | keepkernel_on_exit = None |
|
113 | keepkernel_on_exit = None | |
109 |
|
114 | |||
110 | def init_environment(self): |
|
115 | def init_environment(self): | |
111 | """Configure the user's environment. |
|
116 | """Configure the user's environment. | |
112 |
|
117 | |||
113 | """ |
|
118 | """ | |
114 | env = os.environ |
|
119 | env = os.environ | |
115 | # These two ensure 'ls' produces nice coloring on BSD-derived systems |
|
120 | # These two ensure 'ls' produces nice coloring on BSD-derived systems | |
116 | env['TERM'] = 'xterm-color' |
|
121 | env['TERM'] = 'xterm-color' | |
117 | env['CLICOLOR'] = '1' |
|
122 | env['CLICOLOR'] = '1' | |
118 | # Since normal pagers don't work at all (over pexpect we don't have |
|
123 | # Since normal pagers don't work at all (over pexpect we don't have | |
119 | # single-key control of the subprocess), try to disable paging in |
|
124 | # single-key control of the subprocess), try to disable paging in | |
120 | # subprocesses as much as possible. |
|
125 | # subprocesses as much as possible. | |
121 | env['PAGER'] = 'cat' |
|
126 | env['PAGER'] = 'cat' | |
122 | env['GIT_PAGER'] = 'cat' |
|
127 | env['GIT_PAGER'] = 'cat' | |
123 |
|
128 | |||
124 | def auto_rewrite_input(self, cmd): |
|
129 | def auto_rewrite_input(self, cmd): | |
125 | """Called to show the auto-rewritten input for autocall and friends. |
|
130 | """Called to show the auto-rewritten input for autocall and friends. | |
126 |
|
131 | |||
127 | FIXME: this payload is currently not correctly processed by the |
|
132 | FIXME: this payload is currently not correctly processed by the | |
128 | frontend. |
|
133 | frontend. | |
129 | """ |
|
134 | """ | |
130 | new = self.displayhook.prompt1.auto_rewrite() + cmd |
|
135 | new = self.displayhook.prompt1.auto_rewrite() + cmd | |
131 | payload = dict( |
|
136 | payload = dict( | |
132 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', |
|
137 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', | |
133 | transformed_input=new, |
|
138 | transformed_input=new, | |
134 | ) |
|
139 | ) | |
135 | self.payload_manager.write_payload(payload) |
|
140 | self.payload_manager.write_payload(payload) | |
136 |
|
141 | |||
137 | def ask_exit(self): |
|
142 | def ask_exit(self): | |
138 | """Engage the exit actions.""" |
|
143 | """Engage the exit actions.""" | |
139 | payload = dict( |
|
144 | payload = dict( | |
140 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', |
|
145 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', | |
141 | exit=True, |
|
146 | exit=True, | |
142 | keepkernel=self.keepkernel_on_exit, |
|
147 | keepkernel=self.keepkernel_on_exit, | |
143 | ) |
|
148 | ) | |
144 | self.payload_manager.write_payload(payload) |
|
149 | self.payload_manager.write_payload(payload) | |
145 |
|
150 | |||
146 | def _showtraceback(self, etype, evalue, stb): |
|
151 | def _showtraceback(self, etype, evalue, stb): | |
147 |
|
152 | |||
148 | exc_content = { |
|
153 | exc_content = { | |
149 | u'traceback' : stb, |
|
154 | u'traceback' : stb, | |
150 | u'ename' : unicode(etype.__name__), |
|
155 | u'ename' : unicode(etype.__name__), | |
151 | u'evalue' : unicode(evalue) |
|
156 | u'evalue' : unicode(evalue) | |
152 | } |
|
157 | } | |
153 |
|
158 | |||
154 | dh = self.displayhook |
|
159 | dh = self.displayhook | |
155 | # Send exception info over pub socket for other clients than the caller |
|
160 | # Send exception info over pub socket for other clients than the caller | |
156 | # to pick up |
|
161 | # to pick up | |
157 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) |
|
162 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) | |
158 |
|
163 | |||
159 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
164 | # FIXME - Hack: store exception info in shell object. Right now, the | |
160 | # caller is reading this info after the fact, we need to fix this logic |
|
165 | # caller is reading this info after the fact, we need to fix this logic | |
161 | # to remove this hack. Even uglier, we need to store the error status |
|
166 | # to remove this hack. Even uglier, we need to store the error status | |
162 | # here, because in the main loop, the logic that sets it is being |
|
167 | # here, because in the main loop, the logic that sets it is being | |
163 | # skipped because runlines swallows the exceptions. |
|
168 | # skipped because runlines swallows the exceptions. | |
164 | exc_content[u'status'] = u'error' |
|
169 | exc_content[u'status'] = u'error' | |
165 | self._reply_content = exc_content |
|
170 | self._reply_content = exc_content | |
166 | # /FIXME |
|
171 | # /FIXME | |
167 |
|
172 | |||
168 | return exc_content |
|
173 | return exc_content | |
169 |
|
174 | |||
170 | #------------------------------------------------------------------------ |
|
175 | #------------------------------------------------------------------------ | |
171 | # Magic overrides |
|
176 | # Magic overrides | |
172 | #------------------------------------------------------------------------ |
|
177 | #------------------------------------------------------------------------ | |
173 | # Once the base class stops inheriting from magic, this code needs to be |
|
178 | # Once the base class stops inheriting from magic, this code needs to be | |
174 | # moved into a separate machinery as well. For now, at least isolate here |
|
179 | # moved into a separate machinery as well. For now, at least isolate here | |
175 | # the magics which this class needs to implement differently from the base |
|
180 | # the magics which this class needs to implement differently from the base | |
176 | # class, or that are unique to it. |
|
181 | # class, or that are unique to it. | |
177 |
|
182 | |||
178 | def magic_doctest_mode(self,parameter_s=''): |
|
183 | def magic_doctest_mode(self,parameter_s=''): | |
179 | """Toggle doctest mode on and off. |
|
184 | """Toggle doctest mode on and off. | |
180 |
|
185 | |||
181 | This mode is intended to make IPython behave as much as possible like a |
|
186 | This mode is intended to make IPython behave as much as possible like a | |
182 | plain Python shell, from the perspective of how its prompts, exceptions |
|
187 | plain Python shell, from the perspective of how its prompts, exceptions | |
183 | and output look. This makes it easy to copy and paste parts of a |
|
188 | and output look. This makes it easy to copy and paste parts of a | |
184 | session into doctests. It does so by: |
|
189 | session into doctests. It does so by: | |
185 |
|
190 | |||
186 | - Changing the prompts to the classic ``>>>`` ones. |
|
191 | - Changing the prompts to the classic ``>>>`` ones. | |
187 | - Changing the exception reporting mode to 'Plain'. |
|
192 | - Changing the exception reporting mode to 'Plain'. | |
188 | - Disabling pretty-printing of output. |
|
193 | - Disabling pretty-printing of output. | |
189 |
|
194 | |||
190 | Note that IPython also supports the pasting of code snippets that have |
|
195 | Note that IPython also supports the pasting of code snippets that have | |
191 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
196 | leading '>>>' and '...' prompts in them. This means that you can paste | |
192 | doctests from files or docstrings (even if they have leading |
|
197 | doctests from files or docstrings (even if they have leading | |
193 | whitespace), and the code will execute correctly. You can then use |
|
198 | whitespace), and the code will execute correctly. You can then use | |
194 | '%history -t' to see the translated history; this will give you the |
|
199 | '%history -t' to see the translated history; this will give you the | |
195 | input after removal of all the leading prompts and whitespace, which |
|
200 | input after removal of all the leading prompts and whitespace, which | |
196 | can be pasted back into an editor. |
|
201 | can be pasted back into an editor. | |
197 |
|
202 | |||
198 | With these features, you can switch into this mode easily whenever you |
|
203 | With these features, you can switch into this mode easily whenever you | |
199 | need to do testing and changes to doctests, without having to leave |
|
204 | need to do testing and changes to doctests, without having to leave | |
200 | your existing IPython session. |
|
205 | your existing IPython session. | |
201 | """ |
|
206 | """ | |
202 |
|
207 | |||
203 | from IPython.utils.ipstruct import Struct |
|
208 | from IPython.utils.ipstruct import Struct | |
204 |
|
209 | |||
205 | # Shorthands |
|
210 | # Shorthands | |
206 | shell = self.shell |
|
211 | shell = self.shell | |
207 | disp_formatter = self.shell.display_formatter |
|
212 | disp_formatter = self.shell.display_formatter | |
208 | ptformatter = disp_formatter.formatters['text/plain'] |
|
213 | ptformatter = disp_formatter.formatters['text/plain'] | |
209 | # dstore is a data store kept in the instance metadata bag to track any |
|
214 | # dstore is a data store kept in the instance metadata bag to track any | |
210 | # changes we make, so we can undo them later. |
|
215 | # changes we make, so we can undo them later. | |
211 | dstore = shell.meta.setdefault('doctest_mode', Struct()) |
|
216 | dstore = shell.meta.setdefault('doctest_mode', Struct()) | |
212 | save_dstore = dstore.setdefault |
|
217 | save_dstore = dstore.setdefault | |
213 |
|
218 | |||
214 | # save a few values we'll need to recover later |
|
219 | # save a few values we'll need to recover later | |
215 | mode = save_dstore('mode', False) |
|
220 | mode = save_dstore('mode', False) | |
216 | save_dstore('rc_pprint', ptformatter.pprint) |
|
221 | save_dstore('rc_pprint', ptformatter.pprint) | |
217 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
222 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
218 | save_dstore('xmode', shell.InteractiveTB.mode) |
|
223 | save_dstore('xmode', shell.InteractiveTB.mode) | |
219 |
|
224 | |||
220 | if mode == False: |
|
225 | if mode == False: | |
221 | # turn on |
|
226 | # turn on | |
222 | ptformatter.pprint = False |
|
227 | ptformatter.pprint = False | |
223 | disp_formatter.plain_text_only = True |
|
228 | disp_formatter.plain_text_only = True | |
224 | shell.magic_xmode('Plain') |
|
229 | shell.magic_xmode('Plain') | |
225 | else: |
|
230 | else: | |
226 | # turn off |
|
231 | # turn off | |
227 | ptformatter.pprint = dstore.rc_pprint |
|
232 | ptformatter.pprint = dstore.rc_pprint | |
228 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
233 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
229 | shell.magic_xmode(dstore.xmode) |
|
234 | shell.magic_xmode(dstore.xmode) | |
230 |
|
235 | |||
231 | # Store new mode and inform on console |
|
236 | # Store new mode and inform on console | |
232 | dstore.mode = bool(1-int(mode)) |
|
237 | dstore.mode = bool(1-int(mode)) | |
233 | mode_label = ['OFF','ON'][dstore.mode] |
|
238 | mode_label = ['OFF','ON'][dstore.mode] | |
234 | print('Doctest mode is:', mode_label) |
|
239 | print('Doctest mode is:', mode_label) | |
235 |
|
240 | |||
236 | # Send the payload back so that clients can modify their prompt display |
|
241 | # Send the payload back so that clients can modify their prompt display | |
237 | payload = dict( |
|
242 | payload = dict( | |
238 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', |
|
243 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', | |
239 | mode=dstore.mode) |
|
244 | mode=dstore.mode) | |
240 | self.payload_manager.write_payload(payload) |
|
245 | self.payload_manager.write_payload(payload) | |
241 |
|
246 | |||
242 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
247 | def magic_edit(self,parameter_s='',last_call=['','']): | |
243 | """Bring up an editor and execute the resulting code. |
|
248 | """Bring up an editor and execute the resulting code. | |
244 |
|
249 | |||
245 | Usage: |
|
250 | Usage: | |
246 | %edit [options] [args] |
|
251 | %edit [options] [args] | |
247 |
|
252 | |||
248 | %edit runs IPython's editor hook. The default version of this hook is |
|
253 | %edit runs IPython's editor hook. The default version of this hook is | |
249 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
254 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
250 | environment variable $EDITOR. If this isn't found, it will default to |
|
255 | environment variable $EDITOR. If this isn't found, it will default to | |
251 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
256 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
252 | docstring for how to change the editor hook. |
|
257 | docstring for how to change the editor hook. | |
253 |
|
258 | |||
254 | You can also set the value of this editor via the command line option |
|
259 | You can also set the value of this editor via the command line option | |
255 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
260 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
256 | specifically for IPython an editor different from your typical default |
|
261 | specifically for IPython an editor different from your typical default | |
257 | (and for Windows users who typically don't set environment variables). |
|
262 | (and for Windows users who typically don't set environment variables). | |
258 |
|
263 | |||
259 | This command allows you to conveniently edit multi-line code right in |
|
264 | This command allows you to conveniently edit multi-line code right in | |
260 | your IPython session. |
|
265 | your IPython session. | |
261 |
|
266 | |||
262 | If called without arguments, %edit opens up an empty editor with a |
|
267 | If called without arguments, %edit opens up an empty editor with a | |
263 | temporary file and will execute the contents of this file when you |
|
268 | temporary file and will execute the contents of this file when you | |
264 | close it (don't forget to save it!). |
|
269 | close it (don't forget to save it!). | |
265 |
|
270 | |||
266 |
|
271 | |||
267 | Options: |
|
272 | Options: | |
268 |
|
273 | |||
269 | -n <number>: open the editor at a specified line number. By default, |
|
274 | -n <number>: open the editor at a specified line number. By default, | |
270 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
275 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
271 | you can configure this by providing your own modified hook if your |
|
276 | you can configure this by providing your own modified hook if your | |
272 | favorite editor supports line-number specifications with a different |
|
277 | favorite editor supports line-number specifications with a different | |
273 | syntax. |
|
278 | syntax. | |
274 |
|
279 | |||
275 | -p: this will call the editor with the same data as the previous time |
|
280 | -p: this will call the editor with the same data as the previous time | |
276 | it was used, regardless of how long ago (in your current session) it |
|
281 | it was used, regardless of how long ago (in your current session) it | |
277 | was. |
|
282 | was. | |
278 |
|
283 | |||
279 | -r: use 'raw' input. This option only applies to input taken from the |
|
284 | -r: use 'raw' input. This option only applies to input taken from the | |
280 | user's history. By default, the 'processed' history is used, so that |
|
285 | user's history. By default, the 'processed' history is used, so that | |
281 | magics are loaded in their transformed version to valid Python. If |
|
286 | magics are loaded in their transformed version to valid Python. If | |
282 | this option is given, the raw input as typed as the command line is |
|
287 | this option is given, the raw input as typed as the command line is | |
283 | used instead. When you exit the editor, it will be executed by |
|
288 | used instead. When you exit the editor, it will be executed by | |
284 | IPython's own processor. |
|
289 | IPython's own processor. | |
285 |
|
290 | |||
286 | -x: do not execute the edited code immediately upon exit. This is |
|
291 | -x: do not execute the edited code immediately upon exit. This is | |
287 | mainly useful if you are editing programs which need to be called with |
|
292 | mainly useful if you are editing programs which need to be called with | |
288 | command line arguments, which you can then do using %run. |
|
293 | command line arguments, which you can then do using %run. | |
289 |
|
294 | |||
290 |
|
295 | |||
291 | Arguments: |
|
296 | Arguments: | |
292 |
|
297 | |||
293 | If arguments are given, the following possibilites exist: |
|
298 | If arguments are given, the following possibilites exist: | |
294 |
|
299 | |||
295 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
300 | - The arguments are numbers or pairs of colon-separated numbers (like | |
296 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
301 | 1 4:8 9). These are interpreted as lines of previous input to be | |
297 | loaded into the editor. The syntax is the same of the %macro command. |
|
302 | loaded into the editor. The syntax is the same of the %macro command. | |
298 |
|
303 | |||
299 | - If the argument doesn't start with a number, it is evaluated as a |
|
304 | - If the argument doesn't start with a number, it is evaluated as a | |
300 | variable and its contents loaded into the editor. You can thus edit |
|
305 | variable and its contents loaded into the editor. You can thus edit | |
301 | any string which contains python code (including the result of |
|
306 | any string which contains python code (including the result of | |
302 | previous edits). |
|
307 | previous edits). | |
303 |
|
308 | |||
304 | - If the argument is the name of an object (other than a string), |
|
309 | - If the argument is the name of an object (other than a string), | |
305 | IPython will try to locate the file where it was defined and open the |
|
310 | IPython will try to locate the file where it was defined and open the | |
306 | editor at the point where it is defined. You can use `%edit function` |
|
311 | editor at the point where it is defined. You can use `%edit function` | |
307 | to load an editor exactly at the point where 'function' is defined, |
|
312 | to load an editor exactly at the point where 'function' is defined, | |
308 | edit it and have the file be executed automatically. |
|
313 | edit it and have the file be executed automatically. | |
309 |
|
314 | |||
310 | If the object is a macro (see %macro for details), this opens up your |
|
315 | If the object is a macro (see %macro for details), this opens up your | |
311 | specified editor with a temporary file containing the macro's data. |
|
316 | specified editor with a temporary file containing the macro's data. | |
312 | Upon exit, the macro is reloaded with the contents of the file. |
|
317 | Upon exit, the macro is reloaded with the contents of the file. | |
313 |
|
318 | |||
314 | Note: opening at an exact line is only supported under Unix, and some |
|
319 | Note: opening at an exact line is only supported under Unix, and some | |
315 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
320 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
316 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
321 | '+NUMBER' parameter necessary for this feature. Good editors like | |
317 | (X)Emacs, vi, jed, pico and joe all do. |
|
322 | (X)Emacs, vi, jed, pico and joe all do. | |
318 |
|
323 | |||
319 | - If the argument is not found as a variable, IPython will look for a |
|
324 | - If the argument is not found as a variable, IPython will look for a | |
320 | file with that name (adding .py if necessary) and load it into the |
|
325 | file with that name (adding .py if necessary) and load it into the | |
321 | editor. It will execute its contents with execfile() when you exit, |
|
326 | editor. It will execute its contents with execfile() when you exit, | |
322 | loading any code in the file into your interactive namespace. |
|
327 | loading any code in the file into your interactive namespace. | |
323 |
|
328 | |||
324 | After executing your code, %edit will return as output the code you |
|
329 | After executing your code, %edit will return as output the code you | |
325 | typed in the editor (except when it was an existing file). This way |
|
330 | typed in the editor (except when it was an existing file). This way | |
326 | you can reload the code in further invocations of %edit as a variable, |
|
331 | you can reload the code in further invocations of %edit as a variable, | |
327 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
332 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
328 | the output. |
|
333 | the output. | |
329 |
|
334 | |||
330 | Note that %edit is also available through the alias %ed. |
|
335 | Note that %edit is also available through the alias %ed. | |
331 |
|
336 | |||
332 | This is an example of creating a simple function inside the editor and |
|
337 | This is an example of creating a simple function inside the editor and | |
333 | then modifying it. First, start up the editor: |
|
338 | then modifying it. First, start up the editor: | |
334 |
|
339 | |||
335 | In [1]: ed |
|
340 | In [1]: ed | |
336 | Editing... done. Executing edited code... |
|
341 | Editing... done. Executing edited code... | |
337 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
342 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
338 |
|
343 | |||
339 | We can then call the function foo(): |
|
344 | We can then call the function foo(): | |
340 |
|
345 | |||
341 | In [2]: foo() |
|
346 | In [2]: foo() | |
342 | foo() was defined in an editing session |
|
347 | foo() was defined in an editing session | |
343 |
|
348 | |||
344 | Now we edit foo. IPython automatically loads the editor with the |
|
349 | Now we edit foo. IPython automatically loads the editor with the | |
345 | (temporary) file where foo() was previously defined: |
|
350 | (temporary) file where foo() was previously defined: | |
346 |
|
351 | |||
347 | In [3]: ed foo |
|
352 | In [3]: ed foo | |
348 | Editing... done. Executing edited code... |
|
353 | Editing... done. Executing edited code... | |
349 |
|
354 | |||
350 | And if we call foo() again we get the modified version: |
|
355 | And if we call foo() again we get the modified version: | |
351 |
|
356 | |||
352 | In [4]: foo() |
|
357 | In [4]: foo() | |
353 | foo() has now been changed! |
|
358 | foo() has now been changed! | |
354 |
|
359 | |||
355 | Here is an example of how to edit a code snippet successive |
|
360 | Here is an example of how to edit a code snippet successive | |
356 | times. First we call the editor: |
|
361 | times. First we call the editor: | |
357 |
|
362 | |||
358 | In [5]: ed |
|
363 | In [5]: ed | |
359 | Editing... done. Executing edited code... |
|
364 | Editing... done. Executing edited code... | |
360 | hello |
|
365 | hello | |
361 | Out[5]: "print 'hello'n" |
|
366 | Out[5]: "print 'hello'n" | |
362 |
|
367 | |||
363 | Now we call it again with the previous output (stored in _): |
|
368 | Now we call it again with the previous output (stored in _): | |
364 |
|
369 | |||
365 | In [6]: ed _ |
|
370 | In [6]: ed _ | |
366 | Editing... done. Executing edited code... |
|
371 | Editing... done. Executing edited code... | |
367 | hello world |
|
372 | hello world | |
368 | Out[6]: "print 'hello world'n" |
|
373 | Out[6]: "print 'hello world'n" | |
369 |
|
374 | |||
370 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
375 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
371 |
|
376 | |||
372 | In [7]: ed _8 |
|
377 | In [7]: ed _8 | |
373 | Editing... done. Executing edited code... |
|
378 | Editing... done. Executing edited code... | |
374 | hello again |
|
379 | hello again | |
375 | Out[7]: "print 'hello again'n" |
|
380 | Out[7]: "print 'hello again'n" | |
376 |
|
381 | |||
377 |
|
382 | |||
378 | Changing the default editor hook: |
|
383 | Changing the default editor hook: | |
379 |
|
384 | |||
380 | If you wish to write your own editor hook, you can put it in a |
|
385 | If you wish to write your own editor hook, you can put it in a | |
381 | configuration file which you load at startup time. The default hook |
|
386 | configuration file which you load at startup time. The default hook | |
382 | is defined in the IPython.core.hooks module, and you can use that as a |
|
387 | is defined in the IPython.core.hooks module, and you can use that as a | |
383 | starting example for further modifications. That file also has |
|
388 | starting example for further modifications. That file also has | |
384 | general instructions on how to set a new hook for use once you've |
|
389 | general instructions on how to set a new hook for use once you've | |
385 | defined it.""" |
|
390 | defined it.""" | |
386 |
|
391 | |||
387 | # FIXME: This function has become a convoluted mess. It needs a |
|
392 | # FIXME: This function has become a convoluted mess. It needs a | |
388 | # ground-up rewrite with clean, simple logic. |
|
393 | # ground-up rewrite with clean, simple logic. | |
389 |
|
394 | |||
390 | def make_filename(arg): |
|
395 | def make_filename(arg): | |
391 | "Make a filename from the given args" |
|
396 | "Make a filename from the given args" | |
392 | try: |
|
397 | try: | |
393 | filename = get_py_filename(arg) |
|
398 | filename = get_py_filename(arg) | |
394 | except IOError: |
|
399 | except IOError: | |
395 | if args.endswith('.py'): |
|
400 | if args.endswith('.py'): | |
396 | filename = arg |
|
401 | filename = arg | |
397 | else: |
|
402 | else: | |
398 | filename = None |
|
403 | filename = None | |
399 | return filename |
|
404 | return filename | |
400 |
|
405 | |||
401 | # custom exceptions |
|
406 | # custom exceptions | |
402 | class DataIsObject(Exception): pass |
|
407 | class DataIsObject(Exception): pass | |
403 |
|
408 | |||
404 | opts,args = self.parse_options(parameter_s,'prn:') |
|
409 | opts,args = self.parse_options(parameter_s,'prn:') | |
405 | # Set a few locals from the options for convenience: |
|
410 | # Set a few locals from the options for convenience: | |
406 | opts_p = opts.has_key('p') |
|
411 | opts_p = opts.has_key('p') | |
407 | opts_r = opts.has_key('r') |
|
412 | opts_r = opts.has_key('r') | |
408 |
|
413 | |||
409 | # Default line number value |
|
414 | # Default line number value | |
410 | lineno = opts.get('n',None) |
|
415 | lineno = opts.get('n',None) | |
411 | if lineno is not None: |
|
416 | if lineno is not None: | |
412 | try: |
|
417 | try: | |
413 | lineno = int(lineno) |
|
418 | lineno = int(lineno) | |
414 | except: |
|
419 | except: | |
415 | warn("The -n argument must be an integer.") |
|
420 | warn("The -n argument must be an integer.") | |
416 | return |
|
421 | return | |
417 |
|
422 | |||
418 | if opts_p: |
|
423 | if opts_p: | |
419 | args = '_%s' % last_call[0] |
|
424 | args = '_%s' % last_call[0] | |
420 | if not self.shell.user_ns.has_key(args): |
|
425 | if not self.shell.user_ns.has_key(args): | |
421 | args = last_call[1] |
|
426 | args = last_call[1] | |
422 |
|
427 | |||
423 | # use last_call to remember the state of the previous call, but don't |
|
428 | # use last_call to remember the state of the previous call, but don't | |
424 | # let it be clobbered by successive '-p' calls. |
|
429 | # let it be clobbered by successive '-p' calls. | |
425 | try: |
|
430 | try: | |
426 | last_call[0] = self.shell.displayhook.prompt_count |
|
431 | last_call[0] = self.shell.displayhook.prompt_count | |
427 | if not opts_p: |
|
432 | if not opts_p: | |
428 | last_call[1] = parameter_s |
|
433 | last_call[1] = parameter_s | |
429 | except: |
|
434 | except: | |
430 | pass |
|
435 | pass | |
431 |
|
436 | |||
432 | # by default this is done with temp files, except when the given |
|
437 | # by default this is done with temp files, except when the given | |
433 | # arg is a filename |
|
438 | # arg is a filename | |
434 | use_temp = True |
|
439 | use_temp = True | |
435 |
|
440 | |||
436 | data = '' |
|
441 | data = '' | |
437 | if args[0].isdigit(): |
|
442 | if args[0].isdigit(): | |
438 | # Mode where user specifies ranges of lines, like in %macro. |
|
443 | # Mode where user specifies ranges of lines, like in %macro. | |
439 | # This means that you can't edit files whose names begin with |
|
444 | # This means that you can't edit files whose names begin with | |
440 | # numbers this way. Tough. |
|
445 | # numbers this way. Tough. | |
441 | ranges = args.split() |
|
446 | ranges = args.split() | |
442 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
447 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
443 | elif args.endswith('.py'): |
|
448 | elif args.endswith('.py'): | |
444 | filename = make_filename(args) |
|
449 | filename = make_filename(args) | |
445 | use_temp = False |
|
450 | use_temp = False | |
446 | elif args: |
|
451 | elif args: | |
447 | try: |
|
452 | try: | |
448 | # Load the parameter given as a variable. If not a string, |
|
453 | # Load the parameter given as a variable. If not a string, | |
449 | # process it as an object instead (below) |
|
454 | # process it as an object instead (below) | |
450 |
|
455 | |||
451 | #print '*** args',args,'type',type(args) # dbg |
|
456 | #print '*** args',args,'type',type(args) # dbg | |
452 | data = eval(args, self.shell.user_ns) |
|
457 | data = eval(args, self.shell.user_ns) | |
453 | if not isinstance(data, basestring): |
|
458 | if not isinstance(data, basestring): | |
454 | raise DataIsObject |
|
459 | raise DataIsObject | |
455 |
|
460 | |||
456 | except (NameError,SyntaxError): |
|
461 | except (NameError,SyntaxError): | |
457 | # given argument is not a variable, try as a filename |
|
462 | # given argument is not a variable, try as a filename | |
458 | filename = make_filename(args) |
|
463 | filename = make_filename(args) | |
459 | if filename is None: |
|
464 | if filename is None: | |
460 | warn("Argument given (%s) can't be found as a variable " |
|
465 | warn("Argument given (%s) can't be found as a variable " | |
461 | "or as a filename." % args) |
|
466 | "or as a filename." % args) | |
462 | return |
|
467 | return | |
463 | use_temp = False |
|
468 | use_temp = False | |
464 |
|
469 | |||
465 | except DataIsObject: |
|
470 | except DataIsObject: | |
466 | # macros have a special edit function |
|
471 | # macros have a special edit function | |
467 | if isinstance(data, Macro): |
|
472 | if isinstance(data, Macro): | |
468 | self._edit_macro(args,data) |
|
473 | self._edit_macro(args,data) | |
469 | return |
|
474 | return | |
470 |
|
475 | |||
471 | # For objects, try to edit the file where they are defined |
|
476 | # For objects, try to edit the file where they are defined | |
472 | try: |
|
477 | try: | |
473 | filename = inspect.getabsfile(data) |
|
478 | filename = inspect.getabsfile(data) | |
474 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
479 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
475 | # class created by %edit? Try to find source |
|
480 | # class created by %edit? Try to find source | |
476 | # by looking for method definitions instead, the |
|
481 | # by looking for method definitions instead, the | |
477 | # __module__ in those classes is FakeModule. |
|
482 | # __module__ in those classes is FakeModule. | |
478 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
483 | attrs = [getattr(data, aname) for aname in dir(data)] | |
479 | for attr in attrs: |
|
484 | for attr in attrs: | |
480 | if not inspect.ismethod(attr): |
|
485 | if not inspect.ismethod(attr): | |
481 | continue |
|
486 | continue | |
482 | filename = inspect.getabsfile(attr) |
|
487 | filename = inspect.getabsfile(attr) | |
483 | if filename and 'fakemodule' not in filename.lower(): |
|
488 | if filename and 'fakemodule' not in filename.lower(): | |
484 | # change the attribute to be the edit target instead |
|
489 | # change the attribute to be the edit target instead | |
485 | data = attr |
|
490 | data = attr | |
486 | break |
|
491 | break | |
487 |
|
492 | |||
488 | datafile = 1 |
|
493 | datafile = 1 | |
489 | except TypeError: |
|
494 | except TypeError: | |
490 | filename = make_filename(args) |
|
495 | filename = make_filename(args) | |
491 | datafile = 1 |
|
496 | datafile = 1 | |
492 | warn('Could not find file where `%s` is defined.\n' |
|
497 | warn('Could not find file where `%s` is defined.\n' | |
493 | 'Opening a file named `%s`' % (args,filename)) |
|
498 | 'Opening a file named `%s`' % (args,filename)) | |
494 | # Now, make sure we can actually read the source (if it was in |
|
499 | # Now, make sure we can actually read the source (if it was in | |
495 | # a temp file it's gone by now). |
|
500 | # a temp file it's gone by now). | |
496 | if datafile: |
|
501 | if datafile: | |
497 | try: |
|
502 | try: | |
498 | if lineno is None: |
|
503 | if lineno is None: | |
499 | lineno = inspect.getsourcelines(data)[1] |
|
504 | lineno = inspect.getsourcelines(data)[1] | |
500 | except IOError: |
|
505 | except IOError: | |
501 | filename = make_filename(args) |
|
506 | filename = make_filename(args) | |
502 | if filename is None: |
|
507 | if filename is None: | |
503 | warn('The file `%s` where `%s` was defined cannot ' |
|
508 | warn('The file `%s` where `%s` was defined cannot ' | |
504 | 'be read.' % (filename,data)) |
|
509 | 'be read.' % (filename,data)) | |
505 | return |
|
510 | return | |
506 | use_temp = False |
|
511 | use_temp = False | |
507 |
|
512 | |||
508 | if use_temp: |
|
513 | if use_temp: | |
509 | filename = self.shell.mktempfile(data) |
|
514 | filename = self.shell.mktempfile(data) | |
510 | print('IPython will make a temporary file named:', filename) |
|
515 | print('IPython will make a temporary file named:', filename) | |
511 |
|
516 | |||
512 | # Make sure we send to the client an absolute path, in case the working |
|
517 | # Make sure we send to the client an absolute path, in case the working | |
513 | # directory of client and kernel don't match |
|
518 | # directory of client and kernel don't match | |
514 | filename = os.path.abspath(filename) |
|
519 | filename = os.path.abspath(filename) | |
515 |
|
520 | |||
516 | payload = { |
|
521 | payload = { | |
517 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
522 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
518 | 'filename' : filename, |
|
523 | 'filename' : filename, | |
519 | 'line_number' : lineno |
|
524 | 'line_number' : lineno | |
520 | } |
|
525 | } | |
521 | self.payload_manager.write_payload(payload) |
|
526 | self.payload_manager.write_payload(payload) | |
522 |
|
527 | |||
523 | def magic_gui(self, *args, **kwargs): |
|
528 | def magic_gui(self, *args, **kwargs): | |
524 | raise NotImplementedError( |
|
529 | raise NotImplementedError( | |
525 | 'GUI support must be enabled in command line options.') |
|
530 | 'GUI support must be enabled in command line options.') | |
526 |
|
531 | |||
527 | def magic_pylab(self, *args, **kwargs): |
|
532 | def magic_pylab(self, *args, **kwargs): | |
528 | raise NotImplementedError( |
|
533 | raise NotImplementedError( | |
529 | 'pylab support must be enabled in command line options.') |
|
534 | 'pylab support must be enabled in command line options.') | |
530 |
|
535 | |||
531 | # A few magics that are adapted to the specifics of using pexpect and a |
|
536 | # A few magics that are adapted to the specifics of using pexpect and a | |
532 | # remote terminal |
|
537 | # remote terminal | |
533 |
|
538 | |||
534 | def magic_clear(self, arg_s): |
|
539 | def magic_clear(self, arg_s): | |
535 | """Clear the terminal.""" |
|
540 | """Clear the terminal.""" | |
536 | if os.name == 'posix': |
|
541 | if os.name == 'posix': | |
537 | self.shell.system("clear") |
|
542 | self.shell.system("clear") | |
538 | else: |
|
543 | else: | |
539 | self.shell.system("cls") |
|
544 | self.shell.system("cls") | |
540 |
|
545 | |||
541 | if os.name == 'nt': |
|
546 | if os.name == 'nt': | |
542 | # This is the usual name in windows |
|
547 | # This is the usual name in windows | |
543 | magic_cls = magic_clear |
|
548 | magic_cls = magic_clear | |
544 |
|
549 | |||
545 | # Terminal pagers won't work over pexpect, but we do have our own pager |
|
550 | # Terminal pagers won't work over pexpect, but we do have our own pager | |
546 |
|
551 | |||
547 | def magic_less(self, arg_s): |
|
552 | def magic_less(self, arg_s): | |
548 | """Show a file through the pager. |
|
553 | """Show a file through the pager. | |
549 |
|
554 | |||
550 | Files ending in .py are syntax-highlighted.""" |
|
555 | Files ending in .py are syntax-highlighted.""" | |
551 | cont = open(arg_s).read() |
|
556 | cont = open(arg_s).read() | |
552 | if arg_s.endswith('.py'): |
|
557 | if arg_s.endswith('.py'): | |
553 | cont = self.shell.pycolorize(cont) |
|
558 | cont = self.shell.pycolorize(cont) | |
554 | page.page(cont) |
|
559 | page.page(cont) | |
555 |
|
560 | |||
556 | magic_more = magic_less |
|
561 | magic_more = magic_less | |
557 |
|
562 | |||
558 | # Man calls a pager, so we also need to redefine it |
|
563 | # Man calls a pager, so we also need to redefine it | |
559 | if os.name == 'posix': |
|
564 | if os.name == 'posix': | |
560 | def magic_man(self, arg_s): |
|
565 | def magic_man(self, arg_s): | |
561 | """Find the man page for the given command and display in pager.""" |
|
566 | """Find the man page for the given command and display in pager.""" | |
562 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, |
|
567 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, | |
563 | split=False)) |
|
568 | split=False)) | |
564 |
|
569 | |||
565 | # FIXME: this is specific to the GUI, so we should let the gui app load |
|
570 | # FIXME: this is specific to the GUI, so we should let the gui app load | |
566 | # magics at startup that are only for the gui. Once the gui app has proper |
|
571 | # magics at startup that are only for the gui. Once the gui app has proper | |
567 | # profile and configuration management, we can have it initialize a kernel |
|
572 | # profile and configuration management, we can have it initialize a kernel | |
568 | # with a special config file that provides these. |
|
573 | # with a special config file that provides these. | |
569 | def magic_guiref(self, arg_s): |
|
574 | def magic_guiref(self, arg_s): | |
570 | """Show a basic reference about the GUI console.""" |
|
575 | """Show a basic reference about the GUI console.""" | |
571 | from IPython.core.usage import gui_reference |
|
576 | from IPython.core.usage import gui_reference | |
572 | page.page(gui_reference, auto_html=True) |
|
577 | page.page(gui_reference, auto_html=True) | |
573 |
|
578 | |||
574 | def magic_loadpy(self, arg_s): |
|
579 | def magic_loadpy(self, arg_s): | |
575 | """Load a .py python script into the GUI console. |
|
580 | """Load a .py python script into the GUI console. | |
576 |
|
581 | |||
577 | This magic command can either take a local filename or a url:: |
|
582 | This magic command can either take a local filename or a url:: | |
578 |
|
583 | |||
579 | %loadpy myscript.py |
|
584 | %loadpy myscript.py | |
580 | %loadpy http://www.example.com/myscript.py |
|
585 | %loadpy http://www.example.com/myscript.py | |
581 | """ |
|
586 | """ | |
582 | if not arg_s.endswith('.py'): |
|
587 | if not arg_s.endswith('.py'): | |
583 | raise ValueError('%%load only works with .py files: %s' % arg_s) |
|
588 | raise ValueError('%%load only works with .py files: %s' % arg_s) | |
584 | if arg_s.startswith('http'): |
|
589 | if arg_s.startswith('http'): | |
585 | import urllib2 |
|
590 | import urllib2 | |
586 | response = urllib2.urlopen(arg_s) |
|
591 | response = urllib2.urlopen(arg_s) | |
587 | content = response.read() |
|
592 | content = response.read() | |
588 | else: |
|
593 | else: | |
589 | content = open(arg_s).read() |
|
594 | content = open(arg_s).read() | |
590 | payload = dict( |
|
595 | payload = dict( | |
591 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy', |
|
596 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_loadpy', | |
592 | text=content |
|
597 | text=content | |
593 | ) |
|
598 | ) | |
594 | self.payload_manager.write_payload(payload) |
|
599 | self.payload_manager.write_payload(payload) | |
595 |
|
||||
596 | def magic_Exit(self, parameter_s=''): |
|
|||
597 | """Exit IPython. If the -k option is provided, the kernel will be left |
|
|||
598 | running. Otherwise, it will shutdown without prompting. |
|
|||
599 | """ |
|
|||
600 | opts,args = self.parse_options(parameter_s,'k') |
|
|||
601 | self.shell.keepkernel_on_exit = opts.has_key('k') |
|
|||
602 | self.shell.ask_exit() |
|
|||
603 |
|
||||
604 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
|||
605 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
|||
606 |
|
600 | |||
607 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
601 | InteractiveShellABC.register(ZMQInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now