Show More
@@ -1,589 +1,592 b'' | |||||
1 | """ History related magics and functionality """ |
|
1 | """ History related magics and functionality """ | |
2 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
3 | # Copyright (C) 2010 The IPython Development Team. |
|
3 | # Copyright (C) 2010 The IPython Development Team. | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the BSD License. |
|
5 | # Distributed under the terms of the BSD License. | |
6 | # |
|
6 | # | |
7 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | from __future__ import print_function |
|
13 | from __future__ import print_function | |
14 |
|
14 | |||
15 | # Stdlib imports |
|
15 | # Stdlib imports | |
16 | import atexit |
|
16 | import atexit | |
17 | import fnmatch |
|
17 | import fnmatch | |
18 | import json |
|
18 | import json | |
19 | import os |
|
19 | import os | |
20 | import sys |
|
20 | import sys | |
21 | import threading |
|
21 | import threading | |
22 | import time |
|
22 | import time | |
23 |
|
23 | |||
24 | # Our own packages |
|
24 | # Our own packages | |
25 | import IPython.utils.io |
|
25 | import IPython.utils.io | |
26 |
|
26 | |||
27 | from IPython.testing import decorators as testdec |
|
27 | from IPython.testing import decorators as testdec | |
28 | from IPython.utils.pickleshare import PickleShareDB |
|
28 | from IPython.utils.pickleshare import PickleShareDB | |
29 | from IPython.utils.io import ask_yes_no |
|
29 | from IPython.utils.io import ask_yes_no | |
30 | from IPython.utils.warn import warn |
|
30 | from IPython.utils.warn import warn | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Classes and functions |
|
33 | # Classes and functions | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | class HistoryManager(object): |
|
36 | class HistoryManager(object): | |
37 | """A class to organize all history-related functionality in one place. |
|
37 | """A class to organize all history-related functionality in one place. | |
38 | """ |
|
38 | """ | |
39 | # Public interface |
|
39 | # Public interface | |
40 |
|
40 | |||
41 | # An instance of the IPython shell we are attached to |
|
41 | # An instance of the IPython shell we are attached to | |
42 | shell = None |
|
42 | shell = None | |
43 | # A list to hold processed history |
|
43 | # A list to hold processed history | |
44 | input_hist_parsed = None |
|
44 | input_hist_parsed = None | |
45 | # A list to hold raw history (as typed by user) |
|
45 | # A list to hold raw history (as typed by user) | |
46 | input_hist_raw = None |
|
46 | input_hist_raw = None | |
47 | # A list of directories visited during session |
|
47 | # A list of directories visited during session | |
48 | dir_hist = None |
|
48 | dir_hist = None | |
49 | # A dict of output history, keyed with ints from the shell's execution count |
|
49 | # A dict of output history, keyed with ints from the shell's execution count | |
50 | output_hist = None |
|
50 | output_hist = None | |
51 | # String with path to the history file |
|
51 | # String with path to the history file | |
52 | hist_file = None |
|
52 | hist_file = None | |
53 | # PickleShareDB instance holding the raw data for the shadow history |
|
53 | # PickleShareDB instance holding the raw data for the shadow history | |
54 | shadow_db = None |
|
54 | shadow_db = None | |
55 | # ShadowHist instance with the actual shadow history |
|
55 | # ShadowHist instance with the actual shadow history | |
56 | shadow_hist = None |
|
56 | shadow_hist = None | |
57 |
|
57 | |||
58 | # Private interface |
|
58 | # Private interface | |
59 | # Variables used to store the three last inputs from the user. On each new |
|
59 | # Variables used to store the three last inputs from the user. On each new | |
60 | # history update, we populate the user's namespace with these, shifted as |
|
60 | # history update, we populate the user's namespace with these, shifted as | |
61 | # necessary. |
|
61 | # necessary. | |
62 | _i00, _i, _ii, _iii = '','','','' |
|
62 | _i00, _i, _ii, _iii = '','','','' | |
63 |
|
63 | |||
64 | # A set with all forms of the exit command, so that we don't store them in |
|
64 | # A set with all forms of the exit command, so that we don't store them in | |
65 | # the history (it's annoying to rewind the first entry and land on an exit |
|
65 | # the history (it's annoying to rewind the first entry and land on an exit | |
66 | # call). |
|
66 | # call). | |
67 | _exit_commands = None |
|
67 | _exit_commands = None | |
68 |
|
68 | |||
69 | def __init__(self, shell): |
|
69 | def __init__(self, shell, load_history=False): | |
70 | """Create a new history manager associated with a shell instance. |
|
70 | """Create a new history manager associated with a shell instance. | |
|
71 | ||||
|
72 | If load_history is true, it will load the history from file and set the | |||
|
73 | session offset so that the next line typed can be retrieved as #1. | |||
71 | """ |
|
74 | """ | |
72 | # We need a pointer back to the shell for various tasks. |
|
75 | # We need a pointer back to the shell for various tasks. | |
73 | self.shell = shell |
|
76 | self.shell = shell | |
74 |
|
77 | |||
75 | # List of input with multi-line handling. |
|
78 | # List of input with multi-line handling. | |
76 | self.input_hist_parsed = [] |
|
79 | self.input_hist_parsed = [] | |
77 | # This one will hold the 'raw' input history, without any |
|
80 | # This one will hold the 'raw' input history, without any | |
78 | # pre-processing. This will allow users to retrieve the input just as |
|
81 | # pre-processing. This will allow users to retrieve the input just as | |
79 | # it was exactly typed in by the user, with %hist -r. |
|
82 | # it was exactly typed in by the user, with %hist -r. | |
80 | self.input_hist_raw = [] |
|
83 | self.input_hist_raw = [] | |
|
84 | ||||
|
85 | # Offset so the first line of the current session is #1 | |||
|
86 | self.session_offset = -1 | |||
81 |
|
87 | |||
82 | # list of visited directories |
|
88 | # list of visited directories | |
83 | try: |
|
89 | try: | |
84 | self.dir_hist = [os.getcwd()] |
|
90 | self.dir_hist = [os.getcwd()] | |
85 | except OSError: |
|
91 | except OSError: | |
86 | self.dir_hist = [] |
|
92 | self.dir_hist = [] | |
87 |
|
93 | |||
88 | # dict of output history |
|
94 | # dict of output history | |
89 | self.output_hist = {} |
|
95 | self.output_hist = {} | |
90 |
|
96 | |||
91 | # Now the history file |
|
97 | # Now the history file | |
92 | if shell.profile: |
|
98 | if shell.profile: | |
93 | histfname = 'history-%s' % shell.profile |
|
99 | histfname = 'history-%s' % shell.profile | |
94 | else: |
|
100 | else: | |
95 | histfname = 'history' |
|
101 | histfname = 'history' | |
96 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json') |
|
102 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json') | |
97 |
|
103 | |||
98 | # Objects related to shadow history management |
|
104 | # Objects related to shadow history management | |
99 | self._init_shadow_hist() |
|
105 | self._init_shadow_hist() | |
100 |
|
106 | |||
101 | self._i00, self._i, self._ii, self._iii = '','','','' |
|
107 | self._i00, self._i, self._ii, self._iii = '','','','' | |
102 |
|
108 | |||
103 | self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit', |
|
109 | self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit', | |
104 | '%quit', '%Exit', '%exit']) |
|
110 | '%quit', '%Exit', '%exit']) | |
105 |
|
111 | |||
106 | # Object is fully initialized, we can now call methods on it. |
|
112 | # Object is fully initialized, we can now call methods on it. | |
107 |
|
113 | |||
108 | # Fill the history zero entry, user counter starts at 1 |
|
114 | if load_history: | |
109 | self.store_inputs('\n', '\n') |
|
115 | self.reload_history() | |
|
116 | self.session_offset = len(self.input_hist_raw) -1 | |||
110 |
|
117 | |||
111 | # Create and start the autosaver. |
|
118 | # Create and start the autosaver. | |
112 | self.autosave_flag = threading.Event() |
|
119 | self.autosave_flag = threading.Event() | |
113 | self.autosave_timer = HistorySaveThread(self.autosave_flag, 60) |
|
120 | self.autosave_timer = HistorySaveThread(self.autosave_flag, 60) | |
114 | self.autosave_timer.start() |
|
121 | self.autosave_timer.start() | |
115 | # Register the autosave handler to be triggered as a post execute |
|
122 | # Register the autosave handler to be triggered as a post execute | |
116 | # callback. |
|
123 | # callback. | |
117 | self.shell.register_post_execute(self.autosave_if_due) |
|
124 | self.shell.register_post_execute(self.autosave_if_due) | |
|
125 | ||||
118 |
|
126 | |||
119 | def _init_shadow_hist(self): |
|
127 | def _init_shadow_hist(self): | |
120 | try: |
|
128 | try: | |
121 | self.shadow_db = PickleShareDB(os.path.join( |
|
129 | self.shadow_db = PickleShareDB(os.path.join( | |
122 | self.shell.ipython_dir, 'db')) |
|
130 | self.shell.ipython_dir, 'db')) | |
123 | except UnicodeDecodeError: |
|
131 | except UnicodeDecodeError: | |
124 | print("Your ipython_dir can't be decoded to unicode!") |
|
132 | print("Your ipython_dir can't be decoded to unicode!") | |
125 | print("Please set HOME environment variable to something that") |
|
133 | print("Please set HOME environment variable to something that") | |
126 | print(r"only has ASCII characters, e.g. c:\home") |
|
134 | print(r"only has ASCII characters, e.g. c:\home") | |
127 | print("Now it is", self.ipython_dir) |
|
135 | print("Now it is", self.ipython_dir) | |
128 | sys.exit() |
|
136 | sys.exit() | |
129 | self.shadow_hist = ShadowHist(self.shadow_db, self.shell) |
|
137 | self.shadow_hist = ShadowHist(self.shadow_db, self.shell) | |
130 |
|
138 | |||
131 | def populate_readline_history(self): |
|
139 | def populate_readline_history(self): | |
132 | """Populate the readline history from the raw history. |
|
140 | """Populate the readline history from the raw history. | |
133 |
|
141 | |||
134 | We only store one copy of the raw history, which is persisted to a json |
|
142 | We only store one copy of the raw history, which is persisted to a json | |
135 | file on disk. The readline history is repopulated from the contents of |
|
143 | file on disk. The readline history is repopulated from the contents of | |
136 | this file.""" |
|
144 | this file.""" | |
137 |
|
145 | |||
138 | try: |
|
146 | try: | |
139 | self.shell.readline.clear_history() |
|
147 | self.shell.readline.clear_history() | |
140 | except AttributeError: |
|
148 | except AttributeError: | |
141 | pass |
|
149 | pass | |
142 | else: |
|
150 | else: | |
143 | for h in self.input_hist_raw: |
|
151 | for h in self.input_hist_raw: | |
144 | if not h.isspace(): |
|
152 | if not h.isspace(): | |
145 | for line in h.splitlines(): |
|
153 | for line in h.splitlines(): | |
146 | self.shell.readline.add_history(line) |
|
154 | self.shell.readline.add_history(line) | |
147 |
|
155 | |||
148 | def save_history(self): |
|
156 | def save_history(self): | |
149 | """Save input history to a file (via readline library).""" |
|
157 | """Save input history to a file (via readline library).""" | |
150 | hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:], |
|
158 | hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:], | |
151 | parsed=self.input_hist_parsed) #[-self.shell.history_length:]) |
|
159 | parsed=self.input_hist_parsed) #[-self.shell.history_length:]) | |
152 | with open(self.hist_file,'wt') as hfile: |
|
160 | with open(self.hist_file,'wt') as hfile: | |
153 | json.dump(hist, hfile, |
|
161 | json.dump(hist, hfile, | |
154 | sort_keys=True, indent=4) |
|
162 | sort_keys=True, indent=4) | |
155 |
|
163 | |||
156 | def autosave_if_due(self): |
|
164 | def autosave_if_due(self): | |
157 | """Check if the autosave event is set; if so, save history. We do it |
|
165 | """Check if the autosave event is set; if so, save history. We do it | |
158 | this way so that the save takes place in the main thread.""" |
|
166 | this way so that the save takes place in the main thread.""" | |
159 | if self.autosave_flag.is_set(): |
|
167 | if self.autosave_flag.is_set(): | |
160 | self.save_history() |
|
168 | self.save_history() | |
161 | self.autosave_flag.clear() |
|
169 | self.autosave_flag.clear() | |
162 |
|
170 | |||
163 | def reload_history(self): |
|
171 | def reload_history(self): | |
164 | """Reload the input history from disk file.""" |
|
172 | """Reload the input history from disk file.""" | |
165 |
|
173 | |||
166 | with open(self.hist_file,'rt') as hfile: |
|
174 | with open(self.hist_file,'rt') as hfile: | |
167 | try: |
|
175 | try: | |
168 | hist = json.load(hfile) |
|
176 | hist = json.load(hfile) | |
169 | except ValueError: # Ignore it if JSON is corrupt. |
|
177 | except ValueError: # Ignore it if JSON is corrupt. | |
170 | return |
|
178 | return | |
171 | self.input_hist_parsed = hist['parsed'] |
|
179 | self.input_hist_parsed = hist['parsed'] | |
172 | self.input_hist_raw = hist['raw'] |
|
180 | self.input_hist_raw = hist['raw'] | |
173 | if self.shell.has_readline: |
|
181 | if self.shell.has_readline: | |
174 | self.populate_readline_history() |
|
182 | self.populate_readline_history() | |
175 |
|
183 | |||
176 | def get_history(self, index=None, raw=False, output=True): |
|
184 | def get_history(self, index=None, raw=False, output=True): | |
177 | """Get the history list. |
|
185 | """Get the history list. | |
178 |
|
186 | |||
179 | Get the input and output history. |
|
187 | Get the input and output history. | |
180 |
|
188 | |||
181 | Parameters |
|
189 | Parameters | |
182 | ---------- |
|
190 | ---------- | |
183 | index : n or (n1, n2) or None |
|
191 | index : n or (n1, n2) or None | |
184 | If n, then the last entries. If a tuple, then all in |
|
192 | If n, then the last n entries. If a tuple, then all in | |
185 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
193 | range(n1, n2). If None, then all entries. Raises IndexError if | |
186 | the format of index is incorrect. |
|
194 | the format of index is incorrect. | |
187 | raw : bool |
|
195 | raw : bool | |
188 | If True, return the raw input. |
|
196 | If True, return the raw input. | |
189 | output : bool |
|
197 | output : bool | |
190 | If True, then return the output as well. |
|
198 | If True, then return the output as well. | |
191 |
|
199 | |||
192 | Returns |
|
200 | Returns | |
193 | ------- |
|
201 | ------- | |
194 | If output is True, then return a dict of tuples, keyed by the prompt |
|
202 | If output is True, then return a dict of tuples, keyed by the prompt | |
195 | numbers and with values of (input, output). If output is False, then |
|
203 | numbers and with values of (input, output). If output is False, then | |
196 |
a dict, keyed by the prompt number with the values of input. |
|
204 | a dict, keyed by the prompt number with the values of input. | |
197 | IndexError if no history is found. |
|
|||
198 | """ |
|
205 | """ | |
199 | if raw: |
|
206 | if raw: | |
200 | input_hist = self.input_hist_raw |
|
207 | input_hist = self.input_hist_raw | |
201 | else: |
|
208 | else: | |
202 | input_hist = self.input_hist_parsed |
|
209 | input_hist = self.input_hist_parsed | |
203 | if output: |
|
210 | if output: | |
204 | output_hist = self.output_hist |
|
211 | output_hist = self.output_hist | |
|
212 | ||||
205 | n = len(input_hist) |
|
213 | n = len(input_hist) | |
|
214 | offset = self.session_offset | |||
206 | if index is None: |
|
215 | if index is None: | |
207 |
start= |
|
216 | start=offset+1; stop=n | |
208 | elif isinstance(index, int): |
|
217 | elif isinstance(index, int): | |
209 | start=n-index; stop=n |
|
218 | start=n-index; stop=n | |
210 |
elif |
|
219 | elif len(index) == 2: | |
211 |
start=index[0] |
|
220 | start = index[0] + offset | |
|
221 | stop = index[1] + offset | |||
212 | else: |
|
222 | else: | |
213 | raise IndexError('Not a valid index for the input history: %r' |
|
223 | raise IndexError('Not a valid index for the input history: %r' | |
214 | % index) |
|
224 | % index) | |
215 | hist = {} |
|
225 | hist = {} | |
216 | for i in range(start, stop): |
|
226 | for i in range(start, stop): | |
217 | if output: |
|
227 | if output: | |
218 | hist[i] = (input_hist[i], output_hist.get(i)) |
|
228 | hist[i-offset] = (input_hist[i], output_hist.get(i-offset)) | |
219 | else: |
|
229 | else: | |
220 | hist[i] = input_hist[i] |
|
230 | hist[i-offset] = input_hist[i] | |
221 | if not hist: |
|
|||
222 | raise IndexError('No history for range of indices: %r' % index) |
|
|||
223 | return hist |
|
231 | return hist | |
224 |
|
232 | |||
225 | def store_inputs(self, source, source_raw=None): |
|
233 | def store_inputs(self, source, source_raw=None): | |
226 | """Store source and raw input in history and create input cache |
|
234 | """Store source and raw input in history and create input cache | |
227 | variables _i*. |
|
235 | variables _i*. | |
228 |
|
236 | |||
229 | Parameters |
|
237 | Parameters | |
230 | ---------- |
|
238 | ---------- | |
231 | source : str |
|
239 | source : str | |
232 | Python input. |
|
240 | Python input. | |
233 |
|
241 | |||
234 | source_raw : str, optional |
|
242 | source_raw : str, optional | |
235 | If given, this is the raw input without any IPython transformations |
|
243 | If given, this is the raw input without any IPython transformations | |
236 | applied to it. If not given, ``source`` is used. |
|
244 | applied to it. If not given, ``source`` is used. | |
237 | """ |
|
245 | """ | |
238 | if source_raw is None: |
|
246 | if source_raw is None: | |
239 | source_raw = source |
|
247 | source_raw = source | |
240 |
|
248 | |||
241 | # do not store exit/quit commands |
|
249 | # do not store exit/quit commands | |
242 | if source_raw.strip() in self._exit_commands: |
|
250 | if source_raw.strip() in self._exit_commands: | |
243 | return |
|
251 | return | |
244 |
|
252 | |||
245 | self.input_hist_parsed.append(source.rstrip()) |
|
253 | self.input_hist_parsed.append(source.rstrip()) | |
246 | self.input_hist_raw.append(source_raw.rstrip()) |
|
254 | self.input_hist_raw.append(source_raw.rstrip()) | |
247 | self.shadow_hist.add(source) |
|
255 | self.shadow_hist.add(source) | |
248 |
|
256 | |||
249 | # update the auto _i variables |
|
257 | # update the auto _i variables | |
250 | self._iii = self._ii |
|
258 | self._iii = self._ii | |
251 | self._ii = self._i |
|
259 | self._ii = self._i | |
252 | self._i = self._i00 |
|
260 | self._i = self._i00 | |
253 | self._i00 = source_raw |
|
261 | self._i00 = source_raw | |
254 |
|
262 | |||
255 | # hackish access to user namespace to create _i1,_i2... dynamically |
|
263 | # hackish access to user namespace to create _i1,_i2... dynamically | |
256 | new_i = '_i%s' % self.shell.execution_count |
|
264 | new_i = '_i%s' % self.shell.execution_count | |
257 | to_main = {'_i': self._i, |
|
265 | to_main = {'_i': self._i, | |
258 | '_ii': self._ii, |
|
266 | '_ii': self._ii, | |
259 | '_iii': self._iii, |
|
267 | '_iii': self._iii, | |
260 | new_i : self._i00 } |
|
268 | new_i : self._i00 } | |
261 | self.shell.user_ns.update(to_main) |
|
269 | self.shell.user_ns.update(to_main) | |
262 |
|
270 | |||
263 | def sync_inputs(self): |
|
271 | def sync_inputs(self): | |
264 | """Ensure raw and translated histories have same length.""" |
|
272 | """Ensure raw and translated histories have same length.""" | |
265 | if len(self.input_hist_parsed) != len (self.input_hist_raw): |
|
273 | if len(self.input_hist_parsed) != len (self.input_hist_raw): | |
266 | self.input_hist_raw[:] = self.input_hist_parsed |
|
274 | self.input_hist_raw[:] = self.input_hist_parsed | |
267 |
|
275 | |||
268 | def reset(self): |
|
276 | def reset(self): | |
269 | """Clear all histories managed by this object.""" |
|
277 | """Clear all histories managed by this object.""" | |
270 | self.input_hist_parsed[:] = [] |
|
278 | self.input_hist_parsed[:] = [] | |
271 | self.input_hist_raw[:] = [] |
|
279 | self.input_hist_raw[:] = [] | |
272 | self.output_hist.clear() |
|
280 | self.output_hist.clear() | |
273 | # The directory history can't be completely empty |
|
281 | # The directory history can't be completely empty | |
274 | self.dir_hist[:] = [os.getcwd()] |
|
282 | self.dir_hist[:] = [os.getcwd()] | |
275 |
|
283 | |||
276 | class HistorySaveThread(threading.Thread): |
|
284 | class HistorySaveThread(threading.Thread): | |
277 | """This thread makes IPython save history periodically. |
|
285 | """This thread makes IPython save history periodically. | |
278 |
|
286 | |||
279 | Without this class, IPython would only save the history on a clean exit. |
|
287 | Without this class, IPython would only save the history on a clean exit. | |
280 | This saves the history periodically (the current default is once per |
|
288 | This saves the history periodically (the current default is once per | |
281 | minute), so that it is not lost in the event of a crash. |
|
289 | minute), so that it is not lost in the event of a crash. | |
282 |
|
290 | |||
283 | The implementation sets an event to indicate that history should be saved. |
|
291 | The implementation sets an event to indicate that history should be saved. | |
284 | The actual save is carried out after executing a user command, to avoid |
|
292 | The actual save is carried out after executing a user command, to avoid | |
285 | thread issues. |
|
293 | thread issues. | |
286 | """ |
|
294 | """ | |
287 | daemon = True |
|
295 | daemon = True | |
288 |
|
296 | |||
289 | def __init__(self, autosave_flag, time_interval=60): |
|
297 | def __init__(self, autosave_flag, time_interval=60): | |
290 | threading.Thread.__init__(self) |
|
298 | threading.Thread.__init__(self) | |
291 | self.time_interval = time_interval |
|
299 | self.time_interval = time_interval | |
292 | self.autosave_flag = autosave_flag |
|
300 | self.autosave_flag = autosave_flag | |
293 | self.exit_now = threading.Event() |
|
301 | self.exit_now = threading.Event() | |
294 | # Ensure the thread is stopped tidily when exiting normally |
|
302 | # Ensure the thread is stopped tidily when exiting normally | |
295 | atexit.register(self.stop) |
|
303 | atexit.register(self.stop) | |
296 |
|
304 | |||
297 | def run(self): |
|
305 | def run(self): | |
298 | while True: |
|
306 | while True: | |
299 | self.exit_now.wait(self.time_interval) |
|
307 | self.exit_now.wait(self.time_interval) | |
300 | if self.exit_now.is_set(): |
|
308 | if self.exit_now.is_set(): | |
301 | break |
|
309 | break | |
302 | self.autosave_flag.set() |
|
310 | self.autosave_flag.set() | |
303 |
|
311 | |||
304 | def stop(self): |
|
312 | def stop(self): | |
305 | """Safely and quickly stop the autosave timer thread.""" |
|
313 | """Safely and quickly stop the autosave timer thread.""" | |
306 | self.exit_now.set() |
|
314 | self.exit_now.set() | |
307 | self.join() |
|
315 | self.join() | |
308 |
|
316 | |||
309 | @testdec.skip_doctest |
|
317 | @testdec.skip_doctest | |
310 | def magic_history(self, parameter_s = ''): |
|
318 | def magic_history(self, parameter_s = ''): | |
311 | """Print input history (_i<n> variables), with most recent last. |
|
319 | """Print input history (_i<n> variables), with most recent last. | |
312 |
|
320 | |||
313 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
321 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
314 | %history n -> print at most n inputs\\ |
|
322 | %history n -> print at most n inputs\\ | |
315 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
323 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
316 |
|
324 | |||
317 | By default, input history is printed without line numbers so it can be |
|
325 | By default, input history is printed without line numbers so it can be | |
318 | directly pasted into an editor. |
|
326 | directly pasted into an editor. | |
319 |
|
327 | |||
320 | With -n, each input's number <n> is shown, and is accessible as the |
|
328 | With -n, each input's number <n> is shown, and is accessible as the | |
321 | automatically generated variable _i<n> as well as In[<n>]. Multi-line |
|
329 | automatically generated variable _i<n> as well as In[<n>]. Multi-line | |
322 | statements are printed starting at a new line for easy copy/paste. |
|
330 | statements are printed starting at a new line for easy copy/paste. | |
323 |
|
331 | |||
324 | Options: |
|
332 | Options: | |
325 |
|
333 | |||
326 | -n: print line numbers for each input. |
|
334 | -n: print line numbers for each input. | |
327 | This feature is only available if numbered prompts are in use. |
|
335 | This feature is only available if numbered prompts are in use. | |
328 |
|
336 | |||
329 | -o: also print outputs for each input. |
|
337 | -o: also print outputs for each input. | |
330 |
|
338 | |||
331 | -p: print classic '>>>' python prompts before each input. This is useful |
|
339 | -p: print classic '>>>' python prompts before each input. This is useful | |
332 | for making documentation, and in conjunction with -o, for producing |
|
340 | for making documentation, and in conjunction with -o, for producing | |
333 | doctest-ready output. |
|
341 | doctest-ready output. | |
334 |
|
342 | |||
335 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. |
|
343 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. | |
336 |
|
344 | |||
337 | -t: print the 'translated' history, as IPython understands it. IPython |
|
345 | -t: print the 'translated' history, as IPython understands it. IPython | |
338 | filters your input and converts it all into valid Python source before |
|
346 | filters your input and converts it all into valid Python source before | |
339 | executing it (things like magics or aliases are turned into function |
|
347 | executing it (things like magics or aliases are turned into function | |
340 | calls, for example). With this option, you'll see the native history |
|
348 | calls, for example). With this option, you'll see the native history | |
341 | instead of the user-entered version: '%cd /' will be seen as |
|
349 | instead of the user-entered version: '%cd /' will be seen as | |
342 | 'get_ipython().magic("%cd /")' instead of '%cd /'. |
|
350 | 'get_ipython().magic("%cd /")' instead of '%cd /'. | |
343 |
|
351 | |||
344 | -g: treat the arg as a pattern to grep for in (full) history. |
|
352 | -g: treat the arg as a pattern to grep for in (full) history. | |
345 | This includes the "shadow history" (almost all commands ever written). |
|
353 | This includes the "shadow history" (almost all commands ever written). | |
346 | Use '%hist -g' to show full shadow history (may be very long). |
|
354 | Use '%hist -g' to show full shadow history (may be very long). | |
347 | In shadow history, every index nuwber starts with 0. |
|
355 | In shadow history, every index nuwber starts with 0. | |
348 |
|
356 | |||
349 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
357 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
350 | the given file. The file is always overwritten, though IPython asks for |
|
358 | the given file. The file is always overwritten, though IPython asks for | |
351 | confirmation first if it already exists. |
|
359 | confirmation first if it already exists. | |
352 |
|
360 | |||
353 | Examples |
|
361 | Examples | |
354 | -------- |
|
362 | -------- | |
355 | :: |
|
363 | :: | |
356 |
|
364 | |||
357 | In [6]: %hist -n 4 6 |
|
365 | In [6]: %hist -n 4 6 | |
358 | 4:a = 12 |
|
366 | 4:a = 12 | |
359 | 5:print a**2 |
|
367 | 5:print a**2 | |
360 |
|
368 | |||
361 | """ |
|
369 | """ | |
362 |
|
370 | |||
363 | if not self.shell.displayhook.do_full_cache: |
|
371 | if not self.shell.displayhook.do_full_cache: | |
364 | print('This feature is only available if numbered prompts are in use.') |
|
372 | print('This feature is only available if numbered prompts are in use.') | |
365 | return |
|
373 | return | |
366 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') |
|
374 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') | |
|
375 | ||||
|
376 | # For brevity | |||
|
377 | history_manager = self.shell.history_manager | |||
367 |
|
378 | |||
368 | # Check if output to specific file was requested. |
|
379 | # Check if output to specific file was requested. | |
369 | try: |
|
380 | try: | |
370 | outfname = opts['f'] |
|
381 | outfname = opts['f'] | |
371 | except KeyError: |
|
382 | except KeyError: | |
372 | outfile = IPython.utils.io.Term.cout # default |
|
383 | outfile = IPython.utils.io.Term.cout # default | |
373 | # We don't want to close stdout at the end! |
|
384 | # We don't want to close stdout at the end! | |
374 | close_at_end = False |
|
385 | close_at_end = False | |
375 | else: |
|
386 | else: | |
376 | if os.path.exists(outfname): |
|
387 | if os.path.exists(outfname): | |
377 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
388 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
378 | print('Aborting.') |
|
389 | print('Aborting.') | |
379 | return |
|
390 | return | |
380 |
|
391 | |||
381 | outfile = open(outfname,'w') |
|
392 | outfile = open(outfname,'w') | |
382 | close_at_end = True |
|
393 | close_at_end = True | |
383 |
|
394 | |||
384 |
|
|
395 | print_nums = 'n' in opts | |
385 | input_hist = self.shell.history_manager.input_hist_parsed |
|
396 | print_outputs = 'o' in opts | |
386 |
|
|
397 | pyprompts = 'p' in opts | |
387 | input_hist = self.shell.history_manager.input_hist_raw |
|
398 | # Raw history is the default | |
388 | else: |
|
399 | raw = not('t' in opts) | |
389 | # Raw history is the default |
|
|||
390 | input_hist = self.shell.history_manager.input_hist_raw |
|
|||
391 |
|
400 | |||
392 | default_length = 40 |
|
401 | default_length = 40 | |
393 | pattern = None |
|
402 | pattern = None | |
394 | if 'g' in opts: |
|
403 | if 'g' in opts: | |
395 |
in |
|
404 | index = None | |
396 | final = len(input_hist) |
|
|||
397 | parts = parameter_s.split(None, 1) |
|
405 | parts = parameter_s.split(None, 1) | |
398 | if len(parts) == 1: |
|
406 | if len(parts) == 1: | |
399 | parts += '*' |
|
407 | parts += '*' | |
400 | head, pattern = parts |
|
408 | head, pattern = parts | |
401 | pattern = "*" + pattern + "*" |
|
409 | pattern = "*" + pattern + "*" | |
402 | elif len(args) == 0: |
|
410 | elif len(args) == 0: | |
403 | final = len(input_hist)-1 |
|
411 | index = None | |
404 | init = max(1,final-default_length) |
|
|||
405 | elif len(args) == 1: |
|
412 | elif len(args) == 1: | |
406 |
|
|
413 | index = int(args[0]) | |
407 | init = max(1, final-int(args[0])) |
|
|||
408 | elif len(args) == 2: |
|
414 | elif len(args) == 2: | |
409 |
in |
|
415 | index = map(int, args) | |
410 | else: |
|
416 | else: | |
411 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
417 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
412 | print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout) |
|
418 | print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout) | |
413 | return |
|
419 | return | |
|
420 | ||||
|
421 | hist = history_manager.get_history(index, raw, print_outputs) | |||
414 |
|
422 | |||
415 |
width = len(str( |
|
423 | width = len(str(max(hist.iterkeys()))) | |
416 | line_sep = ['','\n'] |
|
424 | line_sep = ['','\n'] | |
417 | print_nums = 'n' in opts |
|
|||
418 | print_outputs = 'o' in opts |
|
|||
419 | pyprompts = 'p' in opts |
|
|||
420 |
|
425 | |||
421 | found = False |
|
426 | found = False | |
422 | if pattern is not None: |
|
427 | if pattern is not None: | |
423 |
sh = |
|
428 | sh = history_manager.shadow_hist.all() | |
424 | for idx, s in sh: |
|
429 | for idx, s in sh: | |
425 | if fnmatch.fnmatch(s, pattern): |
|
430 | if fnmatch.fnmatch(s, pattern): | |
426 | print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile) |
|
431 | print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile) | |
427 | found = True |
|
432 | found = True | |
428 |
|
433 | |||
429 | if found: |
|
434 | if found: | |
430 | print("===", file=outfile) |
|
435 | print("===", file=outfile) | |
431 | print("shadow history ends, fetch by %rep <number> (must start with 0)", |
|
436 | print("shadow history ends, fetch by %rep <number> (must start with 0)", | |
432 | file=outfile) |
|
437 | file=outfile) | |
433 | print("=== start of normal history ===", file=outfile) |
|
438 | print("=== start of normal history ===", file=outfile) | |
434 |
|
439 | |||
435 |
for in_num in |
|
440 | for in_num, inline in sorted(hist.iteritems()): | |
436 | # Print user history with tabs expanded to 4 spaces. The GUI clients |
|
441 | # Print user history with tabs expanded to 4 spaces. The GUI clients | |
437 | # use hard tabs for easier usability in auto-indented code, but we want |
|
442 | # use hard tabs for easier usability in auto-indented code, but we want | |
438 | # to produce PEP-8 compliant history for safe pasting into an editor. |
|
443 | # to produce PEP-8 compliant history for safe pasting into an editor. | |
439 | inline = input_hist[in_num].expandtabs(4).rstrip()+'\n' |
|
444 | if print_outputs: | |
|
445 | inline, output = inline | |||
|
446 | inline = inline.expandtabs(4).rstrip() | |||
440 |
|
447 | |||
441 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): |
|
448 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): | |
442 | continue |
|
449 | continue | |
443 |
|
450 | |||
444 |
multiline = |
|
451 | multiline = "\n" in inline | |
445 | if print_nums: |
|
452 | if print_nums: | |
446 | print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), |
|
453 | print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), | |
447 | file=outfile) |
|
454 | file=outfile, end='') | |
448 | if pyprompts: |
|
455 | if pyprompts: | |
449 | print('>>>', file=outfile) |
|
456 | inline = ">>> " + inline | |
450 | if multiline: |
|
457 | if multiline: | |
451 | lines = inline.splitlines() |
|
458 | lines = inline.splitlines() | |
452 | print('\n... '.join(lines), file=outfile) |
|
459 | print('\n... '.join(lines), file=outfile) | |
453 | print('... ', file=outfile) |
|
460 | print('... ', file=outfile) | |
454 | else: |
|
461 | else: | |
455 |
print(inline, |
|
462 | print(inline, file=outfile) | |
456 | else: |
|
463 | else: | |
457 |
print(inline, |
|
464 | print(inline, file=outfile) | |
458 | if print_outputs: |
|
465 | if print_outputs and output: | |
459 | output = self.shell.history_manager.output_hist.get(in_num) |
|
466 | print(repr(output), file=outfile) | |
460 | if output is not None: |
|
|||
461 | print(repr(output), file=outfile) |
|
|||
462 |
|
467 | |||
463 | if close_at_end: |
|
468 | if close_at_end: | |
464 | outfile.close() |
|
469 | outfile.close() | |
465 |
|
470 | |||
466 |
|
471 | # %hist is an alternative name | ||
467 | def magic_hist(self, parameter_s=''): |
|
472 | magic_hist = magic_history | |
468 | """Alternate name for %history.""" |
|
|||
469 | return self.magic_history(parameter_s) |
|
|||
470 |
|
473 | |||
471 |
|
474 | |||
472 | def rep_f(self, arg): |
|
475 | def rep_f(self, arg): | |
473 | r""" Repeat a command, or get command to input line for editing |
|
476 | r""" Repeat a command, or get command to input line for editing | |
474 |
|
477 | |||
475 | - %rep (no arguments): |
|
478 | - %rep (no arguments): | |
476 |
|
479 | |||
477 | Place a string version of last computation result (stored in the special '_' |
|
480 | Place a string version of last computation result (stored in the special '_' | |
478 | variable) to the next input prompt. Allows you to create elaborate command |
|
481 | variable) to the next input prompt. Allows you to create elaborate command | |
479 | lines without using copy-paste:: |
|
482 | lines without using copy-paste:: | |
480 |
|
483 | |||
481 | $ l = ["hei", "vaan"] |
|
484 | $ l = ["hei", "vaan"] | |
482 | $ "".join(l) |
|
485 | $ "".join(l) | |
483 | ==> heivaan |
|
486 | ==> heivaan | |
484 | $ %rep |
|
487 | $ %rep | |
485 | $ heivaan_ <== cursor blinking |
|
488 | $ heivaan_ <== cursor blinking | |
486 |
|
489 | |||
487 | %rep 45 |
|
490 | %rep 45 | |
488 |
|
491 | |||
489 | Place history line 45 to next input prompt. Use %hist to find out the |
|
492 | Place history line 45 to next input prompt. Use %hist to find out the | |
490 | number. |
|
493 | number. | |
491 |
|
494 | |||
492 | %rep 1-4 6-7 3 |
|
495 | %rep 1-4 6-7 3 | |
493 |
|
496 | |||
494 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
497 | Repeat the specified lines immediately. Input slice syntax is the same as | |
495 | in %macro and %save. |
|
498 | in %macro and %save. | |
496 |
|
499 | |||
497 | %rep foo |
|
500 | %rep foo | |
498 |
|
501 | |||
499 | Place the most recent line that has the substring "foo" to next input. |
|
502 | Place the most recent line that has the substring "foo" to next input. | |
500 | (e.g. 'svn ci -m foobar'). |
|
503 | (e.g. 'svn ci -m foobar'). | |
501 | """ |
|
504 | """ | |
502 |
|
505 | |||
503 | opts,args = self.parse_options(arg,'',mode='list') |
|
506 | opts,args = self.parse_options(arg,'',mode='list') | |
504 | if not args: |
|
507 | if not args: | |
505 | self.set_next_input(str(self.shell.user_ns["_"])) |
|
508 | self.set_next_input(str(self.shell.user_ns["_"])) | |
506 | return |
|
509 | return | |
507 |
|
510 | |||
508 | if len(args) == 1 and not '-' in args[0]: |
|
511 | if len(args) == 1 and not '-' in args[0]: | |
509 | arg = args[0] |
|
512 | arg = args[0] | |
510 | if len(arg) > 1 and arg.startswith('0'): |
|
513 | if len(arg) > 1 and arg.startswith('0'): | |
511 | # get from shadow hist |
|
514 | # get from shadow hist | |
512 | num = int(arg[1:]) |
|
515 | num = int(arg[1:]) | |
513 | line = self.shell.shadowhist.get(num) |
|
516 | line = self.shell.shadowhist.get(num) | |
514 | self.set_next_input(str(line)) |
|
517 | self.set_next_input(str(line)) | |
515 | return |
|
518 | return | |
516 | try: |
|
519 | try: | |
517 | num = int(args[0]) |
|
520 | num = int(args[0]) | |
518 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) |
|
521 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) | |
519 | return |
|
522 | return | |
520 | except ValueError: |
|
523 | except ValueError: | |
521 | pass |
|
524 | pass | |
522 |
|
525 | |||
523 | for h in reversed(self.shell.input_hist_raw): |
|
526 | for h in reversed(self.shell.input_hist_raw): | |
524 | if 'rep' in h: |
|
527 | if 'rep' in h: | |
525 | continue |
|
528 | continue | |
526 | if fnmatch.fnmatch(h,'*' + arg + '*'): |
|
529 | if fnmatch.fnmatch(h,'*' + arg + '*'): | |
527 | self.set_next_input(str(h).rstrip()) |
|
530 | self.set_next_input(str(h).rstrip()) | |
528 | return |
|
531 | return | |
529 |
|
532 | |||
530 | try: |
|
533 | try: | |
531 | lines = self.extract_input_slices(args, True) |
|
534 | lines = self.extract_input_slices(args, True) | |
532 | print("lines", lines) |
|
535 | print("lines", lines) | |
533 | self.run_cell(lines) |
|
536 | self.run_cell(lines) | |
534 | except ValueError: |
|
537 | except ValueError: | |
535 | print("Not found in recent history:", args) |
|
538 | print("Not found in recent history:", args) | |
536 |
|
539 | |||
537 |
|
540 | |||
538 | _sentinel = object() |
|
541 | _sentinel = object() | |
539 |
|
542 | |||
540 | class ShadowHist(object): |
|
543 | class ShadowHist(object): | |
541 | def __init__(self, db, shell): |
|
544 | def __init__(self, db, shell): | |
542 | # cmd => idx mapping |
|
545 | # cmd => idx mapping | |
543 | self.curidx = 0 |
|
546 | self.curidx = 0 | |
544 | self.db = db |
|
547 | self.db = db | |
545 | self.disabled = False |
|
548 | self.disabled = False | |
546 | self.shell = shell |
|
549 | self.shell = shell | |
547 |
|
550 | |||
548 | def inc_idx(self): |
|
551 | def inc_idx(self): | |
549 | idx = self.db.get('shadowhist_idx', 1) |
|
552 | idx = self.db.get('shadowhist_idx', 1) | |
550 | self.db['shadowhist_idx'] = idx + 1 |
|
553 | self.db['shadowhist_idx'] = idx + 1 | |
551 | return idx |
|
554 | return idx | |
552 |
|
555 | |||
553 | def add(self, ent): |
|
556 | def add(self, ent): | |
554 | if self.disabled: |
|
557 | if self.disabled: | |
555 | return |
|
558 | return | |
556 | try: |
|
559 | try: | |
557 | old = self.db.hget('shadowhist', ent, _sentinel) |
|
560 | old = self.db.hget('shadowhist', ent, _sentinel) | |
558 | if old is not _sentinel: |
|
561 | if old is not _sentinel: | |
559 | return |
|
562 | return | |
560 | newidx = self.inc_idx() |
|
563 | newidx = self.inc_idx() | |
561 | #print("new", newidx) # dbg |
|
564 | #print("new", newidx) # dbg | |
562 | self.db.hset('shadowhist',ent, newidx) |
|
565 | self.db.hset('shadowhist',ent, newidx) | |
563 | except: |
|
566 | except: | |
564 | self.shell.showtraceback() |
|
567 | self.shell.showtraceback() | |
565 | print("WARNING: disabling shadow history") |
|
568 | print("WARNING: disabling shadow history") | |
566 | self.disabled = True |
|
569 | self.disabled = True | |
567 |
|
570 | |||
568 | def all(self): |
|
571 | def all(self): | |
569 | d = self.db.hdict('shadowhist') |
|
572 | d = self.db.hdict('shadowhist') | |
570 | items = [(i,s) for (s,i) in d.iteritems()] |
|
573 | items = [(i,s) for (s,i) in d.iteritems()] | |
571 | items.sort() |
|
574 | items.sort() | |
572 | return items |
|
575 | return items | |
573 |
|
576 | |||
574 | def get(self, idx): |
|
577 | def get(self, idx): | |
575 | all = self.all() |
|
578 | all = self.all() | |
576 |
|
579 | |||
577 | for k, v in all: |
|
580 | for k, v in all: | |
578 | if k == idx: |
|
581 | if k == idx: | |
579 | return v |
|
582 | return v | |
580 |
|
583 | |||
581 |
|
584 | |||
582 | def init_ipython(ip): |
|
585 | def init_ipython(ip): | |
583 | ip.define_magic("rep",rep_f) |
|
586 | ip.define_magic("rep",rep_f) | |
584 | ip.define_magic("hist",magic_hist) |
|
587 | ip.define_magic("hist",magic_hist) | |
585 | ip.define_magic("history",magic_history) |
|
588 | ip.define_magic("history",magic_history) | |
586 |
|
589 | |||
587 | # XXX - ipy_completers are in quarantine, need to be updated to new apis |
|
590 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | |
588 | #import ipy_completers |
|
591 | #import ipy_completers | |
589 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
592 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,2558 +1,2555 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 atexit |
|
23 | import atexit | |
24 | import codeop |
|
24 | import codeop | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
27 | import sys |
|
27 | import sys | |
28 | import tempfile |
|
28 | import tempfile | |
29 | import types |
|
29 | import types | |
30 | from contextlib import nested |
|
30 | from contextlib import nested | |
31 |
|
31 | |||
32 | from IPython.config.configurable import Configurable |
|
32 | from IPython.config.configurable import Configurable | |
33 | from IPython.core import debugger, oinspect |
|
33 | from IPython.core import debugger, oinspect | |
34 | from IPython.core import history as ipcorehist |
|
34 | from IPython.core import history as ipcorehist | |
35 | from IPython.core import page |
|
35 | from IPython.core import page | |
36 | from IPython.core import prefilter |
|
36 | from IPython.core import prefilter | |
37 | from IPython.core import shadowns |
|
37 | from IPython.core import shadowns | |
38 | from IPython.core import ultratb |
|
38 | from IPython.core import ultratb | |
39 | from IPython.core.alias import AliasManager |
|
39 | from IPython.core.alias import AliasManager | |
40 | from IPython.core.builtin_trap import BuiltinTrap |
|
40 | from IPython.core.builtin_trap import BuiltinTrap | |
41 | from IPython.core.compilerop import CachingCompiler |
|
41 | from IPython.core.compilerop import CachingCompiler | |
42 | from IPython.core.display_trap import DisplayTrap |
|
42 | from IPython.core.display_trap import DisplayTrap | |
43 | from IPython.core.displayhook import DisplayHook |
|
43 | from IPython.core.displayhook import DisplayHook | |
44 | from IPython.core.displaypub import DisplayPublisher |
|
44 | from IPython.core.displaypub import DisplayPublisher | |
45 | from IPython.core.error import TryNext, UsageError |
|
45 | from IPython.core.error import TryNext, UsageError | |
46 | from IPython.core.extensions import ExtensionManager |
|
46 | from IPython.core.extensions import ExtensionManager | |
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
48 | from IPython.core.formatters import DisplayFormatter |
|
48 | from IPython.core.formatters import DisplayFormatter | |
49 | from IPython.core.history import HistoryManager |
|
49 | from IPython.core.history import HistoryManager | |
50 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
50 | from IPython.core.inputsplitter import IPythonInputSplitter | |
51 | from IPython.core.logger import Logger |
|
51 | from IPython.core.logger import Logger | |
52 | from IPython.core.magic import Magic |
|
52 | from IPython.core.magic import Magic | |
53 | from IPython.core.payload import PayloadManager |
|
53 | from IPython.core.payload import PayloadManager | |
54 | from IPython.core.plugin import PluginManager |
|
54 | from IPython.core.plugin import PluginManager | |
55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
55 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
56 | from IPython.external.Itpl import ItplNS |
|
56 | from IPython.external.Itpl import ItplNS | |
57 | from IPython.utils import PyColorize |
|
57 | from IPython.utils import PyColorize | |
58 | from IPython.utils import io |
|
58 | from IPython.utils import io | |
59 | from IPython.utils import pickleshare |
|
59 | from IPython.utils import pickleshare | |
60 | from IPython.utils.doctestreload import doctest_reload |
|
60 | from IPython.utils.doctestreload import doctest_reload | |
61 | from IPython.utils.io import ask_yes_no, rprint |
|
61 | from IPython.utils.io import ask_yes_no, rprint | |
62 | from IPython.utils.ipstruct import Struct |
|
62 | from IPython.utils.ipstruct import Struct | |
63 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
63 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
64 | from IPython.utils.process import system, getoutput |
|
64 | from IPython.utils.process import system, getoutput | |
65 | from IPython.utils.strdispatch import StrDispatch |
|
65 | from IPython.utils.strdispatch import StrDispatch | |
66 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
66 | from IPython.utils.syspathcontext import prepended_to_syspath | |
67 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
67 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
68 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
69 | List, Unicode, Instance, Type) |
|
69 | List, Unicode, Instance, Type) | |
70 | from IPython.utils.warn import warn, error, fatal |
|
70 | from IPython.utils.warn import warn, error, fatal | |
71 | import IPython.core.hooks |
|
71 | import IPython.core.hooks | |
72 |
|
72 | |||
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 | # Globals |
|
74 | # Globals | |
75 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
76 |
|
76 | |||
77 | # compiled regexps for autoindent management |
|
77 | # compiled regexps for autoindent management | |
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
78 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
79 |
|
79 | |||
80 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
81 | # Utilities |
|
81 | # Utilities | |
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 |
|
83 | |||
84 | # store the builtin raw_input globally, and use this always, in case user code |
|
84 | # store the builtin raw_input globally, and use this always, in case user code | |
85 | # overwrites it (like wx.py.PyShell does) |
|
85 | # overwrites it (like wx.py.PyShell does) | |
86 | raw_input_original = raw_input |
|
86 | raw_input_original = raw_input | |
87 |
|
87 | |||
88 | def softspace(file, newvalue): |
|
88 | def softspace(file, newvalue): | |
89 | """Copied from code.py, to remove the dependency""" |
|
89 | """Copied from code.py, to remove the dependency""" | |
90 |
|
90 | |||
91 | oldvalue = 0 |
|
91 | oldvalue = 0 | |
92 | try: |
|
92 | try: | |
93 | oldvalue = file.softspace |
|
93 | oldvalue = file.softspace | |
94 | except AttributeError: |
|
94 | except AttributeError: | |
95 | pass |
|
95 | pass | |
96 | try: |
|
96 | try: | |
97 | file.softspace = newvalue |
|
97 | file.softspace = newvalue | |
98 | except (AttributeError, TypeError): |
|
98 | except (AttributeError, TypeError): | |
99 | # "attribute-less object" or "read-only attributes" |
|
99 | # "attribute-less object" or "read-only attributes" | |
100 | pass |
|
100 | pass | |
101 | return oldvalue |
|
101 | return oldvalue | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | def no_op(*a, **kw): pass |
|
104 | def no_op(*a, **kw): pass | |
105 |
|
105 | |||
106 | class SpaceInInput(Exception): pass |
|
106 | class SpaceInInput(Exception): pass | |
107 |
|
107 | |||
108 | class Bunch: pass |
|
108 | class Bunch: pass | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | def get_default_colors(): |
|
111 | def get_default_colors(): | |
112 | if sys.platform=='darwin': |
|
112 | if sys.platform=='darwin': | |
113 | return "LightBG" |
|
113 | return "LightBG" | |
114 | elif os.name=='nt': |
|
114 | elif os.name=='nt': | |
115 | return 'Linux' |
|
115 | return 'Linux' | |
116 | else: |
|
116 | else: | |
117 | return 'Linux' |
|
117 | return 'Linux' | |
118 |
|
118 | |||
119 |
|
119 | |||
120 | class SeparateStr(Str): |
|
120 | class SeparateStr(Str): | |
121 | """A Str subclass to validate separate_in, separate_out, etc. |
|
121 | """A Str subclass to validate separate_in, separate_out, etc. | |
122 |
|
122 | |||
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
123 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
124 | """ |
|
124 | """ | |
125 |
|
125 | |||
126 | def validate(self, obj, value): |
|
126 | def validate(self, obj, value): | |
127 | if value == '0': value = '' |
|
127 | if value == '0': value = '' | |
128 | value = value.replace('\\n','\n') |
|
128 | value = value.replace('\\n','\n') | |
129 | return super(SeparateStr, self).validate(obj, value) |
|
129 | return super(SeparateStr, self).validate(obj, value) | |
130 |
|
130 | |||
131 | class MultipleInstanceError(Exception): |
|
131 | class MultipleInstanceError(Exception): | |
132 | pass |
|
132 | pass | |
133 |
|
133 | |||
134 |
|
134 | |||
135 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
136 | # Main IPython class |
|
136 | # Main IPython class | |
137 | #----------------------------------------------------------------------------- |
|
137 | #----------------------------------------------------------------------------- | |
138 |
|
138 | |||
139 | class InteractiveShell(Configurable, Magic): |
|
139 | class InteractiveShell(Configurable, Magic): | |
140 | """An enhanced, interactive shell for Python.""" |
|
140 | """An enhanced, interactive shell for Python.""" | |
141 |
|
141 | |||
142 | _instance = None |
|
142 | _instance = None | |
143 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
143 | autocall = Enum((0,1,2), default_value=1, config=True) | |
144 | # TODO: remove all autoindent logic and put into frontends. |
|
144 | # TODO: remove all autoindent logic and put into frontends. | |
145 | # We can't do this yet because even runlines uses the autoindent. |
|
145 | # We can't do this yet because even runlines uses the autoindent. | |
146 | autoindent = CBool(True, config=True) |
|
146 | autoindent = CBool(True, config=True) | |
147 | automagic = CBool(True, config=True) |
|
147 | automagic = CBool(True, config=True) | |
148 | cache_size = Int(1000, config=True) |
|
148 | cache_size = Int(1000, config=True) | |
149 | color_info = CBool(True, config=True) |
|
149 | color_info = CBool(True, config=True) | |
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
151 | default_value=get_default_colors(), config=True) |
|
151 | default_value=get_default_colors(), config=True) | |
152 | debug = CBool(False, config=True) |
|
152 | debug = CBool(False, config=True) | |
153 | deep_reload = CBool(False, config=True) |
|
153 | deep_reload = CBool(False, config=True) | |
154 | display_formatter = Instance(DisplayFormatter) |
|
154 | display_formatter = Instance(DisplayFormatter) | |
155 | displayhook_class = Type(DisplayHook) |
|
155 | displayhook_class = Type(DisplayHook) | |
156 | display_pub_class = Type(DisplayPublisher) |
|
156 | display_pub_class = Type(DisplayPublisher) | |
157 |
|
157 | |||
158 | exit_now = CBool(False) |
|
158 | exit_now = CBool(False) | |
159 | # Monotonically increasing execution counter |
|
159 | # Monotonically increasing execution counter | |
160 | execution_count = Int(1) |
|
160 | execution_count = Int(1) | |
161 | filename = Str("<ipython console>") |
|
161 | filename = Str("<ipython console>") | |
162 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
162 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
163 |
|
163 | |||
164 | # Input splitter, to split entire cells of input into either individual |
|
164 | # Input splitter, to split entire cells of input into either individual | |
165 | # interactive statements or whole blocks. |
|
165 | # interactive statements or whole blocks. | |
166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
166 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
167 | (), {}) |
|
167 | (), {}) | |
168 | logstart = CBool(False, config=True) |
|
168 | logstart = CBool(False, config=True) | |
169 | logfile = Str('', config=True) |
|
169 | logfile = Str('', config=True) | |
170 | logappend = Str('', config=True) |
|
170 | logappend = Str('', config=True) | |
171 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
171 | object_info_string_level = Enum((0,1,2), default_value=0, | |
172 | config=True) |
|
172 | config=True) | |
173 | pdb = CBool(False, config=True) |
|
173 | pdb = CBool(False, config=True) | |
174 |
|
174 | |||
175 | profile = Str('', config=True) |
|
175 | profile = Str('', config=True) | |
176 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
176 | prompt_in1 = Str('In [\\#]: ', config=True) | |
177 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
177 | prompt_in2 = Str(' .\\D.: ', config=True) | |
178 | prompt_out = Str('Out[\\#]: ', config=True) |
|
178 | prompt_out = Str('Out[\\#]: ', config=True) | |
179 | prompts_pad_left = CBool(True, config=True) |
|
179 | prompts_pad_left = CBool(True, config=True) | |
180 | quiet = CBool(False, config=True) |
|
180 | quiet = CBool(False, config=True) | |
181 |
|
181 | |||
182 | history_length = Int(10000, config=True) |
|
182 | history_length = Int(10000, config=True) | |
183 |
|
183 | |||
184 | # The readline stuff will eventually be moved to the terminal subclass |
|
184 | # The readline stuff will eventually be moved to the terminal subclass | |
185 | # but for now, we can't do that as readline is welded in everywhere. |
|
185 | # but for now, we can't do that as readline is welded in everywhere. | |
186 | readline_use = CBool(True, config=True) |
|
186 | readline_use = CBool(True, config=True) | |
187 | readline_merge_completions = CBool(True, config=True) |
|
187 | readline_merge_completions = CBool(True, config=True) | |
188 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
188 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) | |
189 | readline_remove_delims = Str('-/~', config=True) |
|
189 | readline_remove_delims = Str('-/~', config=True) | |
190 | readline_parse_and_bind = List([ |
|
190 | readline_parse_and_bind = List([ | |
191 | 'tab: complete', |
|
191 | 'tab: complete', | |
192 | '"\C-l": clear-screen', |
|
192 | '"\C-l": clear-screen', | |
193 | 'set show-all-if-ambiguous on', |
|
193 | 'set show-all-if-ambiguous on', | |
194 | '"\C-o": tab-insert', |
|
194 | '"\C-o": tab-insert', | |
195 | '"\M-i": " "', |
|
195 | '"\M-i": " "', | |
196 | '"\M-o": "\d\d\d\d"', |
|
196 | '"\M-o": "\d\d\d\d"', | |
197 | '"\M-I": "\d\d\d\d"', |
|
197 | '"\M-I": "\d\d\d\d"', | |
198 | '"\C-r": reverse-search-history', |
|
198 | '"\C-r": reverse-search-history', | |
199 | '"\C-s": forward-search-history', |
|
199 | '"\C-s": forward-search-history', | |
200 | '"\C-p": history-search-backward', |
|
200 | '"\C-p": history-search-backward', | |
201 | '"\C-n": history-search-forward', |
|
201 | '"\C-n": history-search-forward', | |
202 | '"\e[A": history-search-backward', |
|
202 | '"\e[A": history-search-backward', | |
203 | '"\e[B": history-search-forward', |
|
203 | '"\e[B": history-search-forward', | |
204 | '"\C-k": kill-line', |
|
204 | '"\C-k": kill-line', | |
205 | '"\C-u": unix-line-discard', |
|
205 | '"\C-u": unix-line-discard', | |
206 | ], allow_none=False, config=True) |
|
206 | ], allow_none=False, config=True) | |
207 |
|
207 | |||
208 | # TODO: this part of prompt management should be moved to the frontends. |
|
208 | # TODO: this part of prompt management should be moved to the frontends. | |
209 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
209 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
210 | separate_in = SeparateStr('\n', config=True) |
|
210 | separate_in = SeparateStr('\n', config=True) | |
211 | separate_out = SeparateStr('', config=True) |
|
211 | separate_out = SeparateStr('', config=True) | |
212 | separate_out2 = SeparateStr('', config=True) |
|
212 | separate_out2 = SeparateStr('', config=True) | |
213 | wildcards_case_sensitive = CBool(True, config=True) |
|
213 | wildcards_case_sensitive = CBool(True, config=True) | |
214 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
214 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
215 | default_value='Context', config=True) |
|
215 | default_value='Context', config=True) | |
216 |
|
216 | |||
217 | # Subcomponents of InteractiveShell |
|
217 | # Subcomponents of InteractiveShell | |
218 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
218 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
219 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
219 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
220 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
220 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
221 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
221 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
222 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
222 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
223 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
223 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
224 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
224 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
225 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
225 | history_manager = Instance('IPython.core.history.HistoryManager') | |
226 |
|
226 | |||
227 | # Private interface |
|
227 | # Private interface | |
228 | _post_execute = set() |
|
228 | _post_execute = set() | |
229 |
|
229 | |||
230 | def __init__(self, config=None, ipython_dir=None, |
|
230 | def __init__(self, config=None, ipython_dir=None, | |
231 | user_ns=None, user_global_ns=None, |
|
231 | user_ns=None, user_global_ns=None, | |
232 | custom_exceptions=((), None)): |
|
232 | custom_exceptions=((), None)): | |
233 |
|
233 | |||
234 | # This is where traits with a config_key argument are updated |
|
234 | # This is where traits with a config_key argument are updated | |
235 | # from the values on config. |
|
235 | # from the values on config. | |
236 | super(InteractiveShell, self).__init__(config=config) |
|
236 | super(InteractiveShell, self).__init__(config=config) | |
237 |
|
237 | |||
238 | # These are relatively independent and stateless |
|
238 | # These are relatively independent and stateless | |
239 | self.init_ipython_dir(ipython_dir) |
|
239 | self.init_ipython_dir(ipython_dir) | |
240 | self.init_instance_attrs() |
|
240 | self.init_instance_attrs() | |
241 | self.init_environment() |
|
241 | self.init_environment() | |
242 |
|
242 | |||
243 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
243 | # Create namespaces (user_ns, user_global_ns, etc.) | |
244 | self.init_create_namespaces(user_ns, user_global_ns) |
|
244 | self.init_create_namespaces(user_ns, user_global_ns) | |
245 | # This has to be done after init_create_namespaces because it uses |
|
245 | # This has to be done after init_create_namespaces because it uses | |
246 | # something in self.user_ns, but before init_sys_modules, which |
|
246 | # something in self.user_ns, but before init_sys_modules, which | |
247 | # is the first thing to modify sys. |
|
247 | # is the first thing to modify sys. | |
248 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
248 | # TODO: When we override sys.stdout and sys.stderr before this class | |
249 | # is created, we are saving the overridden ones here. Not sure if this |
|
249 | # is created, we are saving the overridden ones here. Not sure if this | |
250 | # is what we want to do. |
|
250 | # is what we want to do. | |
251 | self.save_sys_module_state() |
|
251 | self.save_sys_module_state() | |
252 | self.init_sys_modules() |
|
252 | self.init_sys_modules() | |
253 |
|
253 | |||
254 | self.init_history() |
|
254 | self.init_history() | |
255 | self.init_encoding() |
|
255 | self.init_encoding() | |
256 | self.init_prefilter() |
|
256 | self.init_prefilter() | |
257 |
|
257 | |||
258 | Magic.__init__(self, self) |
|
258 | Magic.__init__(self, self) | |
259 |
|
259 | |||
260 | self.init_syntax_highlighting() |
|
260 | self.init_syntax_highlighting() | |
261 | self.init_hooks() |
|
261 | self.init_hooks() | |
262 | self.init_pushd_popd_magic() |
|
262 | self.init_pushd_popd_magic() | |
263 | # self.init_traceback_handlers use to be here, but we moved it below |
|
263 | # self.init_traceback_handlers use to be here, but we moved it below | |
264 | # because it and init_io have to come after init_readline. |
|
264 | # because it and init_io have to come after init_readline. | |
265 | self.init_user_ns() |
|
265 | self.init_user_ns() | |
266 | self.init_logger() |
|
266 | self.init_logger() | |
267 | self.init_alias() |
|
267 | self.init_alias() | |
268 | self.init_builtins() |
|
268 | self.init_builtins() | |
269 |
|
269 | |||
270 | # pre_config_initialization |
|
270 | # pre_config_initialization | |
271 |
|
271 | |||
272 | # The next section should contain everything that was in ipmaker. |
|
272 | # The next section should contain everything that was in ipmaker. | |
273 | self.init_logstart() |
|
273 | self.init_logstart() | |
274 |
|
274 | |||
275 | # The following was in post_config_initialization |
|
275 | # The following was in post_config_initialization | |
276 | self.init_inspector() |
|
276 | self.init_inspector() | |
277 | # init_readline() must come before init_io(), because init_io uses |
|
277 | # init_readline() must come before init_io(), because init_io uses | |
278 | # readline related things. |
|
278 | # readline related things. | |
279 | self.init_readline() |
|
279 | self.init_readline() | |
280 | # init_completer must come after init_readline, because it needs to |
|
280 | # init_completer must come after init_readline, because it needs to | |
281 | # know whether readline is present or not system-wide to configure the |
|
281 | # know whether readline is present or not system-wide to configure the | |
282 | # completers, since the completion machinery can now operate |
|
282 | # completers, since the completion machinery can now operate | |
283 | # independently of readline (e.g. over the network) |
|
283 | # independently of readline (e.g. over the network) | |
284 | self.init_completer() |
|
284 | self.init_completer() | |
285 | # TODO: init_io() needs to happen before init_traceback handlers |
|
285 | # TODO: init_io() needs to happen before init_traceback handlers | |
286 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
286 | # because the traceback handlers hardcode the stdout/stderr streams. | |
287 | # This logic in in debugger.Pdb and should eventually be changed. |
|
287 | # This logic in in debugger.Pdb and should eventually be changed. | |
288 | self.init_io() |
|
288 | self.init_io() | |
289 | self.init_traceback_handlers(custom_exceptions) |
|
289 | self.init_traceback_handlers(custom_exceptions) | |
290 | self.init_prompts() |
|
290 | self.init_prompts() | |
291 | self.init_display_formatter() |
|
291 | self.init_display_formatter() | |
292 | self.init_display_pub() |
|
292 | self.init_display_pub() | |
293 | self.init_displayhook() |
|
293 | self.init_displayhook() | |
294 | self.init_reload_doctest() |
|
294 | self.init_reload_doctest() | |
295 | self.init_magics() |
|
295 | self.init_magics() | |
296 | self.init_pdb() |
|
296 | self.init_pdb() | |
297 | self.init_extension_manager() |
|
297 | self.init_extension_manager() | |
298 | self.init_plugin_manager() |
|
298 | self.init_plugin_manager() | |
299 | self.init_payload() |
|
299 | self.init_payload() | |
300 | self.hooks.late_startup_hook() |
|
300 | self.hooks.late_startup_hook() | |
301 | atexit.register(self.atexit_operations) |
|
301 | atexit.register(self.atexit_operations) | |
302 |
|
302 | |||
303 | # While we're trying to have each part of the code directly access what it |
|
303 | # While we're trying to have each part of the code directly access what it | |
304 | # needs without keeping redundant references to objects, we have too much |
|
304 | # needs without keeping redundant references to objects, we have too much | |
305 | # legacy code that expects ip.db to exist, so let's make it a property that |
|
305 | # legacy code that expects ip.db to exist, so let's make it a property that | |
306 | # retrieves the underlying object from our new history manager. |
|
306 | # retrieves the underlying object from our new history manager. | |
307 | @property |
|
307 | @property | |
308 | def db(self): |
|
308 | def db(self): | |
309 | return self.history_manager.shadow_db |
|
309 | return self.history_manager.shadow_db | |
310 |
|
310 | |||
311 | @classmethod |
|
311 | @classmethod | |
312 | def instance(cls, *args, **kwargs): |
|
312 | def instance(cls, *args, **kwargs): | |
313 | """Returns a global InteractiveShell instance.""" |
|
313 | """Returns a global InteractiveShell instance.""" | |
314 | if cls._instance is None: |
|
314 | if cls._instance is None: | |
315 | inst = cls(*args, **kwargs) |
|
315 | inst = cls(*args, **kwargs) | |
316 | # Now make sure that the instance will also be returned by |
|
316 | # Now make sure that the instance will also be returned by | |
317 | # the subclasses instance attribute. |
|
317 | # the subclasses instance attribute. | |
318 | for subclass in cls.mro(): |
|
318 | for subclass in cls.mro(): | |
319 | if issubclass(cls, subclass) and \ |
|
319 | if issubclass(cls, subclass) and \ | |
320 | issubclass(subclass, InteractiveShell): |
|
320 | issubclass(subclass, InteractiveShell): | |
321 | subclass._instance = inst |
|
321 | subclass._instance = inst | |
322 | else: |
|
322 | else: | |
323 | break |
|
323 | break | |
324 | if isinstance(cls._instance, cls): |
|
324 | if isinstance(cls._instance, cls): | |
325 | return cls._instance |
|
325 | return cls._instance | |
326 | else: |
|
326 | else: | |
327 | raise MultipleInstanceError( |
|
327 | raise MultipleInstanceError( | |
328 | 'Multiple incompatible subclass instances of ' |
|
328 | 'Multiple incompatible subclass instances of ' | |
329 | 'InteractiveShell are being created.' |
|
329 | 'InteractiveShell are being created.' | |
330 | ) |
|
330 | ) | |
331 |
|
331 | |||
332 | @classmethod |
|
332 | @classmethod | |
333 | def initialized(cls): |
|
333 | def initialized(cls): | |
334 | return hasattr(cls, "_instance") |
|
334 | return hasattr(cls, "_instance") | |
335 |
|
335 | |||
336 | def get_ipython(self): |
|
336 | def get_ipython(self): | |
337 | """Return the currently running IPython instance.""" |
|
337 | """Return the currently running IPython instance.""" | |
338 | return self |
|
338 | return self | |
339 |
|
339 | |||
340 | #------------------------------------------------------------------------- |
|
340 | #------------------------------------------------------------------------- | |
341 | # Trait changed handlers |
|
341 | # Trait changed handlers | |
342 | #------------------------------------------------------------------------- |
|
342 | #------------------------------------------------------------------------- | |
343 |
|
343 | |||
344 | def _ipython_dir_changed(self, name, new): |
|
344 | def _ipython_dir_changed(self, name, new): | |
345 | if not os.path.isdir(new): |
|
345 | if not os.path.isdir(new): | |
346 | os.makedirs(new, mode = 0777) |
|
346 | os.makedirs(new, mode = 0777) | |
347 |
|
347 | |||
348 | def set_autoindent(self,value=None): |
|
348 | def set_autoindent(self,value=None): | |
349 | """Set the autoindent flag, checking for readline support. |
|
349 | """Set the autoindent flag, checking for readline support. | |
350 |
|
350 | |||
351 | If called with no arguments, it acts as a toggle.""" |
|
351 | If called with no arguments, it acts as a toggle.""" | |
352 |
|
352 | |||
353 | if not self.has_readline: |
|
353 | if not self.has_readline: | |
354 | if os.name == 'posix': |
|
354 | if os.name == 'posix': | |
355 | warn("The auto-indent feature requires the readline library") |
|
355 | warn("The auto-indent feature requires the readline library") | |
356 | self.autoindent = 0 |
|
356 | self.autoindent = 0 | |
357 | return |
|
357 | return | |
358 | if value is None: |
|
358 | if value is None: | |
359 | self.autoindent = not self.autoindent |
|
359 | self.autoindent = not self.autoindent | |
360 | else: |
|
360 | else: | |
361 | self.autoindent = value |
|
361 | self.autoindent = value | |
362 |
|
362 | |||
363 | #------------------------------------------------------------------------- |
|
363 | #------------------------------------------------------------------------- | |
364 | # init_* methods called by __init__ |
|
364 | # init_* methods called by __init__ | |
365 | #------------------------------------------------------------------------- |
|
365 | #------------------------------------------------------------------------- | |
366 |
|
366 | |||
367 | def init_ipython_dir(self, ipython_dir): |
|
367 | def init_ipython_dir(self, ipython_dir): | |
368 | if ipython_dir is not None: |
|
368 | if ipython_dir is not None: | |
369 | self.ipython_dir = ipython_dir |
|
369 | self.ipython_dir = ipython_dir | |
370 | self.config.Global.ipython_dir = self.ipython_dir |
|
370 | self.config.Global.ipython_dir = self.ipython_dir | |
371 | return |
|
371 | return | |
372 |
|
372 | |||
373 | if hasattr(self.config.Global, 'ipython_dir'): |
|
373 | if hasattr(self.config.Global, 'ipython_dir'): | |
374 | self.ipython_dir = self.config.Global.ipython_dir |
|
374 | self.ipython_dir = self.config.Global.ipython_dir | |
375 | else: |
|
375 | else: | |
376 | self.ipython_dir = get_ipython_dir() |
|
376 | self.ipython_dir = get_ipython_dir() | |
377 |
|
377 | |||
378 | # All children can just read this |
|
378 | # All children can just read this | |
379 | self.config.Global.ipython_dir = self.ipython_dir |
|
379 | self.config.Global.ipython_dir = self.ipython_dir | |
380 |
|
380 | |||
381 | def init_instance_attrs(self): |
|
381 | def init_instance_attrs(self): | |
382 | self.more = False |
|
382 | self.more = False | |
383 |
|
383 | |||
384 | # command compiler |
|
384 | # command compiler | |
385 | self.compile = CachingCompiler() |
|
385 | self.compile = CachingCompiler() | |
386 |
|
386 | |||
387 | # User input buffers |
|
387 | # User input buffers | |
388 | # NOTE: these variables are slated for full removal, once we are 100% |
|
388 | # NOTE: these variables are slated for full removal, once we are 100% | |
389 | # sure that the new execution logic is solid. We will delte runlines, |
|
389 | # sure that the new execution logic is solid. We will delte runlines, | |
390 | # push_line and these buffers, as all input will be managed by the |
|
390 | # push_line and these buffers, as all input will be managed by the | |
391 | # frontends via an inputsplitter instance. |
|
391 | # frontends via an inputsplitter instance. | |
392 | self.buffer = [] |
|
392 | self.buffer = [] | |
393 | self.buffer_raw = [] |
|
393 | self.buffer_raw = [] | |
394 |
|
394 | |||
395 | # Make an empty namespace, which extension writers can rely on both |
|
395 | # Make an empty namespace, which extension writers can rely on both | |
396 | # existing and NEVER being used by ipython itself. This gives them a |
|
396 | # existing and NEVER being used by ipython itself. This gives them a | |
397 | # convenient location for storing additional information and state |
|
397 | # convenient location for storing additional information and state | |
398 | # their extensions may require, without fear of collisions with other |
|
398 | # their extensions may require, without fear of collisions with other | |
399 | # ipython names that may develop later. |
|
399 | # ipython names that may develop later. | |
400 | self.meta = Struct() |
|
400 | self.meta = Struct() | |
401 |
|
401 | |||
402 | # Object variable to store code object waiting execution. This is |
|
402 | # Object variable to store code object waiting execution. This is | |
403 | # used mainly by the multithreaded shells, but it can come in handy in |
|
403 | # used mainly by the multithreaded shells, but it can come in handy in | |
404 | # other situations. No need to use a Queue here, since it's a single |
|
404 | # other situations. No need to use a Queue here, since it's a single | |
405 | # item which gets cleared once run. |
|
405 | # item which gets cleared once run. | |
406 | self.code_to_run = None |
|
406 | self.code_to_run = None | |
407 |
|
407 | |||
408 | # Temporary files used for various purposes. Deleted at exit. |
|
408 | # Temporary files used for various purposes. Deleted at exit. | |
409 | self.tempfiles = [] |
|
409 | self.tempfiles = [] | |
410 |
|
410 | |||
411 | # Keep track of readline usage (later set by init_readline) |
|
411 | # Keep track of readline usage (later set by init_readline) | |
412 | self.has_readline = False |
|
412 | self.has_readline = False | |
413 |
|
413 | |||
414 | # keep track of where we started running (mainly for crash post-mortem) |
|
414 | # keep track of where we started running (mainly for crash post-mortem) | |
415 | # This is not being used anywhere currently. |
|
415 | # This is not being used anywhere currently. | |
416 | self.starting_dir = os.getcwd() |
|
416 | self.starting_dir = os.getcwd() | |
417 |
|
417 | |||
418 | # Indentation management |
|
418 | # Indentation management | |
419 | self.indent_current_nsp = 0 |
|
419 | self.indent_current_nsp = 0 | |
420 |
|
420 | |||
421 | def init_environment(self): |
|
421 | def init_environment(self): | |
422 | """Any changes we need to make to the user's environment.""" |
|
422 | """Any changes we need to make to the user's environment.""" | |
423 | pass |
|
423 | pass | |
424 |
|
424 | |||
425 | def init_encoding(self): |
|
425 | def init_encoding(self): | |
426 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
426 | # Get system encoding at startup time. Certain terminals (like Emacs | |
427 | # under Win32 have it set to None, and we need to have a known valid |
|
427 | # under Win32 have it set to None, and we need to have a known valid | |
428 | # encoding to use in the raw_input() method |
|
428 | # encoding to use in the raw_input() method | |
429 | try: |
|
429 | try: | |
430 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
430 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
431 | except AttributeError: |
|
431 | except AttributeError: | |
432 | self.stdin_encoding = 'ascii' |
|
432 | self.stdin_encoding = 'ascii' | |
433 |
|
433 | |||
434 | def init_syntax_highlighting(self): |
|
434 | def init_syntax_highlighting(self): | |
435 | # Python source parser/formatter for syntax highlighting |
|
435 | # Python source parser/formatter for syntax highlighting | |
436 | pyformat = PyColorize.Parser().format |
|
436 | pyformat = PyColorize.Parser().format | |
437 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
437 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
438 |
|
438 | |||
439 | def init_pushd_popd_magic(self): |
|
439 | def init_pushd_popd_magic(self): | |
440 | # for pushd/popd management |
|
440 | # for pushd/popd management | |
441 | try: |
|
441 | try: | |
442 | self.home_dir = get_home_dir() |
|
442 | self.home_dir = get_home_dir() | |
443 | except HomeDirError, msg: |
|
443 | except HomeDirError, msg: | |
444 | fatal(msg) |
|
444 | fatal(msg) | |
445 |
|
445 | |||
446 | self.dir_stack = [] |
|
446 | self.dir_stack = [] | |
447 |
|
447 | |||
448 | def init_logger(self): |
|
448 | def init_logger(self): | |
449 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
449 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
450 | logmode='rotate') |
|
450 | logmode='rotate') | |
451 |
|
451 | |||
452 | def init_logstart(self): |
|
452 | def init_logstart(self): | |
453 | """Initialize logging in case it was requested at the command line. |
|
453 | """Initialize logging in case it was requested at the command line. | |
454 | """ |
|
454 | """ | |
455 | if self.logappend: |
|
455 | if self.logappend: | |
456 | self.magic_logstart(self.logappend + ' append') |
|
456 | self.magic_logstart(self.logappend + ' append') | |
457 | elif self.logfile: |
|
457 | elif self.logfile: | |
458 | self.magic_logstart(self.logfile) |
|
458 | self.magic_logstart(self.logfile) | |
459 | elif self.logstart: |
|
459 | elif self.logstart: | |
460 | self.magic_logstart() |
|
460 | self.magic_logstart() | |
461 |
|
461 | |||
462 | def init_builtins(self): |
|
462 | def init_builtins(self): | |
463 | self.builtin_trap = BuiltinTrap(shell=self) |
|
463 | self.builtin_trap = BuiltinTrap(shell=self) | |
464 |
|
464 | |||
465 | def init_inspector(self): |
|
465 | def init_inspector(self): | |
466 | # Object inspector |
|
466 | # Object inspector | |
467 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
467 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
468 | PyColorize.ANSICodeColors, |
|
468 | PyColorize.ANSICodeColors, | |
469 | 'NoColor', |
|
469 | 'NoColor', | |
470 | self.object_info_string_level) |
|
470 | self.object_info_string_level) | |
471 |
|
471 | |||
472 | def init_io(self): |
|
472 | def init_io(self): | |
473 | # This will just use sys.stdout and sys.stderr. If you want to |
|
473 | # This will just use sys.stdout and sys.stderr. If you want to | |
474 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
474 | # override sys.stdout and sys.stderr themselves, you need to do that | |
475 | # *before* instantiating this class, because Term holds onto |
|
475 | # *before* instantiating this class, because Term holds onto | |
476 | # references to the underlying streams. |
|
476 | # references to the underlying streams. | |
477 | if sys.platform == 'win32' and self.has_readline: |
|
477 | if sys.platform == 'win32' and self.has_readline: | |
478 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
478 | Term = io.IOTerm(cout=self.readline._outputfile, | |
479 | cerr=self.readline._outputfile) |
|
479 | cerr=self.readline._outputfile) | |
480 | else: |
|
480 | else: | |
481 | Term = io.IOTerm() |
|
481 | Term = io.IOTerm() | |
482 | io.Term = Term |
|
482 | io.Term = Term | |
483 |
|
483 | |||
484 | def init_prompts(self): |
|
484 | def init_prompts(self): | |
485 | # TODO: This is a pass for now because the prompts are managed inside |
|
485 | # TODO: This is a pass for now because the prompts are managed inside | |
486 | # the DisplayHook. Once there is a separate prompt manager, this |
|
486 | # the DisplayHook. Once there is a separate prompt manager, this | |
487 | # will initialize that object and all prompt related information. |
|
487 | # will initialize that object and all prompt related information. | |
488 | pass |
|
488 | pass | |
489 |
|
489 | |||
490 | def init_display_formatter(self): |
|
490 | def init_display_formatter(self): | |
491 | self.display_formatter = DisplayFormatter(config=self.config) |
|
491 | self.display_formatter = DisplayFormatter(config=self.config) | |
492 |
|
492 | |||
493 | def init_display_pub(self): |
|
493 | def init_display_pub(self): | |
494 | self.display_pub = self.display_pub_class(config=self.config) |
|
494 | self.display_pub = self.display_pub_class(config=self.config) | |
495 |
|
495 | |||
496 | def init_displayhook(self): |
|
496 | def init_displayhook(self): | |
497 | # Initialize displayhook, set in/out prompts and printing system |
|
497 | # Initialize displayhook, set in/out prompts and printing system | |
498 | self.displayhook = self.displayhook_class( |
|
498 | self.displayhook = self.displayhook_class( | |
499 | config=self.config, |
|
499 | config=self.config, | |
500 | shell=self, |
|
500 | shell=self, | |
501 | cache_size=self.cache_size, |
|
501 | cache_size=self.cache_size, | |
502 | input_sep = self.separate_in, |
|
502 | input_sep = self.separate_in, | |
503 | output_sep = self.separate_out, |
|
503 | output_sep = self.separate_out, | |
504 | output_sep2 = self.separate_out2, |
|
504 | output_sep2 = self.separate_out2, | |
505 | ps1 = self.prompt_in1, |
|
505 | ps1 = self.prompt_in1, | |
506 | ps2 = self.prompt_in2, |
|
506 | ps2 = self.prompt_in2, | |
507 | ps_out = self.prompt_out, |
|
507 | ps_out = self.prompt_out, | |
508 | pad_left = self.prompts_pad_left |
|
508 | pad_left = self.prompts_pad_left | |
509 | ) |
|
509 | ) | |
510 | # This is a context manager that installs/revmoes the displayhook at |
|
510 | # This is a context manager that installs/revmoes the displayhook at | |
511 | # the appropriate time. |
|
511 | # the appropriate time. | |
512 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
512 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
513 |
|
513 | |||
514 | def init_reload_doctest(self): |
|
514 | def init_reload_doctest(self): | |
515 | # Do a proper resetting of doctest, including the necessary displayhook |
|
515 | # Do a proper resetting of doctest, including the necessary displayhook | |
516 | # monkeypatching |
|
516 | # monkeypatching | |
517 | try: |
|
517 | try: | |
518 | doctest_reload() |
|
518 | doctest_reload() | |
519 | except ImportError: |
|
519 | except ImportError: | |
520 | warn("doctest module does not exist.") |
|
520 | warn("doctest module does not exist.") | |
521 |
|
521 | |||
522 | #------------------------------------------------------------------------- |
|
522 | #------------------------------------------------------------------------- | |
523 | # Things related to injections into the sys module |
|
523 | # Things related to injections into the sys module | |
524 | #------------------------------------------------------------------------- |
|
524 | #------------------------------------------------------------------------- | |
525 |
|
525 | |||
526 | def save_sys_module_state(self): |
|
526 | def save_sys_module_state(self): | |
527 | """Save the state of hooks in the sys module. |
|
527 | """Save the state of hooks in the sys module. | |
528 |
|
528 | |||
529 | This has to be called after self.user_ns is created. |
|
529 | This has to be called after self.user_ns is created. | |
530 | """ |
|
530 | """ | |
531 | self._orig_sys_module_state = {} |
|
531 | self._orig_sys_module_state = {} | |
532 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
532 | self._orig_sys_module_state['stdin'] = sys.stdin | |
533 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
533 | self._orig_sys_module_state['stdout'] = sys.stdout | |
534 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
534 | self._orig_sys_module_state['stderr'] = sys.stderr | |
535 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
535 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
536 | try: |
|
536 | try: | |
537 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
537 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
538 | except KeyError: |
|
538 | except KeyError: | |
539 | pass |
|
539 | pass | |
540 |
|
540 | |||
541 | def restore_sys_module_state(self): |
|
541 | def restore_sys_module_state(self): | |
542 | """Restore the state of the sys module.""" |
|
542 | """Restore the state of the sys module.""" | |
543 | try: |
|
543 | try: | |
544 | for k, v in self._orig_sys_module_state.iteritems(): |
|
544 | for k, v in self._orig_sys_module_state.iteritems(): | |
545 | setattr(sys, k, v) |
|
545 | setattr(sys, k, v) | |
546 | except AttributeError: |
|
546 | except AttributeError: | |
547 | pass |
|
547 | pass | |
548 | # Reset what what done in self.init_sys_modules |
|
548 | # Reset what what done in self.init_sys_modules | |
549 | try: |
|
549 | try: | |
550 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
550 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
551 | except (AttributeError, KeyError): |
|
551 | except (AttributeError, KeyError): | |
552 | pass |
|
552 | pass | |
553 |
|
553 | |||
554 | #------------------------------------------------------------------------- |
|
554 | #------------------------------------------------------------------------- | |
555 | # Things related to hooks |
|
555 | # Things related to hooks | |
556 | #------------------------------------------------------------------------- |
|
556 | #------------------------------------------------------------------------- | |
557 |
|
557 | |||
558 | def init_hooks(self): |
|
558 | def init_hooks(self): | |
559 | # hooks holds pointers used for user-side customizations |
|
559 | # hooks holds pointers used for user-side customizations | |
560 | self.hooks = Struct() |
|
560 | self.hooks = Struct() | |
561 |
|
561 | |||
562 | self.strdispatchers = {} |
|
562 | self.strdispatchers = {} | |
563 |
|
563 | |||
564 | # Set all default hooks, defined in the IPython.hooks module. |
|
564 | # Set all default hooks, defined in the IPython.hooks module. | |
565 | hooks = IPython.core.hooks |
|
565 | hooks = IPython.core.hooks | |
566 | for hook_name in hooks.__all__: |
|
566 | for hook_name in hooks.__all__: | |
567 | # default hooks have priority 100, i.e. low; user hooks should have |
|
567 | # default hooks have priority 100, i.e. low; user hooks should have | |
568 | # 0-100 priority |
|
568 | # 0-100 priority | |
569 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
569 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
570 |
|
570 | |||
571 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
571 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
572 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
572 | """set_hook(name,hook) -> sets an internal IPython hook. | |
573 |
|
573 | |||
574 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
574 | IPython exposes some of its internal API as user-modifiable hooks. By | |
575 | adding your function to one of these hooks, you can modify IPython's |
|
575 | adding your function to one of these hooks, you can modify IPython's | |
576 | behavior to call at runtime your own routines.""" |
|
576 | behavior to call at runtime your own routines.""" | |
577 |
|
577 | |||
578 | # At some point in the future, this should validate the hook before it |
|
578 | # At some point in the future, this should validate the hook before it | |
579 | # accepts it. Probably at least check that the hook takes the number |
|
579 | # accepts it. Probably at least check that the hook takes the number | |
580 | # of args it's supposed to. |
|
580 | # of args it's supposed to. | |
581 |
|
581 | |||
582 | f = types.MethodType(hook,self) |
|
582 | f = types.MethodType(hook,self) | |
583 |
|
583 | |||
584 | # check if the hook is for strdispatcher first |
|
584 | # check if the hook is for strdispatcher first | |
585 | if str_key is not None: |
|
585 | if str_key is not None: | |
586 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
586 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
587 | sdp.add_s(str_key, f, priority ) |
|
587 | sdp.add_s(str_key, f, priority ) | |
588 | self.strdispatchers[name] = sdp |
|
588 | self.strdispatchers[name] = sdp | |
589 | return |
|
589 | return | |
590 | if re_key is not None: |
|
590 | if re_key is not None: | |
591 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
591 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
592 | sdp.add_re(re.compile(re_key), f, priority ) |
|
592 | sdp.add_re(re.compile(re_key), f, priority ) | |
593 | self.strdispatchers[name] = sdp |
|
593 | self.strdispatchers[name] = sdp | |
594 | return |
|
594 | return | |
595 |
|
595 | |||
596 | dp = getattr(self.hooks, name, None) |
|
596 | dp = getattr(self.hooks, name, None) | |
597 | if name not in IPython.core.hooks.__all__: |
|
597 | if name not in IPython.core.hooks.__all__: | |
598 | print "Warning! Hook '%s' is not one of %s" % \ |
|
598 | print "Warning! Hook '%s' is not one of %s" % \ | |
599 | (name, IPython.core.hooks.__all__ ) |
|
599 | (name, IPython.core.hooks.__all__ ) | |
600 | if not dp: |
|
600 | if not dp: | |
601 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
601 | dp = IPython.core.hooks.CommandChainDispatcher() | |
602 |
|
602 | |||
603 | try: |
|
603 | try: | |
604 | dp.add(f,priority) |
|
604 | dp.add(f,priority) | |
605 | except AttributeError: |
|
605 | except AttributeError: | |
606 | # it was not commandchain, plain old func - replace |
|
606 | # it was not commandchain, plain old func - replace | |
607 | dp = f |
|
607 | dp = f | |
608 |
|
608 | |||
609 | setattr(self.hooks,name, dp) |
|
609 | setattr(self.hooks,name, dp) | |
610 |
|
610 | |||
611 | def register_post_execute(self, func): |
|
611 | def register_post_execute(self, func): | |
612 | """Register a function for calling after code execution. |
|
612 | """Register a function for calling after code execution. | |
613 | """ |
|
613 | """ | |
614 | if not callable(func): |
|
614 | if not callable(func): | |
615 | raise ValueError('argument %s must be callable' % func) |
|
615 | raise ValueError('argument %s must be callable' % func) | |
616 | self._post_execute.add(func) |
|
616 | self._post_execute.add(func) | |
617 |
|
617 | |||
618 | #------------------------------------------------------------------------- |
|
618 | #------------------------------------------------------------------------- | |
619 | # Things related to the "main" module |
|
619 | # Things related to the "main" module | |
620 | #------------------------------------------------------------------------- |
|
620 | #------------------------------------------------------------------------- | |
621 |
|
621 | |||
622 | def new_main_mod(self,ns=None): |
|
622 | def new_main_mod(self,ns=None): | |
623 | """Return a new 'main' module object for user code execution. |
|
623 | """Return a new 'main' module object for user code execution. | |
624 | """ |
|
624 | """ | |
625 | main_mod = self._user_main_module |
|
625 | main_mod = self._user_main_module | |
626 | init_fakemod_dict(main_mod,ns) |
|
626 | init_fakemod_dict(main_mod,ns) | |
627 | return main_mod |
|
627 | return main_mod | |
628 |
|
628 | |||
629 | def cache_main_mod(self,ns,fname): |
|
629 | def cache_main_mod(self,ns,fname): | |
630 | """Cache a main module's namespace. |
|
630 | """Cache a main module's namespace. | |
631 |
|
631 | |||
632 | When scripts are executed via %run, we must keep a reference to the |
|
632 | When scripts are executed via %run, we must keep a reference to the | |
633 | namespace of their __main__ module (a FakeModule instance) around so |
|
633 | namespace of their __main__ module (a FakeModule instance) around so | |
634 | that Python doesn't clear it, rendering objects defined therein |
|
634 | that Python doesn't clear it, rendering objects defined therein | |
635 | useless. |
|
635 | useless. | |
636 |
|
636 | |||
637 | This method keeps said reference in a private dict, keyed by the |
|
637 | This method keeps said reference in a private dict, keyed by the | |
638 | absolute path of the module object (which corresponds to the script |
|
638 | absolute path of the module object (which corresponds to the script | |
639 | path). This way, for multiple executions of the same script we only |
|
639 | path). This way, for multiple executions of the same script we only | |
640 | keep one copy of the namespace (the last one), thus preventing memory |
|
640 | keep one copy of the namespace (the last one), thus preventing memory | |
641 | leaks from old references while allowing the objects from the last |
|
641 | leaks from old references while allowing the objects from the last | |
642 | execution to be accessible. |
|
642 | execution to be accessible. | |
643 |
|
643 | |||
644 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
644 | Note: we can not allow the actual FakeModule instances to be deleted, | |
645 | because of how Python tears down modules (it hard-sets all their |
|
645 | because of how Python tears down modules (it hard-sets all their | |
646 | references to None without regard for reference counts). This method |
|
646 | references to None without regard for reference counts). This method | |
647 | must therefore make a *copy* of the given namespace, to allow the |
|
647 | must therefore make a *copy* of the given namespace, to allow the | |
648 | original module's __dict__ to be cleared and reused. |
|
648 | original module's __dict__ to be cleared and reused. | |
649 |
|
649 | |||
650 |
|
650 | |||
651 | Parameters |
|
651 | Parameters | |
652 | ---------- |
|
652 | ---------- | |
653 | ns : a namespace (a dict, typically) |
|
653 | ns : a namespace (a dict, typically) | |
654 |
|
654 | |||
655 | fname : str |
|
655 | fname : str | |
656 | Filename associated with the namespace. |
|
656 | Filename associated with the namespace. | |
657 |
|
657 | |||
658 | Examples |
|
658 | Examples | |
659 | -------- |
|
659 | -------- | |
660 |
|
660 | |||
661 | In [10]: import IPython |
|
661 | In [10]: import IPython | |
662 |
|
662 | |||
663 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
663 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
664 |
|
664 | |||
665 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
665 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
666 | Out[12]: True |
|
666 | Out[12]: True | |
667 | """ |
|
667 | """ | |
668 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
668 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
669 |
|
669 | |||
670 | def clear_main_mod_cache(self): |
|
670 | def clear_main_mod_cache(self): | |
671 | """Clear the cache of main modules. |
|
671 | """Clear the cache of main modules. | |
672 |
|
672 | |||
673 | Mainly for use by utilities like %reset. |
|
673 | Mainly for use by utilities like %reset. | |
674 |
|
674 | |||
675 | Examples |
|
675 | Examples | |
676 | -------- |
|
676 | -------- | |
677 |
|
677 | |||
678 | In [15]: import IPython |
|
678 | In [15]: import IPython | |
679 |
|
679 | |||
680 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
680 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
681 |
|
681 | |||
682 | In [17]: len(_ip._main_ns_cache) > 0 |
|
682 | In [17]: len(_ip._main_ns_cache) > 0 | |
683 | Out[17]: True |
|
683 | Out[17]: True | |
684 |
|
684 | |||
685 | In [18]: _ip.clear_main_mod_cache() |
|
685 | In [18]: _ip.clear_main_mod_cache() | |
686 |
|
686 | |||
687 | In [19]: len(_ip._main_ns_cache) == 0 |
|
687 | In [19]: len(_ip._main_ns_cache) == 0 | |
688 | Out[19]: True |
|
688 | Out[19]: True | |
689 | """ |
|
689 | """ | |
690 | self._main_ns_cache.clear() |
|
690 | self._main_ns_cache.clear() | |
691 |
|
691 | |||
692 | #------------------------------------------------------------------------- |
|
692 | #------------------------------------------------------------------------- | |
693 | # Things related to debugging |
|
693 | # Things related to debugging | |
694 | #------------------------------------------------------------------------- |
|
694 | #------------------------------------------------------------------------- | |
695 |
|
695 | |||
696 | def init_pdb(self): |
|
696 | def init_pdb(self): | |
697 | # Set calling of pdb on exceptions |
|
697 | # Set calling of pdb on exceptions | |
698 | # self.call_pdb is a property |
|
698 | # self.call_pdb is a property | |
699 | self.call_pdb = self.pdb |
|
699 | self.call_pdb = self.pdb | |
700 |
|
700 | |||
701 | def _get_call_pdb(self): |
|
701 | def _get_call_pdb(self): | |
702 | return self._call_pdb |
|
702 | return self._call_pdb | |
703 |
|
703 | |||
704 | def _set_call_pdb(self,val): |
|
704 | def _set_call_pdb(self,val): | |
705 |
|
705 | |||
706 | if val not in (0,1,False,True): |
|
706 | if val not in (0,1,False,True): | |
707 | raise ValueError,'new call_pdb value must be boolean' |
|
707 | raise ValueError,'new call_pdb value must be boolean' | |
708 |
|
708 | |||
709 | # store value in instance |
|
709 | # store value in instance | |
710 | self._call_pdb = val |
|
710 | self._call_pdb = val | |
711 |
|
711 | |||
712 | # notify the actual exception handlers |
|
712 | # notify the actual exception handlers | |
713 | self.InteractiveTB.call_pdb = val |
|
713 | self.InteractiveTB.call_pdb = val | |
714 |
|
714 | |||
715 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
715 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
716 | 'Control auto-activation of pdb at exceptions') |
|
716 | 'Control auto-activation of pdb at exceptions') | |
717 |
|
717 | |||
718 | def debugger(self,force=False): |
|
718 | def debugger(self,force=False): | |
719 | """Call the pydb/pdb debugger. |
|
719 | """Call the pydb/pdb debugger. | |
720 |
|
720 | |||
721 | Keywords: |
|
721 | Keywords: | |
722 |
|
722 | |||
723 | - force(False): by default, this routine checks the instance call_pdb |
|
723 | - force(False): by default, this routine checks the instance call_pdb | |
724 | flag and does not actually invoke the debugger if the flag is false. |
|
724 | flag and does not actually invoke the debugger if the flag is false. | |
725 | The 'force' option forces the debugger to activate even if the flag |
|
725 | The 'force' option forces the debugger to activate even if the flag | |
726 | is false. |
|
726 | is false. | |
727 | """ |
|
727 | """ | |
728 |
|
728 | |||
729 | if not (force or self.call_pdb): |
|
729 | if not (force or self.call_pdb): | |
730 | return |
|
730 | return | |
731 |
|
731 | |||
732 | if not hasattr(sys,'last_traceback'): |
|
732 | if not hasattr(sys,'last_traceback'): | |
733 | error('No traceback has been produced, nothing to debug.') |
|
733 | error('No traceback has been produced, nothing to debug.') | |
734 | return |
|
734 | return | |
735 |
|
735 | |||
736 | # use pydb if available |
|
736 | # use pydb if available | |
737 | if debugger.has_pydb: |
|
737 | if debugger.has_pydb: | |
738 | from pydb import pm |
|
738 | from pydb import pm | |
739 | else: |
|
739 | else: | |
740 | # fallback to our internal debugger |
|
740 | # fallback to our internal debugger | |
741 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
741 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
742 | self.history_saving_wrapper(pm)() |
|
742 | self.history_saving_wrapper(pm)() | |
743 |
|
743 | |||
744 | #------------------------------------------------------------------------- |
|
744 | #------------------------------------------------------------------------- | |
745 | # Things related to IPython's various namespaces |
|
745 | # Things related to IPython's various namespaces | |
746 | #------------------------------------------------------------------------- |
|
746 | #------------------------------------------------------------------------- | |
747 |
|
747 | |||
748 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
748 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
749 | # Create the namespace where the user will operate. user_ns is |
|
749 | # Create the namespace where the user will operate. user_ns is | |
750 | # normally the only one used, and it is passed to the exec calls as |
|
750 | # normally the only one used, and it is passed to the exec calls as | |
751 | # the locals argument. But we do carry a user_global_ns namespace |
|
751 | # the locals argument. But we do carry a user_global_ns namespace | |
752 | # given as the exec 'globals' argument, This is useful in embedding |
|
752 | # given as the exec 'globals' argument, This is useful in embedding | |
753 | # situations where the ipython shell opens in a context where the |
|
753 | # situations where the ipython shell opens in a context where the | |
754 | # distinction between locals and globals is meaningful. For |
|
754 | # distinction between locals and globals is meaningful. For | |
755 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
755 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
756 |
|
756 | |||
757 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
757 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
758 | # level as a dict instead of a module. This is a manual fix, but I |
|
758 | # level as a dict instead of a module. This is a manual fix, but I | |
759 | # should really track down where the problem is coming from. Alex |
|
759 | # should really track down where the problem is coming from. Alex | |
760 | # Schmolck reported this problem first. |
|
760 | # Schmolck reported this problem first. | |
761 |
|
761 | |||
762 | # A useful post by Alex Martelli on this topic: |
|
762 | # A useful post by Alex Martelli on this topic: | |
763 | # Re: inconsistent value from __builtins__ |
|
763 | # Re: inconsistent value from __builtins__ | |
764 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
764 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
765 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
765 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
766 | # Gruppen: comp.lang.python |
|
766 | # Gruppen: comp.lang.python | |
767 |
|
767 | |||
768 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
768 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
769 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
769 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
770 | # > <type 'dict'> |
|
770 | # > <type 'dict'> | |
771 | # > >>> print type(__builtins__) |
|
771 | # > >>> print type(__builtins__) | |
772 | # > <type 'module'> |
|
772 | # > <type 'module'> | |
773 | # > Is this difference in return value intentional? |
|
773 | # > Is this difference in return value intentional? | |
774 |
|
774 | |||
775 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
775 | # Well, it's documented that '__builtins__' can be either a dictionary | |
776 | # or a module, and it's been that way for a long time. Whether it's |
|
776 | # or a module, and it's been that way for a long time. Whether it's | |
777 | # intentional (or sensible), I don't know. In any case, the idea is |
|
777 | # intentional (or sensible), I don't know. In any case, the idea is | |
778 | # that if you need to access the built-in namespace directly, you |
|
778 | # that if you need to access the built-in namespace directly, you | |
779 | # should start with "import __builtin__" (note, no 's') which will |
|
779 | # should start with "import __builtin__" (note, no 's') which will | |
780 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
780 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
781 |
|
781 | |||
782 | # These routines return properly built dicts as needed by the rest of |
|
782 | # These routines return properly built dicts as needed by the rest of | |
783 | # the code, and can also be used by extension writers to generate |
|
783 | # the code, and can also be used by extension writers to generate | |
784 | # properly initialized namespaces. |
|
784 | # properly initialized namespaces. | |
785 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
785 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
786 | user_global_ns) |
|
786 | user_global_ns) | |
787 |
|
787 | |||
788 | # Assign namespaces |
|
788 | # Assign namespaces | |
789 | # This is the namespace where all normal user variables live |
|
789 | # This is the namespace where all normal user variables live | |
790 | self.user_ns = user_ns |
|
790 | self.user_ns = user_ns | |
791 | self.user_global_ns = user_global_ns |
|
791 | self.user_global_ns = user_global_ns | |
792 |
|
792 | |||
793 | # An auxiliary namespace that checks what parts of the user_ns were |
|
793 | # An auxiliary namespace that checks what parts of the user_ns were | |
794 | # loaded at startup, so we can list later only variables defined in |
|
794 | # loaded at startup, so we can list later only variables defined in | |
795 | # actual interactive use. Since it is always a subset of user_ns, it |
|
795 | # actual interactive use. Since it is always a subset of user_ns, it | |
796 | # doesn't need to be separately tracked in the ns_table. |
|
796 | # doesn't need to be separately tracked in the ns_table. | |
797 | self.user_ns_hidden = {} |
|
797 | self.user_ns_hidden = {} | |
798 |
|
798 | |||
799 | # A namespace to keep track of internal data structures to prevent |
|
799 | # A namespace to keep track of internal data structures to prevent | |
800 | # them from cluttering user-visible stuff. Will be updated later |
|
800 | # them from cluttering user-visible stuff. Will be updated later | |
801 | self.internal_ns = {} |
|
801 | self.internal_ns = {} | |
802 |
|
802 | |||
803 | # Now that FakeModule produces a real module, we've run into a nasty |
|
803 | # Now that FakeModule produces a real module, we've run into a nasty | |
804 | # problem: after script execution (via %run), the module where the user |
|
804 | # problem: after script execution (via %run), the module where the user | |
805 | # code ran is deleted. Now that this object is a true module (needed |
|
805 | # code ran is deleted. Now that this object is a true module (needed | |
806 | # so docetst and other tools work correctly), the Python module |
|
806 | # so docetst and other tools work correctly), the Python module | |
807 | # teardown mechanism runs over it, and sets to None every variable |
|
807 | # teardown mechanism runs over it, and sets to None every variable | |
808 | # present in that module. Top-level references to objects from the |
|
808 | # present in that module. Top-level references to objects from the | |
809 | # script survive, because the user_ns is updated with them. However, |
|
809 | # script survive, because the user_ns is updated with them. However, | |
810 | # calling functions defined in the script that use other things from |
|
810 | # calling functions defined in the script that use other things from | |
811 | # the script will fail, because the function's closure had references |
|
811 | # the script will fail, because the function's closure had references | |
812 | # to the original objects, which are now all None. So we must protect |
|
812 | # to the original objects, which are now all None. So we must protect | |
813 | # these modules from deletion by keeping a cache. |
|
813 | # these modules from deletion by keeping a cache. | |
814 | # |
|
814 | # | |
815 | # To avoid keeping stale modules around (we only need the one from the |
|
815 | # To avoid keeping stale modules around (we only need the one from the | |
816 | # last run), we use a dict keyed with the full path to the script, so |
|
816 | # last run), we use a dict keyed with the full path to the script, so | |
817 | # only the last version of the module is held in the cache. Note, |
|
817 | # only the last version of the module is held in the cache. Note, | |
818 | # however, that we must cache the module *namespace contents* (their |
|
818 | # however, that we must cache the module *namespace contents* (their | |
819 | # __dict__). Because if we try to cache the actual modules, old ones |
|
819 | # __dict__). Because if we try to cache the actual modules, old ones | |
820 | # (uncached) could be destroyed while still holding references (such as |
|
820 | # (uncached) could be destroyed while still holding references (such as | |
821 | # those held by GUI objects that tend to be long-lived)> |
|
821 | # those held by GUI objects that tend to be long-lived)> | |
822 | # |
|
822 | # | |
823 | # The %reset command will flush this cache. See the cache_main_mod() |
|
823 | # The %reset command will flush this cache. See the cache_main_mod() | |
824 | # and clear_main_mod_cache() methods for details on use. |
|
824 | # and clear_main_mod_cache() methods for details on use. | |
825 |
|
825 | |||
826 | # This is the cache used for 'main' namespaces |
|
826 | # This is the cache used for 'main' namespaces | |
827 | self._main_ns_cache = {} |
|
827 | self._main_ns_cache = {} | |
828 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
828 | # And this is the single instance of FakeModule whose __dict__ we keep | |
829 | # copying and clearing for reuse on each %run |
|
829 | # copying and clearing for reuse on each %run | |
830 | self._user_main_module = FakeModule() |
|
830 | self._user_main_module = FakeModule() | |
831 |
|
831 | |||
832 | # A table holding all the namespaces IPython deals with, so that |
|
832 | # A table holding all the namespaces IPython deals with, so that | |
833 | # introspection facilities can search easily. |
|
833 | # introspection facilities can search easily. | |
834 | self.ns_table = {'user':user_ns, |
|
834 | self.ns_table = {'user':user_ns, | |
835 | 'user_global':user_global_ns, |
|
835 | 'user_global':user_global_ns, | |
836 | 'internal':self.internal_ns, |
|
836 | 'internal':self.internal_ns, | |
837 | 'builtin':__builtin__.__dict__ |
|
837 | 'builtin':__builtin__.__dict__ | |
838 | } |
|
838 | } | |
839 |
|
839 | |||
840 | # Similarly, track all namespaces where references can be held and that |
|
840 | # Similarly, track all namespaces where references can be held and that | |
841 | # we can safely clear (so it can NOT include builtin). This one can be |
|
841 | # we can safely clear (so it can NOT include builtin). This one can be | |
842 | # a simple list. Note that the main execution namespaces, user_ns and |
|
842 | # a simple list. Note that the main execution namespaces, user_ns and | |
843 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
843 | # user_global_ns, can NOT be listed here, as clearing them blindly | |
844 | # causes errors in object __del__ methods. Instead, the reset() method |
|
844 | # causes errors in object __del__ methods. Instead, the reset() method | |
845 | # clears them manually and carefully. |
|
845 | # clears them manually and carefully. | |
846 | self.ns_refs_table = [ self.user_ns_hidden, |
|
846 | self.ns_refs_table = [ self.user_ns_hidden, | |
847 | self.internal_ns, self._main_ns_cache ] |
|
847 | self.internal_ns, self._main_ns_cache ] | |
848 |
|
848 | |||
849 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
849 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
850 | """Return a valid local and global user interactive namespaces. |
|
850 | """Return a valid local and global user interactive namespaces. | |
851 |
|
851 | |||
852 | This builds a dict with the minimal information needed to operate as a |
|
852 | This builds a dict with the minimal information needed to operate as a | |
853 | valid IPython user namespace, which you can pass to the various |
|
853 | valid IPython user namespace, which you can pass to the various | |
854 | embedding classes in ipython. The default implementation returns the |
|
854 | embedding classes in ipython. The default implementation returns the | |
855 | same dict for both the locals and the globals to allow functions to |
|
855 | same dict for both the locals and the globals to allow functions to | |
856 | refer to variables in the namespace. Customized implementations can |
|
856 | refer to variables in the namespace. Customized implementations can | |
857 | return different dicts. The locals dictionary can actually be anything |
|
857 | return different dicts. The locals dictionary can actually be anything | |
858 | following the basic mapping protocol of a dict, but the globals dict |
|
858 | following the basic mapping protocol of a dict, but the globals dict | |
859 | must be a true dict, not even a subclass. It is recommended that any |
|
859 | must be a true dict, not even a subclass. It is recommended that any | |
860 | custom object for the locals namespace synchronize with the globals |
|
860 | custom object for the locals namespace synchronize with the globals | |
861 | dict somehow. |
|
861 | dict somehow. | |
862 |
|
862 | |||
863 | Raises TypeError if the provided globals namespace is not a true dict. |
|
863 | Raises TypeError if the provided globals namespace is not a true dict. | |
864 |
|
864 | |||
865 | Parameters |
|
865 | Parameters | |
866 | ---------- |
|
866 | ---------- | |
867 | user_ns : dict-like, optional |
|
867 | user_ns : dict-like, optional | |
868 | The current user namespace. The items in this namespace should |
|
868 | The current user namespace. The items in this namespace should | |
869 | be included in the output. If None, an appropriate blank |
|
869 | be included in the output. If None, an appropriate blank | |
870 | namespace should be created. |
|
870 | namespace should be created. | |
871 | user_global_ns : dict, optional |
|
871 | user_global_ns : dict, optional | |
872 | The current user global namespace. The items in this namespace |
|
872 | The current user global namespace. The items in this namespace | |
873 | should be included in the output. If None, an appropriate |
|
873 | should be included in the output. If None, an appropriate | |
874 | blank namespace should be created. |
|
874 | blank namespace should be created. | |
875 |
|
875 | |||
876 | Returns |
|
876 | Returns | |
877 | ------- |
|
877 | ------- | |
878 | A pair of dictionary-like object to be used as the local namespace |
|
878 | A pair of dictionary-like object to be used as the local namespace | |
879 | of the interpreter and a dict to be used as the global namespace. |
|
879 | of the interpreter and a dict to be used as the global namespace. | |
880 | """ |
|
880 | """ | |
881 |
|
881 | |||
882 |
|
882 | |||
883 | # We must ensure that __builtin__ (without the final 's') is always |
|
883 | # We must ensure that __builtin__ (without the final 's') is always | |
884 | # available and pointing to the __builtin__ *module*. For more details: |
|
884 | # available and pointing to the __builtin__ *module*. For more details: | |
885 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
885 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
886 |
|
886 | |||
887 | if user_ns is None: |
|
887 | if user_ns is None: | |
888 | # Set __name__ to __main__ to better match the behavior of the |
|
888 | # Set __name__ to __main__ to better match the behavior of the | |
889 | # normal interpreter. |
|
889 | # normal interpreter. | |
890 | user_ns = {'__name__' :'__main__', |
|
890 | user_ns = {'__name__' :'__main__', | |
891 | '__builtin__' : __builtin__, |
|
891 | '__builtin__' : __builtin__, | |
892 | '__builtins__' : __builtin__, |
|
892 | '__builtins__' : __builtin__, | |
893 | } |
|
893 | } | |
894 | else: |
|
894 | else: | |
895 | user_ns.setdefault('__name__','__main__') |
|
895 | user_ns.setdefault('__name__','__main__') | |
896 | user_ns.setdefault('__builtin__',__builtin__) |
|
896 | user_ns.setdefault('__builtin__',__builtin__) | |
897 | user_ns.setdefault('__builtins__',__builtin__) |
|
897 | user_ns.setdefault('__builtins__',__builtin__) | |
898 |
|
898 | |||
899 | if user_global_ns is None: |
|
899 | if user_global_ns is None: | |
900 | user_global_ns = user_ns |
|
900 | user_global_ns = user_ns | |
901 | if type(user_global_ns) is not dict: |
|
901 | if type(user_global_ns) is not dict: | |
902 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
902 | raise TypeError("user_global_ns must be a true dict; got %r" | |
903 | % type(user_global_ns)) |
|
903 | % type(user_global_ns)) | |
904 |
|
904 | |||
905 | return user_ns, user_global_ns |
|
905 | return user_ns, user_global_ns | |
906 |
|
906 | |||
907 | def init_sys_modules(self): |
|
907 | def init_sys_modules(self): | |
908 | # We need to insert into sys.modules something that looks like a |
|
908 | # We need to insert into sys.modules something that looks like a | |
909 | # module but which accesses the IPython namespace, for shelve and |
|
909 | # module but which accesses the IPython namespace, for shelve and | |
910 | # pickle to work interactively. Normally they rely on getting |
|
910 | # pickle to work interactively. Normally they rely on getting | |
911 | # everything out of __main__, but for embedding purposes each IPython |
|
911 | # everything out of __main__, but for embedding purposes each IPython | |
912 | # instance has its own private namespace, so we can't go shoving |
|
912 | # instance has its own private namespace, so we can't go shoving | |
913 | # everything into __main__. |
|
913 | # everything into __main__. | |
914 |
|
914 | |||
915 | # note, however, that we should only do this for non-embedded |
|
915 | # note, however, that we should only do this for non-embedded | |
916 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
916 | # ipythons, which really mimic the __main__.__dict__ with their own | |
917 | # namespace. Embedded instances, on the other hand, should not do |
|
917 | # namespace. Embedded instances, on the other hand, should not do | |
918 | # this because they need to manage the user local/global namespaces |
|
918 | # this because they need to manage the user local/global namespaces | |
919 | # only, but they live within a 'normal' __main__ (meaning, they |
|
919 | # only, but they live within a 'normal' __main__ (meaning, they | |
920 | # shouldn't overtake the execution environment of the script they're |
|
920 | # shouldn't overtake the execution environment of the script they're | |
921 | # embedded in). |
|
921 | # embedded in). | |
922 |
|
922 | |||
923 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
923 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
924 |
|
924 | |||
925 | try: |
|
925 | try: | |
926 | main_name = self.user_ns['__name__'] |
|
926 | main_name = self.user_ns['__name__'] | |
927 | except KeyError: |
|
927 | except KeyError: | |
928 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
928 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
929 | else: |
|
929 | else: | |
930 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
930 | sys.modules[main_name] = FakeModule(self.user_ns) | |
931 |
|
931 | |||
932 | def init_user_ns(self): |
|
932 | def init_user_ns(self): | |
933 | """Initialize all user-visible namespaces to their minimum defaults. |
|
933 | """Initialize all user-visible namespaces to their minimum defaults. | |
934 |
|
934 | |||
935 | Certain history lists are also initialized here, as they effectively |
|
935 | Certain history lists are also initialized here, as they effectively | |
936 | act as user namespaces. |
|
936 | act as user namespaces. | |
937 |
|
937 | |||
938 | Notes |
|
938 | Notes | |
939 | ----- |
|
939 | ----- | |
940 | All data structures here are only filled in, they are NOT reset by this |
|
940 | All data structures here are only filled in, they are NOT reset by this | |
941 | method. If they were not empty before, data will simply be added to |
|
941 | method. If they were not empty before, data will simply be added to | |
942 | therm. |
|
942 | therm. | |
943 | """ |
|
943 | """ | |
944 | # This function works in two parts: first we put a few things in |
|
944 | # This function works in two parts: first we put a few things in | |
945 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
945 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
946 | # initial variables aren't shown by %who. After the sync, we add the |
|
946 | # initial variables aren't shown by %who. After the sync, we add the | |
947 | # rest of what we *do* want the user to see with %who even on a new |
|
947 | # rest of what we *do* want the user to see with %who even on a new | |
948 | # session (probably nothing, so theye really only see their own stuff) |
|
948 | # session (probably nothing, so theye really only see their own stuff) | |
949 |
|
949 | |||
950 | # The user dict must *always* have a __builtin__ reference to the |
|
950 | # The user dict must *always* have a __builtin__ reference to the | |
951 | # Python standard __builtin__ namespace, which must be imported. |
|
951 | # Python standard __builtin__ namespace, which must be imported. | |
952 | # This is so that certain operations in prompt evaluation can be |
|
952 | # This is so that certain operations in prompt evaluation can be | |
953 | # reliably executed with builtins. Note that we can NOT use |
|
953 | # reliably executed with builtins. Note that we can NOT use | |
954 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
954 | # __builtins__ (note the 's'), because that can either be a dict or a | |
955 | # module, and can even mutate at runtime, depending on the context |
|
955 | # module, and can even mutate at runtime, depending on the context | |
956 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
956 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
957 | # always a module object, though it must be explicitly imported. |
|
957 | # always a module object, though it must be explicitly imported. | |
958 |
|
958 | |||
959 | # For more details: |
|
959 | # For more details: | |
960 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
960 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
961 | ns = dict(__builtin__ = __builtin__) |
|
961 | ns = dict(__builtin__ = __builtin__) | |
962 |
|
962 | |||
963 | # Put 'help' in the user namespace |
|
963 | # Put 'help' in the user namespace | |
964 | try: |
|
964 | try: | |
965 | from site import _Helper |
|
965 | from site import _Helper | |
966 | ns['help'] = _Helper() |
|
966 | ns['help'] = _Helper() | |
967 | except ImportError: |
|
967 | except ImportError: | |
968 | warn('help() not available - check site.py') |
|
968 | warn('help() not available - check site.py') | |
969 |
|
969 | |||
970 | # make global variables for user access to the histories |
|
970 | # make global variables for user access to the histories | |
971 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
971 | ns['_ih'] = self.history_manager.input_hist_parsed | |
972 | ns['_oh'] = self.history_manager.output_hist |
|
972 | ns['_oh'] = self.history_manager.output_hist | |
973 | ns['_dh'] = self.history_manager.dir_hist |
|
973 | ns['_dh'] = self.history_manager.dir_hist | |
974 |
|
974 | |||
975 | ns['_sh'] = shadowns |
|
975 | ns['_sh'] = shadowns | |
976 |
|
976 | |||
977 | # user aliases to input and output histories. These shouldn't show up |
|
977 | # user aliases to input and output histories. These shouldn't show up | |
978 | # in %who, as they can have very large reprs. |
|
978 | # in %who, as they can have very large reprs. | |
979 | ns['In'] = self.history_manager.input_hist_parsed |
|
979 | ns['In'] = self.history_manager.input_hist_parsed | |
980 | ns['Out'] = self.history_manager.output_hist |
|
980 | ns['Out'] = self.history_manager.output_hist | |
981 |
|
981 | |||
982 | # Store myself as the public api!!! |
|
982 | # Store myself as the public api!!! | |
983 | ns['get_ipython'] = self.get_ipython |
|
983 | ns['get_ipython'] = self.get_ipython | |
984 |
|
984 | |||
985 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
985 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
986 | # by %who |
|
986 | # by %who | |
987 | self.user_ns_hidden.update(ns) |
|
987 | self.user_ns_hidden.update(ns) | |
988 |
|
988 | |||
989 | # Anything put into ns now would show up in %who. Think twice before |
|
989 | # Anything put into ns now would show up in %who. Think twice before | |
990 | # putting anything here, as we really want %who to show the user their |
|
990 | # putting anything here, as we really want %who to show the user their | |
991 | # stuff, not our variables. |
|
991 | # stuff, not our variables. | |
992 |
|
992 | |||
993 | # Finally, update the real user's namespace |
|
993 | # Finally, update the real user's namespace | |
994 | self.user_ns.update(ns) |
|
994 | self.user_ns.update(ns) | |
995 |
|
995 | |||
996 | def reset(self): |
|
996 | def reset(self): | |
997 | """Clear all internal namespaces. |
|
997 | """Clear all internal namespaces. | |
998 |
|
998 | |||
999 | Note that this is much more aggressive than %reset, since it clears |
|
999 | Note that this is much more aggressive than %reset, since it clears | |
1000 | fully all namespaces, as well as all input/output lists. |
|
1000 | fully all namespaces, as well as all input/output lists. | |
1001 | """ |
|
1001 | """ | |
1002 | # Clear histories |
|
1002 | # Clear histories | |
1003 | self.history_manager.reset() |
|
1003 | self.history_manager.reset() | |
1004 |
|
1004 | |||
1005 | # Reset counter used to index all histories |
|
1005 | # Reset counter used to index all histories | |
1006 | self.execution_count = 0 |
|
1006 | self.execution_count = 0 | |
1007 |
|
1007 | |||
1008 | # Restore the user namespaces to minimal usability |
|
1008 | # Restore the user namespaces to minimal usability | |
1009 | for ns in self.ns_refs_table: |
|
1009 | for ns in self.ns_refs_table: | |
1010 | ns.clear() |
|
1010 | ns.clear() | |
1011 |
|
1011 | |||
1012 | # The main execution namespaces must be cleared very carefully, |
|
1012 | # The main execution namespaces must be cleared very carefully, | |
1013 | # skipping the deletion of the builtin-related keys, because doing so |
|
1013 | # skipping the deletion of the builtin-related keys, because doing so | |
1014 | # would cause errors in many object's __del__ methods. |
|
1014 | # would cause errors in many object's __del__ methods. | |
1015 | for ns in [self.user_ns, self.user_global_ns]: |
|
1015 | for ns in [self.user_ns, self.user_global_ns]: | |
1016 | drop_keys = set(ns.keys()) |
|
1016 | drop_keys = set(ns.keys()) | |
1017 | drop_keys.discard('__builtin__') |
|
1017 | drop_keys.discard('__builtin__') | |
1018 | drop_keys.discard('__builtins__') |
|
1018 | drop_keys.discard('__builtins__') | |
1019 | for k in drop_keys: |
|
1019 | for k in drop_keys: | |
1020 | del ns[k] |
|
1020 | del ns[k] | |
1021 |
|
1021 | |||
1022 | # Restore the user namespaces to minimal usability |
|
1022 | # Restore the user namespaces to minimal usability | |
1023 | self.init_user_ns() |
|
1023 | self.init_user_ns() | |
1024 |
|
1024 | |||
1025 | # Restore the default and user aliases |
|
1025 | # Restore the default and user aliases | |
1026 | self.alias_manager.clear_aliases() |
|
1026 | self.alias_manager.clear_aliases() | |
1027 | self.alias_manager.init_aliases() |
|
1027 | self.alias_manager.init_aliases() | |
1028 |
|
1028 | |||
1029 | def reset_selective(self, regex=None): |
|
1029 | def reset_selective(self, regex=None): | |
1030 | """Clear selective variables from internal namespaces based on a |
|
1030 | """Clear selective variables from internal namespaces based on a | |
1031 | specified regular expression. |
|
1031 | specified regular expression. | |
1032 |
|
1032 | |||
1033 | Parameters |
|
1033 | Parameters | |
1034 | ---------- |
|
1034 | ---------- | |
1035 | regex : string or compiled pattern, optional |
|
1035 | regex : string or compiled pattern, optional | |
1036 | A regular expression pattern that will be used in searching |
|
1036 | A regular expression pattern that will be used in searching | |
1037 | variable names in the users namespaces. |
|
1037 | variable names in the users namespaces. | |
1038 | """ |
|
1038 | """ | |
1039 | if regex is not None: |
|
1039 | if regex is not None: | |
1040 | try: |
|
1040 | try: | |
1041 | m = re.compile(regex) |
|
1041 | m = re.compile(regex) | |
1042 | except TypeError: |
|
1042 | except TypeError: | |
1043 | raise TypeError('regex must be a string or compiled pattern') |
|
1043 | raise TypeError('regex must be a string or compiled pattern') | |
1044 | # Search for keys in each namespace that match the given regex |
|
1044 | # Search for keys in each namespace that match the given regex | |
1045 | # If a match is found, delete the key/value pair. |
|
1045 | # If a match is found, delete the key/value pair. | |
1046 | for ns in self.ns_refs_table: |
|
1046 | for ns in self.ns_refs_table: | |
1047 | for var in ns: |
|
1047 | for var in ns: | |
1048 | if m.search(var): |
|
1048 | if m.search(var): | |
1049 | del ns[var] |
|
1049 | del ns[var] | |
1050 |
|
1050 | |||
1051 | def push(self, variables, interactive=True): |
|
1051 | def push(self, variables, interactive=True): | |
1052 | """Inject a group of variables into the IPython user namespace. |
|
1052 | """Inject a group of variables into the IPython user namespace. | |
1053 |
|
1053 | |||
1054 | Parameters |
|
1054 | Parameters | |
1055 | ---------- |
|
1055 | ---------- | |
1056 | variables : dict, str or list/tuple of str |
|
1056 | variables : dict, str or list/tuple of str | |
1057 | The variables to inject into the user's namespace. If a dict, a |
|
1057 | The variables to inject into the user's namespace. If a dict, a | |
1058 | simple update is done. If a str, the string is assumed to have |
|
1058 | simple update is done. If a str, the string is assumed to have | |
1059 | variable names separated by spaces. A list/tuple of str can also |
|
1059 | variable names separated by spaces. A list/tuple of str can also | |
1060 | be used to give the variable names. If just the variable names are |
|
1060 | be used to give the variable names. If just the variable names are | |
1061 | give (list/tuple/str) then the variable values looked up in the |
|
1061 | give (list/tuple/str) then the variable values looked up in the | |
1062 | callers frame. |
|
1062 | callers frame. | |
1063 | interactive : bool |
|
1063 | interactive : bool | |
1064 | If True (default), the variables will be listed with the ``who`` |
|
1064 | If True (default), the variables will be listed with the ``who`` | |
1065 | magic. |
|
1065 | magic. | |
1066 | """ |
|
1066 | """ | |
1067 | vdict = None |
|
1067 | vdict = None | |
1068 |
|
1068 | |||
1069 | # We need a dict of name/value pairs to do namespace updates. |
|
1069 | # We need a dict of name/value pairs to do namespace updates. | |
1070 | if isinstance(variables, dict): |
|
1070 | if isinstance(variables, dict): | |
1071 | vdict = variables |
|
1071 | vdict = variables | |
1072 | elif isinstance(variables, (basestring, list, tuple)): |
|
1072 | elif isinstance(variables, (basestring, list, tuple)): | |
1073 | if isinstance(variables, basestring): |
|
1073 | if isinstance(variables, basestring): | |
1074 | vlist = variables.split() |
|
1074 | vlist = variables.split() | |
1075 | else: |
|
1075 | else: | |
1076 | vlist = variables |
|
1076 | vlist = variables | |
1077 | vdict = {} |
|
1077 | vdict = {} | |
1078 | cf = sys._getframe(1) |
|
1078 | cf = sys._getframe(1) | |
1079 | for name in vlist: |
|
1079 | for name in vlist: | |
1080 | try: |
|
1080 | try: | |
1081 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1081 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1082 | except: |
|
1082 | except: | |
1083 | print ('Could not get variable %s from %s' % |
|
1083 | print ('Could not get variable %s from %s' % | |
1084 | (name,cf.f_code.co_name)) |
|
1084 | (name,cf.f_code.co_name)) | |
1085 | else: |
|
1085 | else: | |
1086 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1086 | raise ValueError('variables must be a dict/str/list/tuple') | |
1087 |
|
1087 | |||
1088 | # Propagate variables to user namespace |
|
1088 | # Propagate variables to user namespace | |
1089 | self.user_ns.update(vdict) |
|
1089 | self.user_ns.update(vdict) | |
1090 |
|
1090 | |||
1091 | # And configure interactive visibility |
|
1091 | # And configure interactive visibility | |
1092 | config_ns = self.user_ns_hidden |
|
1092 | config_ns = self.user_ns_hidden | |
1093 | if interactive: |
|
1093 | if interactive: | |
1094 | for name, val in vdict.iteritems(): |
|
1094 | for name, val in vdict.iteritems(): | |
1095 | config_ns.pop(name, None) |
|
1095 | config_ns.pop(name, None) | |
1096 | else: |
|
1096 | else: | |
1097 | for name,val in vdict.iteritems(): |
|
1097 | for name,val in vdict.iteritems(): | |
1098 | config_ns[name] = val |
|
1098 | config_ns[name] = val | |
1099 |
|
1099 | |||
1100 | #------------------------------------------------------------------------- |
|
1100 | #------------------------------------------------------------------------- | |
1101 | # Things related to object introspection |
|
1101 | # Things related to object introspection | |
1102 | #------------------------------------------------------------------------- |
|
1102 | #------------------------------------------------------------------------- | |
1103 |
|
1103 | |||
1104 | def _ofind(self, oname, namespaces=None): |
|
1104 | def _ofind(self, oname, namespaces=None): | |
1105 | """Find an object in the available namespaces. |
|
1105 | """Find an object in the available namespaces. | |
1106 |
|
1106 | |||
1107 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1107 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1108 |
|
1108 | |||
1109 | Has special code to detect magic functions. |
|
1109 | Has special code to detect magic functions. | |
1110 | """ |
|
1110 | """ | |
1111 | #oname = oname.strip() |
|
1111 | #oname = oname.strip() | |
1112 | #print '1- oname: <%r>' % oname # dbg |
|
1112 | #print '1- oname: <%r>' % oname # dbg | |
1113 | try: |
|
1113 | try: | |
1114 | oname = oname.strip().encode('ascii') |
|
1114 | oname = oname.strip().encode('ascii') | |
1115 | #print '2- oname: <%r>' % oname # dbg |
|
1115 | #print '2- oname: <%r>' % oname # dbg | |
1116 | except UnicodeEncodeError: |
|
1116 | except UnicodeEncodeError: | |
1117 | print 'Python identifiers can only contain ascii characters.' |
|
1117 | print 'Python identifiers can only contain ascii characters.' | |
1118 | return dict(found=False) |
|
1118 | return dict(found=False) | |
1119 |
|
1119 | |||
1120 | alias_ns = None |
|
1120 | alias_ns = None | |
1121 | if namespaces is None: |
|
1121 | if namespaces is None: | |
1122 | # Namespaces to search in: |
|
1122 | # Namespaces to search in: | |
1123 | # Put them in a list. The order is important so that we |
|
1123 | # Put them in a list. The order is important so that we | |
1124 | # find things in the same order that Python finds them. |
|
1124 | # find things in the same order that Python finds them. | |
1125 | namespaces = [ ('Interactive', self.user_ns), |
|
1125 | namespaces = [ ('Interactive', self.user_ns), | |
1126 | ('IPython internal', self.internal_ns), |
|
1126 | ('IPython internal', self.internal_ns), | |
1127 | ('Python builtin', __builtin__.__dict__), |
|
1127 | ('Python builtin', __builtin__.__dict__), | |
1128 | ('Alias', self.alias_manager.alias_table), |
|
1128 | ('Alias', self.alias_manager.alias_table), | |
1129 | ] |
|
1129 | ] | |
1130 | alias_ns = self.alias_manager.alias_table |
|
1130 | alias_ns = self.alias_manager.alias_table | |
1131 |
|
1131 | |||
1132 | # initialize results to 'null' |
|
1132 | # initialize results to 'null' | |
1133 | found = False; obj = None; ospace = None; ds = None; |
|
1133 | found = False; obj = None; ospace = None; ds = None; | |
1134 | ismagic = False; isalias = False; parent = None |
|
1134 | ismagic = False; isalias = False; parent = None | |
1135 |
|
1135 | |||
1136 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1136 | # We need to special-case 'print', which as of python2.6 registers as a | |
1137 | # function but should only be treated as one if print_function was |
|
1137 | # function but should only be treated as one if print_function was | |
1138 | # loaded with a future import. In this case, just bail. |
|
1138 | # loaded with a future import. In this case, just bail. | |
1139 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1139 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1140 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1140 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1141 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1141 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1142 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1142 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1143 |
|
1143 | |||
1144 | # Look for the given name by splitting it in parts. If the head is |
|
1144 | # Look for the given name by splitting it in parts. If the head is | |
1145 | # found, then we look for all the remaining parts as members, and only |
|
1145 | # found, then we look for all the remaining parts as members, and only | |
1146 | # declare success if we can find them all. |
|
1146 | # declare success if we can find them all. | |
1147 | oname_parts = oname.split('.') |
|
1147 | oname_parts = oname.split('.') | |
1148 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1148 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1149 | for nsname,ns in namespaces: |
|
1149 | for nsname,ns in namespaces: | |
1150 | try: |
|
1150 | try: | |
1151 | obj = ns[oname_head] |
|
1151 | obj = ns[oname_head] | |
1152 | except KeyError: |
|
1152 | except KeyError: | |
1153 | continue |
|
1153 | continue | |
1154 | else: |
|
1154 | else: | |
1155 | #print 'oname_rest:', oname_rest # dbg |
|
1155 | #print 'oname_rest:', oname_rest # dbg | |
1156 | for part in oname_rest: |
|
1156 | for part in oname_rest: | |
1157 | try: |
|
1157 | try: | |
1158 | parent = obj |
|
1158 | parent = obj | |
1159 | obj = getattr(obj,part) |
|
1159 | obj = getattr(obj,part) | |
1160 | except: |
|
1160 | except: | |
1161 | # Blanket except b/c some badly implemented objects |
|
1161 | # Blanket except b/c some badly implemented objects | |
1162 | # allow __getattr__ to raise exceptions other than |
|
1162 | # allow __getattr__ to raise exceptions other than | |
1163 | # AttributeError, which then crashes IPython. |
|
1163 | # AttributeError, which then crashes IPython. | |
1164 | break |
|
1164 | break | |
1165 | else: |
|
1165 | else: | |
1166 | # If we finish the for loop (no break), we got all members |
|
1166 | # If we finish the for loop (no break), we got all members | |
1167 | found = True |
|
1167 | found = True | |
1168 | ospace = nsname |
|
1168 | ospace = nsname | |
1169 | if ns == alias_ns: |
|
1169 | if ns == alias_ns: | |
1170 | isalias = True |
|
1170 | isalias = True | |
1171 | break # namespace loop |
|
1171 | break # namespace loop | |
1172 |
|
1172 | |||
1173 | # Try to see if it's magic |
|
1173 | # Try to see if it's magic | |
1174 | if not found: |
|
1174 | if not found: | |
1175 | if oname.startswith(ESC_MAGIC): |
|
1175 | if oname.startswith(ESC_MAGIC): | |
1176 | oname = oname[1:] |
|
1176 | oname = oname[1:] | |
1177 | obj = getattr(self,'magic_'+oname,None) |
|
1177 | obj = getattr(self,'magic_'+oname,None) | |
1178 | if obj is not None: |
|
1178 | if obj is not None: | |
1179 | found = True |
|
1179 | found = True | |
1180 | ospace = 'IPython internal' |
|
1180 | ospace = 'IPython internal' | |
1181 | ismagic = True |
|
1181 | ismagic = True | |
1182 |
|
1182 | |||
1183 | # Last try: special-case some literals like '', [], {}, etc: |
|
1183 | # Last try: special-case some literals like '', [], {}, etc: | |
1184 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1184 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1185 | obj = eval(oname_head) |
|
1185 | obj = eval(oname_head) | |
1186 | found = True |
|
1186 | found = True | |
1187 | ospace = 'Interactive' |
|
1187 | ospace = 'Interactive' | |
1188 |
|
1188 | |||
1189 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1189 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1190 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1190 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1191 |
|
1191 | |||
1192 | def _ofind_property(self, oname, info): |
|
1192 | def _ofind_property(self, oname, info): | |
1193 | """Second part of object finding, to look for property details.""" |
|
1193 | """Second part of object finding, to look for property details.""" | |
1194 | if info.found: |
|
1194 | if info.found: | |
1195 | # Get the docstring of the class property if it exists. |
|
1195 | # Get the docstring of the class property if it exists. | |
1196 | path = oname.split('.') |
|
1196 | path = oname.split('.') | |
1197 | root = '.'.join(path[:-1]) |
|
1197 | root = '.'.join(path[:-1]) | |
1198 | if info.parent is not None: |
|
1198 | if info.parent is not None: | |
1199 | try: |
|
1199 | try: | |
1200 | target = getattr(info.parent, '__class__') |
|
1200 | target = getattr(info.parent, '__class__') | |
1201 | # The object belongs to a class instance. |
|
1201 | # The object belongs to a class instance. | |
1202 | try: |
|
1202 | try: | |
1203 | target = getattr(target, path[-1]) |
|
1203 | target = getattr(target, path[-1]) | |
1204 | # The class defines the object. |
|
1204 | # The class defines the object. | |
1205 | if isinstance(target, property): |
|
1205 | if isinstance(target, property): | |
1206 | oname = root + '.__class__.' + path[-1] |
|
1206 | oname = root + '.__class__.' + path[-1] | |
1207 | info = Struct(self._ofind(oname)) |
|
1207 | info = Struct(self._ofind(oname)) | |
1208 | except AttributeError: pass |
|
1208 | except AttributeError: pass | |
1209 | except AttributeError: pass |
|
1209 | except AttributeError: pass | |
1210 |
|
1210 | |||
1211 | # We return either the new info or the unmodified input if the object |
|
1211 | # We return either the new info or the unmodified input if the object | |
1212 | # hadn't been found |
|
1212 | # hadn't been found | |
1213 | return info |
|
1213 | return info | |
1214 |
|
1214 | |||
1215 | def _object_find(self, oname, namespaces=None): |
|
1215 | def _object_find(self, oname, namespaces=None): | |
1216 | """Find an object and return a struct with info about it.""" |
|
1216 | """Find an object and return a struct with info about it.""" | |
1217 | inf = Struct(self._ofind(oname, namespaces)) |
|
1217 | inf = Struct(self._ofind(oname, namespaces)) | |
1218 | return Struct(self._ofind_property(oname, inf)) |
|
1218 | return Struct(self._ofind_property(oname, inf)) | |
1219 |
|
1219 | |||
1220 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1220 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1221 | """Generic interface to the inspector system. |
|
1221 | """Generic interface to the inspector system. | |
1222 |
|
1222 | |||
1223 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1223 | This function is meant to be called by pdef, pdoc & friends.""" | |
1224 | info = self._object_find(oname) |
|
1224 | info = self._object_find(oname) | |
1225 | if info.found: |
|
1225 | if info.found: | |
1226 | pmethod = getattr(self.inspector, meth) |
|
1226 | pmethod = getattr(self.inspector, meth) | |
1227 | formatter = format_screen if info.ismagic else None |
|
1227 | formatter = format_screen if info.ismagic else None | |
1228 | if meth == 'pdoc': |
|
1228 | if meth == 'pdoc': | |
1229 | pmethod(info.obj, oname, formatter) |
|
1229 | pmethod(info.obj, oname, formatter) | |
1230 | elif meth == 'pinfo': |
|
1230 | elif meth == 'pinfo': | |
1231 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1231 | pmethod(info.obj, oname, formatter, info, **kw) | |
1232 | else: |
|
1232 | else: | |
1233 | pmethod(info.obj, oname) |
|
1233 | pmethod(info.obj, oname) | |
1234 | else: |
|
1234 | else: | |
1235 | print 'Object `%s` not found.' % oname |
|
1235 | print 'Object `%s` not found.' % oname | |
1236 | return 'not found' # so callers can take other action |
|
1236 | return 'not found' # so callers can take other action | |
1237 |
|
1237 | |||
1238 | def object_inspect(self, oname): |
|
1238 | def object_inspect(self, oname): | |
1239 | info = self._object_find(oname) |
|
1239 | info = self._object_find(oname) | |
1240 | if info.found: |
|
1240 | if info.found: | |
1241 | return self.inspector.info(info.obj, oname, info=info) |
|
1241 | return self.inspector.info(info.obj, oname, info=info) | |
1242 | else: |
|
1242 | else: | |
1243 | return oinspect.object_info(name=oname, found=False) |
|
1243 | return oinspect.object_info(name=oname, found=False) | |
1244 |
|
1244 | |||
1245 | #------------------------------------------------------------------------- |
|
1245 | #------------------------------------------------------------------------- | |
1246 | # Things related to history management |
|
1246 | # Things related to history management | |
1247 | #------------------------------------------------------------------------- |
|
1247 | #------------------------------------------------------------------------- | |
1248 |
|
1248 | |||
1249 | def init_history(self): |
|
1249 | def init_history(self): | |
1250 | """Sets up the command history, and starts regular autosaves.""" |
|
1250 | """Sets up the command history, and starts regular autosaves.""" | |
1251 | self.history_manager = HistoryManager(shell=self) |
|
1251 | self.history_manager = HistoryManager(shell=self, load_history=True) | |
1252 |
|
1252 | |||
1253 | def save_history(self): |
|
1253 | def save_history(self): | |
1254 | """Save input history to a file (via readline library).""" |
|
1254 | """Save input history to a file (via readline library).""" | |
1255 | self.history_manager.save_history() |
|
1255 | self.history_manager.save_history() | |
1256 |
|
1256 | |||
1257 | def reload_history(self): |
|
1257 | def reload_history(self): | |
1258 | """Reload the input history from disk file.""" |
|
1258 | """Reload the input history from disk file.""" | |
1259 | self.history_manager.reload_history() |
|
1259 | self.history_manager.reload_history() | |
1260 |
|
1260 | |||
1261 | def history_saving_wrapper(self, func): |
|
1261 | def history_saving_wrapper(self, func): | |
1262 | """ Wrap func for readline history saving |
|
1262 | """ Wrap func for readline history saving | |
1263 |
|
1263 | |||
1264 | Convert func into callable that saves & restores |
|
1264 | Convert func into callable that saves & restores | |
1265 | history around the call """ |
|
1265 | history around the call """ | |
1266 |
|
1266 | |||
1267 | if self.has_readline: |
|
1267 | if self.has_readline: | |
1268 | from IPython.utils import rlineimpl as readline |
|
1268 | from IPython.utils import rlineimpl as readline | |
1269 | else: |
|
1269 | else: | |
1270 | return func |
|
1270 | return func | |
1271 |
|
1271 | |||
1272 | def wrapper(): |
|
1272 | def wrapper(): | |
1273 | self.save_history() |
|
1273 | self.save_history() | |
1274 | try: |
|
1274 | try: | |
1275 | func() |
|
1275 | func() | |
1276 | finally: |
|
1276 | finally: | |
1277 | self.reload_history() |
|
1277 | self.reload_history() | |
1278 | return wrapper |
|
1278 | return wrapper | |
1279 |
|
1279 | |||
1280 | def get_history(self, index=None, raw=False, output=True): |
|
1280 | def get_history(self, index=None, raw=False, output=True): | |
1281 | return self.history_manager.get_history(index, raw, output) |
|
1281 | return self.history_manager.get_history(index, raw, output) | |
1282 |
|
1282 | |||
1283 |
|
1283 | |||
1284 | #------------------------------------------------------------------------- |
|
1284 | #------------------------------------------------------------------------- | |
1285 | # Things related to exception handling and tracebacks (not debugging) |
|
1285 | # Things related to exception handling and tracebacks (not debugging) | |
1286 | #------------------------------------------------------------------------- |
|
1286 | #------------------------------------------------------------------------- | |
1287 |
|
1287 | |||
1288 | def init_traceback_handlers(self, custom_exceptions): |
|
1288 | def init_traceback_handlers(self, custom_exceptions): | |
1289 | # Syntax error handler. |
|
1289 | # Syntax error handler. | |
1290 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1290 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1291 |
|
1291 | |||
1292 | # The interactive one is initialized with an offset, meaning we always |
|
1292 | # The interactive one is initialized with an offset, meaning we always | |
1293 | # want to remove the topmost item in the traceback, which is our own |
|
1293 | # want to remove the topmost item in the traceback, which is our own | |
1294 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1294 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1295 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1295 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1296 | color_scheme='NoColor', |
|
1296 | color_scheme='NoColor', | |
1297 | tb_offset = 1, |
|
1297 | tb_offset = 1, | |
1298 | check_cache=self.compile.check_cache) |
|
1298 | check_cache=self.compile.check_cache) | |
1299 |
|
1299 | |||
1300 | # The instance will store a pointer to the system-wide exception hook, |
|
1300 | # The instance will store a pointer to the system-wide exception hook, | |
1301 | # so that runtime code (such as magics) can access it. This is because |
|
1301 | # so that runtime code (such as magics) can access it. This is because | |
1302 | # during the read-eval loop, it may get temporarily overwritten. |
|
1302 | # during the read-eval loop, it may get temporarily overwritten. | |
1303 | self.sys_excepthook = sys.excepthook |
|
1303 | self.sys_excepthook = sys.excepthook | |
1304 |
|
1304 | |||
1305 | # and add any custom exception handlers the user may have specified |
|
1305 | # and add any custom exception handlers the user may have specified | |
1306 | self.set_custom_exc(*custom_exceptions) |
|
1306 | self.set_custom_exc(*custom_exceptions) | |
1307 |
|
1307 | |||
1308 | # Set the exception mode |
|
1308 | # Set the exception mode | |
1309 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1309 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1310 |
|
1310 | |||
1311 | def set_custom_exc(self, exc_tuple, handler): |
|
1311 | def set_custom_exc(self, exc_tuple, handler): | |
1312 | """set_custom_exc(exc_tuple,handler) |
|
1312 | """set_custom_exc(exc_tuple,handler) | |
1313 |
|
1313 | |||
1314 | Set a custom exception handler, which will be called if any of the |
|
1314 | Set a custom exception handler, which will be called if any of the | |
1315 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1315 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1316 | run_code() method. |
|
1316 | run_code() method. | |
1317 |
|
1317 | |||
1318 | Inputs: |
|
1318 | Inputs: | |
1319 |
|
1319 | |||
1320 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1320 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1321 | handler for. It is very important that you use a tuple, and NOT A |
|
1321 | handler for. It is very important that you use a tuple, and NOT A | |
1322 | LIST here, because of the way Python's except statement works. If |
|
1322 | LIST here, because of the way Python's except statement works. If | |
1323 | you only want to trap a single exception, use a singleton tuple: |
|
1323 | you only want to trap a single exception, use a singleton tuple: | |
1324 |
|
1324 | |||
1325 | exc_tuple == (MyCustomException,) |
|
1325 | exc_tuple == (MyCustomException,) | |
1326 |
|
1326 | |||
1327 | - handler: this must be defined as a function with the following |
|
1327 | - handler: this must be defined as a function with the following | |
1328 | basic interface:: |
|
1328 | basic interface:: | |
1329 |
|
1329 | |||
1330 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1330 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1331 | ... |
|
1331 | ... | |
1332 | # The return value must be |
|
1332 | # The return value must be | |
1333 | return structured_traceback |
|
1333 | return structured_traceback | |
1334 |
|
1334 | |||
1335 | This will be made into an instance method (via types.MethodType) |
|
1335 | This will be made into an instance method (via types.MethodType) | |
1336 | of IPython itself, and it will be called if any of the exceptions |
|
1336 | of IPython itself, and it will be called if any of the exceptions | |
1337 | listed in the exc_tuple are caught. If the handler is None, an |
|
1337 | listed in the exc_tuple are caught. If the handler is None, an | |
1338 | internal basic one is used, which just prints basic info. |
|
1338 | internal basic one is used, which just prints basic info. | |
1339 |
|
1339 | |||
1340 | WARNING: by putting in your own exception handler into IPython's main |
|
1340 | WARNING: by putting in your own exception handler into IPython's main | |
1341 | execution loop, you run a very good chance of nasty crashes. This |
|
1341 | execution loop, you run a very good chance of nasty crashes. This | |
1342 | facility should only be used if you really know what you are doing.""" |
|
1342 | facility should only be used if you really know what you are doing.""" | |
1343 |
|
1343 | |||
1344 | assert type(exc_tuple)==type(()) , \ |
|
1344 | assert type(exc_tuple)==type(()) , \ | |
1345 | "The custom exceptions must be given AS A TUPLE." |
|
1345 | "The custom exceptions must be given AS A TUPLE." | |
1346 |
|
1346 | |||
1347 | def dummy_handler(self,etype,value,tb): |
|
1347 | def dummy_handler(self,etype,value,tb): | |
1348 | print '*** Simple custom exception handler ***' |
|
1348 | print '*** Simple custom exception handler ***' | |
1349 | print 'Exception type :',etype |
|
1349 | print 'Exception type :',etype | |
1350 | print 'Exception value:',value |
|
1350 | print 'Exception value:',value | |
1351 | print 'Traceback :',tb |
|
1351 | print 'Traceback :',tb | |
1352 | print 'Source code :','\n'.join(self.buffer) |
|
1352 | print 'Source code :','\n'.join(self.buffer) | |
1353 |
|
1353 | |||
1354 | if handler is None: handler = dummy_handler |
|
1354 | if handler is None: handler = dummy_handler | |
1355 |
|
1355 | |||
1356 | self.CustomTB = types.MethodType(handler,self) |
|
1356 | self.CustomTB = types.MethodType(handler,self) | |
1357 | self.custom_exceptions = exc_tuple |
|
1357 | self.custom_exceptions = exc_tuple | |
1358 |
|
1358 | |||
1359 | def excepthook(self, etype, value, tb): |
|
1359 | def excepthook(self, etype, value, tb): | |
1360 | """One more defense for GUI apps that call sys.excepthook. |
|
1360 | """One more defense for GUI apps that call sys.excepthook. | |
1361 |
|
1361 | |||
1362 | GUI frameworks like wxPython trap exceptions and call |
|
1362 | GUI frameworks like wxPython trap exceptions and call | |
1363 | sys.excepthook themselves. I guess this is a feature that |
|
1363 | sys.excepthook themselves. I guess this is a feature that | |
1364 | enables them to keep running after exceptions that would |
|
1364 | enables them to keep running after exceptions that would | |
1365 | otherwise kill their mainloop. This is a bother for IPython |
|
1365 | otherwise kill their mainloop. This is a bother for IPython | |
1366 | which excepts to catch all of the program exceptions with a try: |
|
1366 | which excepts to catch all of the program exceptions with a try: | |
1367 | except: statement. |
|
1367 | except: statement. | |
1368 |
|
1368 | |||
1369 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1369 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1370 | any app directly invokes sys.excepthook, it will look to the user like |
|
1370 | any app directly invokes sys.excepthook, it will look to the user like | |
1371 | IPython crashed. In order to work around this, we can disable the |
|
1371 | IPython crashed. In order to work around this, we can disable the | |
1372 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1372 | CrashHandler and replace it with this excepthook instead, which prints a | |
1373 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1373 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1374 | call sys.excepthook will generate a regular-looking exception from |
|
1374 | call sys.excepthook will generate a regular-looking exception from | |
1375 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1375 | IPython, and the CrashHandler will only be triggered by real IPython | |
1376 | crashes. |
|
1376 | crashes. | |
1377 |
|
1377 | |||
1378 | This hook should be used sparingly, only in places which are not likely |
|
1378 | This hook should be used sparingly, only in places which are not likely | |
1379 | to be true IPython errors. |
|
1379 | to be true IPython errors. | |
1380 | """ |
|
1380 | """ | |
1381 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1381 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1382 |
|
1382 | |||
1383 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1383 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1384 | exception_only=False): |
|
1384 | exception_only=False): | |
1385 | """Display the exception that just occurred. |
|
1385 | """Display the exception that just occurred. | |
1386 |
|
1386 | |||
1387 | If nothing is known about the exception, this is the method which |
|
1387 | If nothing is known about the exception, this is the method which | |
1388 | should be used throughout the code for presenting user tracebacks, |
|
1388 | should be used throughout the code for presenting user tracebacks, | |
1389 | rather than directly invoking the InteractiveTB object. |
|
1389 | rather than directly invoking the InteractiveTB object. | |
1390 |
|
1390 | |||
1391 | A specific showsyntaxerror() also exists, but this method can take |
|
1391 | A specific showsyntaxerror() also exists, but this method can take | |
1392 | care of calling it if needed, so unless you are explicitly catching a |
|
1392 | care of calling it if needed, so unless you are explicitly catching a | |
1393 | SyntaxError exception, don't try to analyze the stack manually and |
|
1393 | SyntaxError exception, don't try to analyze the stack manually and | |
1394 | simply call this method.""" |
|
1394 | simply call this method.""" | |
1395 |
|
1395 | |||
1396 | try: |
|
1396 | try: | |
1397 | if exc_tuple is None: |
|
1397 | if exc_tuple is None: | |
1398 | etype, value, tb = sys.exc_info() |
|
1398 | etype, value, tb = sys.exc_info() | |
1399 | else: |
|
1399 | else: | |
1400 | etype, value, tb = exc_tuple |
|
1400 | etype, value, tb = exc_tuple | |
1401 |
|
1401 | |||
1402 | if etype is None: |
|
1402 | if etype is None: | |
1403 | if hasattr(sys, 'last_type'): |
|
1403 | if hasattr(sys, 'last_type'): | |
1404 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1404 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1405 | sys.last_traceback |
|
1405 | sys.last_traceback | |
1406 | else: |
|
1406 | else: | |
1407 | self.write_err('No traceback available to show.\n') |
|
1407 | self.write_err('No traceback available to show.\n') | |
1408 | return |
|
1408 | return | |
1409 |
|
1409 | |||
1410 | if etype is SyntaxError: |
|
1410 | if etype is SyntaxError: | |
1411 | # Though this won't be called by syntax errors in the input |
|
1411 | # Though this won't be called by syntax errors in the input | |
1412 | # line, there may be SyntaxError cases whith imported code. |
|
1412 | # line, there may be SyntaxError cases whith imported code. | |
1413 | self.showsyntaxerror(filename) |
|
1413 | self.showsyntaxerror(filename) | |
1414 | elif etype is UsageError: |
|
1414 | elif etype is UsageError: | |
1415 | print "UsageError:", value |
|
1415 | print "UsageError:", value | |
1416 | else: |
|
1416 | else: | |
1417 | # WARNING: these variables are somewhat deprecated and not |
|
1417 | # WARNING: these variables are somewhat deprecated and not | |
1418 | # necessarily safe to use in a threaded environment, but tools |
|
1418 | # necessarily safe to use in a threaded environment, but tools | |
1419 | # like pdb depend on their existence, so let's set them. If we |
|
1419 | # like pdb depend on their existence, so let's set them. If we | |
1420 | # find problems in the field, we'll need to revisit their use. |
|
1420 | # find problems in the field, we'll need to revisit their use. | |
1421 | sys.last_type = etype |
|
1421 | sys.last_type = etype | |
1422 | sys.last_value = value |
|
1422 | sys.last_value = value | |
1423 | sys.last_traceback = tb |
|
1423 | sys.last_traceback = tb | |
1424 |
|
1424 | |||
1425 | if etype in self.custom_exceptions: |
|
1425 | if etype in self.custom_exceptions: | |
1426 | # FIXME: Old custom traceback objects may just return a |
|
1426 | # FIXME: Old custom traceback objects may just return a | |
1427 | # string, in that case we just put it into a list |
|
1427 | # string, in that case we just put it into a list | |
1428 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1428 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1429 | if isinstance(ctb, basestring): |
|
1429 | if isinstance(ctb, basestring): | |
1430 | stb = [stb] |
|
1430 | stb = [stb] | |
1431 | else: |
|
1431 | else: | |
1432 | if exception_only: |
|
1432 | if exception_only: | |
1433 | stb = ['An exception has occurred, use %tb to see ' |
|
1433 | stb = ['An exception has occurred, use %tb to see ' | |
1434 | 'the full traceback.\n'] |
|
1434 | 'the full traceback.\n'] | |
1435 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1435 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1436 | value)) |
|
1436 | value)) | |
1437 | else: |
|
1437 | else: | |
1438 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1438 | stb = self.InteractiveTB.structured_traceback(etype, | |
1439 | value, tb, tb_offset=tb_offset) |
|
1439 | value, tb, tb_offset=tb_offset) | |
1440 | # FIXME: the pdb calling should be done by us, not by |
|
1440 | # FIXME: the pdb calling should be done by us, not by | |
1441 | # the code computing the traceback. |
|
1441 | # the code computing the traceback. | |
1442 | if self.InteractiveTB.call_pdb: |
|
1442 | if self.InteractiveTB.call_pdb: | |
1443 | # pdb mucks up readline, fix it back |
|
1443 | # pdb mucks up readline, fix it back | |
1444 | self.set_readline_completer() |
|
1444 | self.set_readline_completer() | |
1445 |
|
1445 | |||
1446 | # Actually show the traceback |
|
1446 | # Actually show the traceback | |
1447 | self._showtraceback(etype, value, stb) |
|
1447 | self._showtraceback(etype, value, stb) | |
1448 |
|
1448 | |||
1449 | except KeyboardInterrupt: |
|
1449 | except KeyboardInterrupt: | |
1450 | self.write_err("\nKeyboardInterrupt\n") |
|
1450 | self.write_err("\nKeyboardInterrupt\n") | |
1451 |
|
1451 | |||
1452 | def _showtraceback(self, etype, evalue, stb): |
|
1452 | def _showtraceback(self, etype, evalue, stb): | |
1453 | """Actually show a traceback. |
|
1453 | """Actually show a traceback. | |
1454 |
|
1454 | |||
1455 | Subclasses may override this method to put the traceback on a different |
|
1455 | Subclasses may override this method to put the traceback on a different | |
1456 | place, like a side channel. |
|
1456 | place, like a side channel. | |
1457 | """ |
|
1457 | """ | |
1458 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1458 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1459 |
|
1459 | |||
1460 | def showsyntaxerror(self, filename=None): |
|
1460 | def showsyntaxerror(self, filename=None): | |
1461 | """Display the syntax error that just occurred. |
|
1461 | """Display the syntax error that just occurred. | |
1462 |
|
1462 | |||
1463 | This doesn't display a stack trace because there isn't one. |
|
1463 | This doesn't display a stack trace because there isn't one. | |
1464 |
|
1464 | |||
1465 | If a filename is given, it is stuffed in the exception instead |
|
1465 | If a filename is given, it is stuffed in the exception instead | |
1466 | of what was there before (because Python's parser always uses |
|
1466 | of what was there before (because Python's parser always uses | |
1467 | "<string>" when reading from a string). |
|
1467 | "<string>" when reading from a string). | |
1468 | """ |
|
1468 | """ | |
1469 | etype, value, last_traceback = sys.exc_info() |
|
1469 | etype, value, last_traceback = sys.exc_info() | |
1470 |
|
1470 | |||
1471 | # See note about these variables in showtraceback() above |
|
1471 | # See note about these variables in showtraceback() above | |
1472 | sys.last_type = etype |
|
1472 | sys.last_type = etype | |
1473 | sys.last_value = value |
|
1473 | sys.last_value = value | |
1474 | sys.last_traceback = last_traceback |
|
1474 | sys.last_traceback = last_traceback | |
1475 |
|
1475 | |||
1476 | if filename and etype is SyntaxError: |
|
1476 | if filename and etype is SyntaxError: | |
1477 | # Work hard to stuff the correct filename in the exception |
|
1477 | # Work hard to stuff the correct filename in the exception | |
1478 | try: |
|
1478 | try: | |
1479 | msg, (dummy_filename, lineno, offset, line) = value |
|
1479 | msg, (dummy_filename, lineno, offset, line) = value | |
1480 | except: |
|
1480 | except: | |
1481 | # Not the format we expect; leave it alone |
|
1481 | # Not the format we expect; leave it alone | |
1482 | pass |
|
1482 | pass | |
1483 | else: |
|
1483 | else: | |
1484 | # Stuff in the right filename |
|
1484 | # Stuff in the right filename | |
1485 | try: |
|
1485 | try: | |
1486 | # Assume SyntaxError is a class exception |
|
1486 | # Assume SyntaxError is a class exception | |
1487 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1487 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1488 | except: |
|
1488 | except: | |
1489 | # If that failed, assume SyntaxError is a string |
|
1489 | # If that failed, assume SyntaxError is a string | |
1490 | value = msg, (filename, lineno, offset, line) |
|
1490 | value = msg, (filename, lineno, offset, line) | |
1491 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1491 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1492 | self._showtraceback(etype, value, stb) |
|
1492 | self._showtraceback(etype, value, stb) | |
1493 |
|
1493 | |||
1494 | #------------------------------------------------------------------------- |
|
1494 | #------------------------------------------------------------------------- | |
1495 | # Things related to readline |
|
1495 | # Things related to readline | |
1496 | #------------------------------------------------------------------------- |
|
1496 | #------------------------------------------------------------------------- | |
1497 |
|
1497 | |||
1498 | def init_readline(self): |
|
1498 | def init_readline(self): | |
1499 | """Command history completion/saving/reloading.""" |
|
1499 | """Command history completion/saving/reloading.""" | |
1500 |
|
1500 | |||
1501 | if self.readline_use: |
|
1501 | if self.readline_use: | |
1502 | import IPython.utils.rlineimpl as readline |
|
1502 | import IPython.utils.rlineimpl as readline | |
1503 |
|
1503 | |||
1504 | self.rl_next_input = None |
|
1504 | self.rl_next_input = None | |
1505 | self.rl_do_indent = False |
|
1505 | self.rl_do_indent = False | |
1506 |
|
1506 | |||
1507 | if not self.readline_use or not readline.have_readline: |
|
1507 | if not self.readline_use or not readline.have_readline: | |
1508 | self.has_readline = False |
|
1508 | self.has_readline = False | |
1509 | self.readline = None |
|
1509 | self.readline = None | |
1510 | # Set a number of methods that depend on readline to be no-op |
|
1510 | # Set a number of methods that depend on readline to be no-op | |
1511 | self.set_readline_completer = no_op |
|
1511 | self.set_readline_completer = no_op | |
1512 | self.set_custom_completer = no_op |
|
1512 | self.set_custom_completer = no_op | |
1513 | self.set_completer_frame = no_op |
|
1513 | self.set_completer_frame = no_op | |
1514 | warn('Readline services not available or not loaded.') |
|
1514 | warn('Readline services not available or not loaded.') | |
1515 | else: |
|
1515 | else: | |
1516 | self.has_readline = True |
|
1516 | self.has_readline = True | |
1517 | self.readline = readline |
|
1517 | self.readline = readline | |
1518 | sys.modules['readline'] = readline |
|
1518 | sys.modules['readline'] = readline | |
1519 |
|
1519 | |||
1520 | # Platform-specific configuration |
|
1520 | # Platform-specific configuration | |
1521 | if os.name == 'nt': |
|
1521 | if os.name == 'nt': | |
1522 | # FIXME - check with Frederick to see if we can harmonize |
|
1522 | # FIXME - check with Frederick to see if we can harmonize | |
1523 | # naming conventions with pyreadline to avoid this |
|
1523 | # naming conventions with pyreadline to avoid this | |
1524 | # platform-dependent check |
|
1524 | # platform-dependent check | |
1525 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1525 | self.readline_startup_hook = readline.set_pre_input_hook | |
1526 | else: |
|
1526 | else: | |
1527 | self.readline_startup_hook = readline.set_startup_hook |
|
1527 | self.readline_startup_hook = readline.set_startup_hook | |
1528 |
|
1528 | |||
1529 | # Load user's initrc file (readline config) |
|
1529 | # Load user's initrc file (readline config) | |
1530 | # Or if libedit is used, load editrc. |
|
1530 | # Or if libedit is used, load editrc. | |
1531 | inputrc_name = os.environ.get('INPUTRC') |
|
1531 | inputrc_name = os.environ.get('INPUTRC') | |
1532 | if inputrc_name is None: |
|
1532 | if inputrc_name is None: | |
1533 | home_dir = get_home_dir() |
|
1533 | home_dir = get_home_dir() | |
1534 | if home_dir is not None: |
|
1534 | if home_dir is not None: | |
1535 | inputrc_name = '.inputrc' |
|
1535 | inputrc_name = '.inputrc' | |
1536 | if readline.uses_libedit: |
|
1536 | if readline.uses_libedit: | |
1537 | inputrc_name = '.editrc' |
|
1537 | inputrc_name = '.editrc' | |
1538 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1538 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1539 | if os.path.isfile(inputrc_name): |
|
1539 | if os.path.isfile(inputrc_name): | |
1540 | try: |
|
1540 | try: | |
1541 | readline.read_init_file(inputrc_name) |
|
1541 | readline.read_init_file(inputrc_name) | |
1542 | except: |
|
1542 | except: | |
1543 | warn('Problems reading readline initialization file <%s>' |
|
1543 | warn('Problems reading readline initialization file <%s>' | |
1544 | % inputrc_name) |
|
1544 | % inputrc_name) | |
1545 |
|
1545 | |||
1546 | # Configure readline according to user's prefs |
|
1546 | # Configure readline according to user's prefs | |
1547 | # This is only done if GNU readline is being used. If libedit |
|
1547 | # This is only done if GNU readline is being used. If libedit | |
1548 | # is being used (as on Leopard) the readline config is |
|
1548 | # is being used (as on Leopard) the readline config is | |
1549 | # not run as the syntax for libedit is different. |
|
1549 | # not run as the syntax for libedit is different. | |
1550 | if not readline.uses_libedit: |
|
1550 | if not readline.uses_libedit: | |
1551 | for rlcommand in self.readline_parse_and_bind: |
|
1551 | for rlcommand in self.readline_parse_and_bind: | |
1552 | #print "loading rl:",rlcommand # dbg |
|
1552 | #print "loading rl:",rlcommand # dbg | |
1553 | readline.parse_and_bind(rlcommand) |
|
1553 | readline.parse_and_bind(rlcommand) | |
1554 |
|
1554 | |||
1555 | # Remove some chars from the delimiters list. If we encounter |
|
1555 | # Remove some chars from the delimiters list. If we encounter | |
1556 | # unicode chars, discard them. |
|
1556 | # unicode chars, discard them. | |
1557 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1557 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1558 | delims = delims.translate(None, self.readline_remove_delims) |
|
1558 | delims = delims.translate(None, self.readline_remove_delims) | |
1559 | delims = delims.replace(ESC_MAGIC, '') |
|
1559 | delims = delims.replace(ESC_MAGIC, '') | |
1560 | readline.set_completer_delims(delims) |
|
1560 | readline.set_completer_delims(delims) | |
1561 | # otherwise we end up with a monster history after a while: |
|
1561 | # otherwise we end up with a monster history after a while: | |
1562 | readline.set_history_length(self.history_length) |
|
1562 | readline.set_history_length(self.history_length) | |
1563 |
|
|
1563 | ||
1564 | #print '*** Reading readline history' # dbg |
|
1564 | self.history_manager.populate_readline_history() | |
1565 | self.reload_history() |
|
|||
1566 | except IOError: |
|
|||
1567 | pass # It doesn't exist yet. |
|
|||
1568 |
|
1565 | |||
1569 | # Configure auto-indent for all platforms |
|
1566 | # Configure auto-indent for all platforms | |
1570 | self.set_autoindent(self.autoindent) |
|
1567 | self.set_autoindent(self.autoindent) | |
1571 |
|
1568 | |||
1572 | def set_next_input(self, s): |
|
1569 | def set_next_input(self, s): | |
1573 | """ Sets the 'default' input string for the next command line. |
|
1570 | """ Sets the 'default' input string for the next command line. | |
1574 |
|
1571 | |||
1575 | Requires readline. |
|
1572 | Requires readline. | |
1576 |
|
1573 | |||
1577 | Example: |
|
1574 | Example: | |
1578 |
|
1575 | |||
1579 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1576 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1580 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1577 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1581 | """ |
|
1578 | """ | |
1582 |
|
1579 | |||
1583 | self.rl_next_input = s |
|
1580 | self.rl_next_input = s | |
1584 |
|
1581 | |||
1585 | # Maybe move this to the terminal subclass? |
|
1582 | # Maybe move this to the terminal subclass? | |
1586 | def pre_readline(self): |
|
1583 | def pre_readline(self): | |
1587 | """readline hook to be used at the start of each line. |
|
1584 | """readline hook to be used at the start of each line. | |
1588 |
|
1585 | |||
1589 | Currently it handles auto-indent only.""" |
|
1586 | Currently it handles auto-indent only.""" | |
1590 |
|
1587 | |||
1591 | if self.rl_do_indent: |
|
1588 | if self.rl_do_indent: | |
1592 | self.readline.insert_text(self._indent_current_str()) |
|
1589 | self.readline.insert_text(self._indent_current_str()) | |
1593 | if self.rl_next_input is not None: |
|
1590 | if self.rl_next_input is not None: | |
1594 | self.readline.insert_text(self.rl_next_input) |
|
1591 | self.readline.insert_text(self.rl_next_input) | |
1595 | self.rl_next_input = None |
|
1592 | self.rl_next_input = None | |
1596 |
|
1593 | |||
1597 | def _indent_current_str(self): |
|
1594 | def _indent_current_str(self): | |
1598 | """return the current level of indentation as a string""" |
|
1595 | """return the current level of indentation as a string""" | |
1599 | return self.input_splitter.indent_spaces * ' ' |
|
1596 | return self.input_splitter.indent_spaces * ' ' | |
1600 |
|
1597 | |||
1601 | #------------------------------------------------------------------------- |
|
1598 | #------------------------------------------------------------------------- | |
1602 | # Things related to text completion |
|
1599 | # Things related to text completion | |
1603 | #------------------------------------------------------------------------- |
|
1600 | #------------------------------------------------------------------------- | |
1604 |
|
1601 | |||
1605 | def init_completer(self): |
|
1602 | def init_completer(self): | |
1606 | """Initialize the completion machinery. |
|
1603 | """Initialize the completion machinery. | |
1607 |
|
1604 | |||
1608 | This creates completion machinery that can be used by client code, |
|
1605 | This creates completion machinery that can be used by client code, | |
1609 | either interactively in-process (typically triggered by the readline |
|
1606 | either interactively in-process (typically triggered by the readline | |
1610 | library), programatically (such as in test suites) or out-of-prcess |
|
1607 | library), programatically (such as in test suites) or out-of-prcess | |
1611 | (typically over the network by remote frontends). |
|
1608 | (typically over the network by remote frontends). | |
1612 | """ |
|
1609 | """ | |
1613 | from IPython.core.completer import IPCompleter |
|
1610 | from IPython.core.completer import IPCompleter | |
1614 | from IPython.core.completerlib import (module_completer, |
|
1611 | from IPython.core.completerlib import (module_completer, | |
1615 | magic_run_completer, cd_completer) |
|
1612 | magic_run_completer, cd_completer) | |
1616 |
|
1613 | |||
1617 | self.Completer = IPCompleter(self, |
|
1614 | self.Completer = IPCompleter(self, | |
1618 | self.user_ns, |
|
1615 | self.user_ns, | |
1619 | self.user_global_ns, |
|
1616 | self.user_global_ns, | |
1620 | self.readline_omit__names, |
|
1617 | self.readline_omit__names, | |
1621 | self.alias_manager.alias_table, |
|
1618 | self.alias_manager.alias_table, | |
1622 | self.has_readline) |
|
1619 | self.has_readline) | |
1623 |
|
1620 | |||
1624 | # Add custom completers to the basic ones built into IPCompleter |
|
1621 | # Add custom completers to the basic ones built into IPCompleter | |
1625 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1622 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1626 | self.strdispatchers['complete_command'] = sdisp |
|
1623 | self.strdispatchers['complete_command'] = sdisp | |
1627 | self.Completer.custom_completers = sdisp |
|
1624 | self.Completer.custom_completers = sdisp | |
1628 |
|
1625 | |||
1629 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1626 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1630 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1627 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1631 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1628 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1632 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1629 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1633 |
|
1630 | |||
1634 | # Only configure readline if we truly are using readline. IPython can |
|
1631 | # Only configure readline if we truly are using readline. IPython can | |
1635 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1632 | # do tab-completion over the network, in GUIs, etc, where readline | |
1636 | # itself may be absent |
|
1633 | # itself may be absent | |
1637 | if self.has_readline: |
|
1634 | if self.has_readline: | |
1638 | self.set_readline_completer() |
|
1635 | self.set_readline_completer() | |
1639 |
|
1636 | |||
1640 | def complete(self, text, line=None, cursor_pos=None): |
|
1637 | def complete(self, text, line=None, cursor_pos=None): | |
1641 | """Return the completed text and a list of completions. |
|
1638 | """Return the completed text and a list of completions. | |
1642 |
|
1639 | |||
1643 | Parameters |
|
1640 | Parameters | |
1644 | ---------- |
|
1641 | ---------- | |
1645 |
|
1642 | |||
1646 | text : string |
|
1643 | text : string | |
1647 | A string of text to be completed on. It can be given as empty and |
|
1644 | A string of text to be completed on. It can be given as empty and | |
1648 | instead a line/position pair are given. In this case, the |
|
1645 | instead a line/position pair are given. In this case, the | |
1649 | completer itself will split the line like readline does. |
|
1646 | completer itself will split the line like readline does. | |
1650 |
|
1647 | |||
1651 | line : string, optional |
|
1648 | line : string, optional | |
1652 | The complete line that text is part of. |
|
1649 | The complete line that text is part of. | |
1653 |
|
1650 | |||
1654 | cursor_pos : int, optional |
|
1651 | cursor_pos : int, optional | |
1655 | The position of the cursor on the input line. |
|
1652 | The position of the cursor on the input line. | |
1656 |
|
1653 | |||
1657 | Returns |
|
1654 | Returns | |
1658 | ------- |
|
1655 | ------- | |
1659 | text : string |
|
1656 | text : string | |
1660 | The actual text that was completed. |
|
1657 | The actual text that was completed. | |
1661 |
|
1658 | |||
1662 | matches : list |
|
1659 | matches : list | |
1663 | A sorted list with all possible completions. |
|
1660 | A sorted list with all possible completions. | |
1664 |
|
1661 | |||
1665 | The optional arguments allow the completion to take more context into |
|
1662 | The optional arguments allow the completion to take more context into | |
1666 | account, and are part of the low-level completion API. |
|
1663 | account, and are part of the low-level completion API. | |
1667 |
|
1664 | |||
1668 | This is a wrapper around the completion mechanism, similar to what |
|
1665 | This is a wrapper around the completion mechanism, similar to what | |
1669 | readline does at the command line when the TAB key is hit. By |
|
1666 | readline does at the command line when the TAB key is hit. By | |
1670 | exposing it as a method, it can be used by other non-readline |
|
1667 | exposing it as a method, it can be used by other non-readline | |
1671 | environments (such as GUIs) for text completion. |
|
1668 | environments (such as GUIs) for text completion. | |
1672 |
|
1669 | |||
1673 | Simple usage example: |
|
1670 | Simple usage example: | |
1674 |
|
1671 | |||
1675 | In [1]: x = 'hello' |
|
1672 | In [1]: x = 'hello' | |
1676 |
|
1673 | |||
1677 | In [2]: _ip.complete('x.l') |
|
1674 | In [2]: _ip.complete('x.l') | |
1678 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1675 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1679 | """ |
|
1676 | """ | |
1680 |
|
1677 | |||
1681 | # Inject names into __builtin__ so we can complete on the added names. |
|
1678 | # Inject names into __builtin__ so we can complete on the added names. | |
1682 | with self.builtin_trap: |
|
1679 | with self.builtin_trap: | |
1683 | return self.Completer.complete(text, line, cursor_pos) |
|
1680 | return self.Completer.complete(text, line, cursor_pos) | |
1684 |
|
1681 | |||
1685 | def set_custom_completer(self, completer, pos=0): |
|
1682 | def set_custom_completer(self, completer, pos=0): | |
1686 | """Adds a new custom completer function. |
|
1683 | """Adds a new custom completer function. | |
1687 |
|
1684 | |||
1688 | The position argument (defaults to 0) is the index in the completers |
|
1685 | The position argument (defaults to 0) is the index in the completers | |
1689 | list where you want the completer to be inserted.""" |
|
1686 | list where you want the completer to be inserted.""" | |
1690 |
|
1687 | |||
1691 | newcomp = types.MethodType(completer,self.Completer) |
|
1688 | newcomp = types.MethodType(completer,self.Completer) | |
1692 | self.Completer.matchers.insert(pos,newcomp) |
|
1689 | self.Completer.matchers.insert(pos,newcomp) | |
1693 |
|
1690 | |||
1694 | def set_readline_completer(self): |
|
1691 | def set_readline_completer(self): | |
1695 | """Reset readline's completer to be our own.""" |
|
1692 | """Reset readline's completer to be our own.""" | |
1696 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1693 | self.readline.set_completer(self.Completer.rlcomplete) | |
1697 |
|
1694 | |||
1698 | def set_completer_frame(self, frame=None): |
|
1695 | def set_completer_frame(self, frame=None): | |
1699 | """Set the frame of the completer.""" |
|
1696 | """Set the frame of the completer.""" | |
1700 | if frame: |
|
1697 | if frame: | |
1701 | self.Completer.namespace = frame.f_locals |
|
1698 | self.Completer.namespace = frame.f_locals | |
1702 | self.Completer.global_namespace = frame.f_globals |
|
1699 | self.Completer.global_namespace = frame.f_globals | |
1703 | else: |
|
1700 | else: | |
1704 | self.Completer.namespace = self.user_ns |
|
1701 | self.Completer.namespace = self.user_ns | |
1705 | self.Completer.global_namespace = self.user_global_ns |
|
1702 | self.Completer.global_namespace = self.user_global_ns | |
1706 |
|
1703 | |||
1707 | #------------------------------------------------------------------------- |
|
1704 | #------------------------------------------------------------------------- | |
1708 | # Things related to magics |
|
1705 | # Things related to magics | |
1709 | #------------------------------------------------------------------------- |
|
1706 | #------------------------------------------------------------------------- | |
1710 |
|
1707 | |||
1711 | def init_magics(self): |
|
1708 | def init_magics(self): | |
1712 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1709 | # FIXME: Move the color initialization to the DisplayHook, which | |
1713 | # should be split into a prompt manager and displayhook. We probably |
|
1710 | # should be split into a prompt manager and displayhook. We probably | |
1714 | # even need a centralize colors management object. |
|
1711 | # even need a centralize colors management object. | |
1715 | self.magic_colors(self.colors) |
|
1712 | self.magic_colors(self.colors) | |
1716 | # History was moved to a separate module |
|
1713 | # History was moved to a separate module | |
1717 | from . import history |
|
1714 | from . import history | |
1718 | history.init_ipython(self) |
|
1715 | history.init_ipython(self) | |
1719 |
|
1716 | |||
1720 | def magic(self,arg_s): |
|
1717 | def magic(self,arg_s): | |
1721 | """Call a magic function by name. |
|
1718 | """Call a magic function by name. | |
1722 |
|
1719 | |||
1723 | Input: a string containing the name of the magic function to call and |
|
1720 | Input: a string containing the name of the magic function to call and | |
1724 | any additional arguments to be passed to the magic. |
|
1721 | any additional arguments to be passed to the magic. | |
1725 |
|
1722 | |||
1726 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1723 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1727 | prompt: |
|
1724 | prompt: | |
1728 |
|
1725 | |||
1729 | In[1]: %name -opt foo bar |
|
1726 | In[1]: %name -opt foo bar | |
1730 |
|
1727 | |||
1731 | To call a magic without arguments, simply use magic('name'). |
|
1728 | To call a magic without arguments, simply use magic('name'). | |
1732 |
|
1729 | |||
1733 | This provides a proper Python function to call IPython's magics in any |
|
1730 | This provides a proper Python function to call IPython's magics in any | |
1734 | valid Python code you can type at the interpreter, including loops and |
|
1731 | valid Python code you can type at the interpreter, including loops and | |
1735 | compound statements. |
|
1732 | compound statements. | |
1736 | """ |
|
1733 | """ | |
1737 | args = arg_s.split(' ',1) |
|
1734 | args = arg_s.split(' ',1) | |
1738 | magic_name = args[0] |
|
1735 | magic_name = args[0] | |
1739 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1736 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1740 |
|
1737 | |||
1741 | try: |
|
1738 | try: | |
1742 | magic_args = args[1] |
|
1739 | magic_args = args[1] | |
1743 | except IndexError: |
|
1740 | except IndexError: | |
1744 | magic_args = '' |
|
1741 | magic_args = '' | |
1745 | fn = getattr(self,'magic_'+magic_name,None) |
|
1742 | fn = getattr(self,'magic_'+magic_name,None) | |
1746 | if fn is None: |
|
1743 | if fn is None: | |
1747 | error("Magic function `%s` not found." % magic_name) |
|
1744 | error("Magic function `%s` not found." % magic_name) | |
1748 | else: |
|
1745 | else: | |
1749 | magic_args = self.var_expand(magic_args,1) |
|
1746 | magic_args = self.var_expand(magic_args,1) | |
1750 | with nested(self.builtin_trap,): |
|
1747 | with nested(self.builtin_trap,): | |
1751 | result = fn(magic_args) |
|
1748 | result = fn(magic_args) | |
1752 | return result |
|
1749 | return result | |
1753 |
|
1750 | |||
1754 | def define_magic(self, magicname, func): |
|
1751 | def define_magic(self, magicname, func): | |
1755 | """Expose own function as magic function for ipython |
|
1752 | """Expose own function as magic function for ipython | |
1756 |
|
1753 | |||
1757 | def foo_impl(self,parameter_s=''): |
|
1754 | def foo_impl(self,parameter_s=''): | |
1758 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1755 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1759 | print 'Magic function. Passed parameter is between < >:' |
|
1756 | print 'Magic function. Passed parameter is between < >:' | |
1760 | print '<%s>' % parameter_s |
|
1757 | print '<%s>' % parameter_s | |
1761 | print 'The self object is:',self |
|
1758 | print 'The self object is:',self | |
1762 |
|
1759 | |||
1763 | self.define_magic('foo',foo_impl) |
|
1760 | self.define_magic('foo',foo_impl) | |
1764 | """ |
|
1761 | """ | |
1765 |
|
1762 | |||
1766 | import new |
|
1763 | import new | |
1767 | im = types.MethodType(func,self) |
|
1764 | im = types.MethodType(func,self) | |
1768 | old = getattr(self, "magic_" + magicname, None) |
|
1765 | old = getattr(self, "magic_" + magicname, None) | |
1769 | setattr(self, "magic_" + magicname, im) |
|
1766 | setattr(self, "magic_" + magicname, im) | |
1770 | return old |
|
1767 | return old | |
1771 |
|
1768 | |||
1772 | #------------------------------------------------------------------------- |
|
1769 | #------------------------------------------------------------------------- | |
1773 | # Things related to macros |
|
1770 | # Things related to macros | |
1774 | #------------------------------------------------------------------------- |
|
1771 | #------------------------------------------------------------------------- | |
1775 |
|
1772 | |||
1776 | def define_macro(self, name, themacro): |
|
1773 | def define_macro(self, name, themacro): | |
1777 | """Define a new macro |
|
1774 | """Define a new macro | |
1778 |
|
1775 | |||
1779 | Parameters |
|
1776 | Parameters | |
1780 | ---------- |
|
1777 | ---------- | |
1781 | name : str |
|
1778 | name : str | |
1782 | The name of the macro. |
|
1779 | The name of the macro. | |
1783 | themacro : str or Macro |
|
1780 | themacro : str or Macro | |
1784 | The action to do upon invoking the macro. If a string, a new |
|
1781 | The action to do upon invoking the macro. If a string, a new | |
1785 | Macro object is created by passing the string to it. |
|
1782 | Macro object is created by passing the string to it. | |
1786 | """ |
|
1783 | """ | |
1787 |
|
1784 | |||
1788 | from IPython.core import macro |
|
1785 | from IPython.core import macro | |
1789 |
|
1786 | |||
1790 | if isinstance(themacro, basestring): |
|
1787 | if isinstance(themacro, basestring): | |
1791 | themacro = macro.Macro(themacro) |
|
1788 | themacro = macro.Macro(themacro) | |
1792 | if not isinstance(themacro, macro.Macro): |
|
1789 | if not isinstance(themacro, macro.Macro): | |
1793 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1790 | raise ValueError('A macro must be a string or a Macro instance.') | |
1794 | self.user_ns[name] = themacro |
|
1791 | self.user_ns[name] = themacro | |
1795 |
|
1792 | |||
1796 | #------------------------------------------------------------------------- |
|
1793 | #------------------------------------------------------------------------- | |
1797 | # Things related to the running of system commands |
|
1794 | # Things related to the running of system commands | |
1798 | #------------------------------------------------------------------------- |
|
1795 | #------------------------------------------------------------------------- | |
1799 |
|
1796 | |||
1800 | def system(self, cmd): |
|
1797 | def system(self, cmd): | |
1801 | """Call the given cmd in a subprocess. |
|
1798 | """Call the given cmd in a subprocess. | |
1802 |
|
1799 | |||
1803 | Parameters |
|
1800 | Parameters | |
1804 | ---------- |
|
1801 | ---------- | |
1805 | cmd : str |
|
1802 | cmd : str | |
1806 | Command to execute (can not end in '&', as bacground processes are |
|
1803 | Command to execute (can not end in '&', as bacground processes are | |
1807 | not supported. |
|
1804 | not supported. | |
1808 | """ |
|
1805 | """ | |
1809 | # We do not support backgrounding processes because we either use |
|
1806 | # We do not support backgrounding processes because we either use | |
1810 | # pexpect or pipes to read from. Users can always just call |
|
1807 | # pexpect or pipes to read from. Users can always just call | |
1811 | # os.system() if they really want a background process. |
|
1808 | # os.system() if they really want a background process. | |
1812 | if cmd.endswith('&'): |
|
1809 | if cmd.endswith('&'): | |
1813 | raise OSError("Background processes not supported.") |
|
1810 | raise OSError("Background processes not supported.") | |
1814 |
|
1811 | |||
1815 | return system(self.var_expand(cmd, depth=2)) |
|
1812 | return system(self.var_expand(cmd, depth=2)) | |
1816 |
|
1813 | |||
1817 | def getoutput(self, cmd, split=True): |
|
1814 | def getoutput(self, cmd, split=True): | |
1818 | """Get output (possibly including stderr) from a subprocess. |
|
1815 | """Get output (possibly including stderr) from a subprocess. | |
1819 |
|
1816 | |||
1820 | Parameters |
|
1817 | Parameters | |
1821 | ---------- |
|
1818 | ---------- | |
1822 | cmd : str |
|
1819 | cmd : str | |
1823 | Command to execute (can not end in '&', as background processes are |
|
1820 | Command to execute (can not end in '&', as background processes are | |
1824 | not supported. |
|
1821 | not supported. | |
1825 | split : bool, optional |
|
1822 | split : bool, optional | |
1826 |
|
1823 | |||
1827 | If True, split the output into an IPython SList. Otherwise, an |
|
1824 | If True, split the output into an IPython SList. Otherwise, an | |
1828 | IPython LSString is returned. These are objects similar to normal |
|
1825 | IPython LSString is returned. These are objects similar to normal | |
1829 | lists and strings, with a few convenience attributes for easier |
|
1826 | lists and strings, with a few convenience attributes for easier | |
1830 | manipulation of line-based output. You can use '?' on them for |
|
1827 | manipulation of line-based output. You can use '?' on them for | |
1831 | details. |
|
1828 | details. | |
1832 | """ |
|
1829 | """ | |
1833 | if cmd.endswith('&'): |
|
1830 | if cmd.endswith('&'): | |
1834 | raise OSError("Background processes not supported.") |
|
1831 | raise OSError("Background processes not supported.") | |
1835 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1832 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1836 | if split: |
|
1833 | if split: | |
1837 | out = SList(out.splitlines()) |
|
1834 | out = SList(out.splitlines()) | |
1838 | else: |
|
1835 | else: | |
1839 | out = LSString(out) |
|
1836 | out = LSString(out) | |
1840 | return out |
|
1837 | return out | |
1841 |
|
1838 | |||
1842 | #------------------------------------------------------------------------- |
|
1839 | #------------------------------------------------------------------------- | |
1843 | # Things related to aliases |
|
1840 | # Things related to aliases | |
1844 | #------------------------------------------------------------------------- |
|
1841 | #------------------------------------------------------------------------- | |
1845 |
|
1842 | |||
1846 | def init_alias(self): |
|
1843 | def init_alias(self): | |
1847 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1844 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1848 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1845 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1849 |
|
1846 | |||
1850 | #------------------------------------------------------------------------- |
|
1847 | #------------------------------------------------------------------------- | |
1851 | # Things related to extensions and plugins |
|
1848 | # Things related to extensions and plugins | |
1852 | #------------------------------------------------------------------------- |
|
1849 | #------------------------------------------------------------------------- | |
1853 |
|
1850 | |||
1854 | def init_extension_manager(self): |
|
1851 | def init_extension_manager(self): | |
1855 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1852 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1856 |
|
1853 | |||
1857 | def init_plugin_manager(self): |
|
1854 | def init_plugin_manager(self): | |
1858 | self.plugin_manager = PluginManager(config=self.config) |
|
1855 | self.plugin_manager = PluginManager(config=self.config) | |
1859 |
|
1856 | |||
1860 | #------------------------------------------------------------------------- |
|
1857 | #------------------------------------------------------------------------- | |
1861 | # Things related to payloads |
|
1858 | # Things related to payloads | |
1862 | #------------------------------------------------------------------------- |
|
1859 | #------------------------------------------------------------------------- | |
1863 |
|
1860 | |||
1864 | def init_payload(self): |
|
1861 | def init_payload(self): | |
1865 | self.payload_manager = PayloadManager(config=self.config) |
|
1862 | self.payload_manager = PayloadManager(config=self.config) | |
1866 |
|
1863 | |||
1867 | #------------------------------------------------------------------------- |
|
1864 | #------------------------------------------------------------------------- | |
1868 | # Things related to the prefilter |
|
1865 | # Things related to the prefilter | |
1869 | #------------------------------------------------------------------------- |
|
1866 | #------------------------------------------------------------------------- | |
1870 |
|
1867 | |||
1871 | def init_prefilter(self): |
|
1868 | def init_prefilter(self): | |
1872 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1869 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1873 | # Ultimately this will be refactored in the new interpreter code, but |
|
1870 | # Ultimately this will be refactored in the new interpreter code, but | |
1874 | # for now, we should expose the main prefilter method (there's legacy |
|
1871 | # for now, we should expose the main prefilter method (there's legacy | |
1875 | # code out there that may rely on this). |
|
1872 | # code out there that may rely on this). | |
1876 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1873 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1877 |
|
1874 | |||
1878 | def auto_rewrite_input(self, cmd): |
|
1875 | def auto_rewrite_input(self, cmd): | |
1879 | """Print to the screen the rewritten form of the user's command. |
|
1876 | """Print to the screen the rewritten form of the user's command. | |
1880 |
|
1877 | |||
1881 | This shows visual feedback by rewriting input lines that cause |
|
1878 | This shows visual feedback by rewriting input lines that cause | |
1882 | automatic calling to kick in, like:: |
|
1879 | automatic calling to kick in, like:: | |
1883 |
|
1880 | |||
1884 | /f x |
|
1881 | /f x | |
1885 |
|
1882 | |||
1886 | into:: |
|
1883 | into:: | |
1887 |
|
1884 | |||
1888 | ------> f(x) |
|
1885 | ------> f(x) | |
1889 |
|
1886 | |||
1890 | after the user's input prompt. This helps the user understand that the |
|
1887 | after the user's input prompt. This helps the user understand that the | |
1891 | input line was transformed automatically by IPython. |
|
1888 | input line was transformed automatically by IPython. | |
1892 | """ |
|
1889 | """ | |
1893 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1890 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1894 |
|
1891 | |||
1895 | try: |
|
1892 | try: | |
1896 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1893 | # plain ascii works better w/ pyreadline, on some machines, so | |
1897 | # we use it and only print uncolored rewrite if we have unicode |
|
1894 | # we use it and only print uncolored rewrite if we have unicode | |
1898 | rw = str(rw) |
|
1895 | rw = str(rw) | |
1899 | print >> IPython.utils.io.Term.cout, rw |
|
1896 | print >> IPython.utils.io.Term.cout, rw | |
1900 | except UnicodeEncodeError: |
|
1897 | except UnicodeEncodeError: | |
1901 | print "------> " + cmd |
|
1898 | print "------> " + cmd | |
1902 |
|
1899 | |||
1903 | #------------------------------------------------------------------------- |
|
1900 | #------------------------------------------------------------------------- | |
1904 | # Things related to extracting values/expressions from kernel and user_ns |
|
1901 | # Things related to extracting values/expressions from kernel and user_ns | |
1905 | #------------------------------------------------------------------------- |
|
1902 | #------------------------------------------------------------------------- | |
1906 |
|
1903 | |||
1907 | def _simple_error(self): |
|
1904 | def _simple_error(self): | |
1908 | etype, value = sys.exc_info()[:2] |
|
1905 | etype, value = sys.exc_info()[:2] | |
1909 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1906 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1910 |
|
1907 | |||
1911 | def user_variables(self, names): |
|
1908 | def user_variables(self, names): | |
1912 | """Get a list of variable names from the user's namespace. |
|
1909 | """Get a list of variable names from the user's namespace. | |
1913 |
|
1910 | |||
1914 | Parameters |
|
1911 | Parameters | |
1915 | ---------- |
|
1912 | ---------- | |
1916 | names : list of strings |
|
1913 | names : list of strings | |
1917 | A list of names of variables to be read from the user namespace. |
|
1914 | A list of names of variables to be read from the user namespace. | |
1918 |
|
1915 | |||
1919 | Returns |
|
1916 | Returns | |
1920 | ------- |
|
1917 | ------- | |
1921 | A dict, keyed by the input names and with the repr() of each value. |
|
1918 | A dict, keyed by the input names and with the repr() of each value. | |
1922 | """ |
|
1919 | """ | |
1923 | out = {} |
|
1920 | out = {} | |
1924 | user_ns = self.user_ns |
|
1921 | user_ns = self.user_ns | |
1925 | for varname in names: |
|
1922 | for varname in names: | |
1926 | try: |
|
1923 | try: | |
1927 | value = repr(user_ns[varname]) |
|
1924 | value = repr(user_ns[varname]) | |
1928 | except: |
|
1925 | except: | |
1929 | value = self._simple_error() |
|
1926 | value = self._simple_error() | |
1930 | out[varname] = value |
|
1927 | out[varname] = value | |
1931 | return out |
|
1928 | return out | |
1932 |
|
1929 | |||
1933 | def user_expressions(self, expressions): |
|
1930 | def user_expressions(self, expressions): | |
1934 | """Evaluate a dict of expressions in the user's namespace. |
|
1931 | """Evaluate a dict of expressions in the user's namespace. | |
1935 |
|
1932 | |||
1936 | Parameters |
|
1933 | Parameters | |
1937 | ---------- |
|
1934 | ---------- | |
1938 | expressions : dict |
|
1935 | expressions : dict | |
1939 | A dict with string keys and string values. The expression values |
|
1936 | A dict with string keys and string values. The expression values | |
1940 | should be valid Python expressions, each of which will be evaluated |
|
1937 | should be valid Python expressions, each of which will be evaluated | |
1941 | in the user namespace. |
|
1938 | in the user namespace. | |
1942 |
|
1939 | |||
1943 | Returns |
|
1940 | Returns | |
1944 | ------- |
|
1941 | ------- | |
1945 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1942 | A dict, keyed like the input expressions dict, with the repr() of each | |
1946 | value. |
|
1943 | value. | |
1947 | """ |
|
1944 | """ | |
1948 | out = {} |
|
1945 | out = {} | |
1949 | user_ns = self.user_ns |
|
1946 | user_ns = self.user_ns | |
1950 | global_ns = self.user_global_ns |
|
1947 | global_ns = self.user_global_ns | |
1951 | for key, expr in expressions.iteritems(): |
|
1948 | for key, expr in expressions.iteritems(): | |
1952 | try: |
|
1949 | try: | |
1953 | value = repr(eval(expr, global_ns, user_ns)) |
|
1950 | value = repr(eval(expr, global_ns, user_ns)) | |
1954 | except: |
|
1951 | except: | |
1955 | value = self._simple_error() |
|
1952 | value = self._simple_error() | |
1956 | out[key] = value |
|
1953 | out[key] = value | |
1957 | return out |
|
1954 | return out | |
1958 |
|
1955 | |||
1959 | #------------------------------------------------------------------------- |
|
1956 | #------------------------------------------------------------------------- | |
1960 | # Things related to the running of code |
|
1957 | # Things related to the running of code | |
1961 | #------------------------------------------------------------------------- |
|
1958 | #------------------------------------------------------------------------- | |
1962 |
|
1959 | |||
1963 | def ex(self, cmd): |
|
1960 | def ex(self, cmd): | |
1964 | """Execute a normal python statement in user namespace.""" |
|
1961 | """Execute a normal python statement in user namespace.""" | |
1965 | with nested(self.builtin_trap,): |
|
1962 | with nested(self.builtin_trap,): | |
1966 | exec cmd in self.user_global_ns, self.user_ns |
|
1963 | exec cmd in self.user_global_ns, self.user_ns | |
1967 |
|
1964 | |||
1968 | def ev(self, expr): |
|
1965 | def ev(self, expr): | |
1969 | """Evaluate python expression expr in user namespace. |
|
1966 | """Evaluate python expression expr in user namespace. | |
1970 |
|
1967 | |||
1971 | Returns the result of evaluation |
|
1968 | Returns the result of evaluation | |
1972 | """ |
|
1969 | """ | |
1973 | with nested(self.builtin_trap,): |
|
1970 | with nested(self.builtin_trap,): | |
1974 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1971 | return eval(expr, self.user_global_ns, self.user_ns) | |
1975 |
|
1972 | |||
1976 | def safe_execfile(self, fname, *where, **kw): |
|
1973 | def safe_execfile(self, fname, *where, **kw): | |
1977 | """A safe version of the builtin execfile(). |
|
1974 | """A safe version of the builtin execfile(). | |
1978 |
|
1975 | |||
1979 | This version will never throw an exception, but instead print |
|
1976 | This version will never throw an exception, but instead print | |
1980 | helpful error messages to the screen. This only works on pure |
|
1977 | helpful error messages to the screen. This only works on pure | |
1981 | Python files with the .py extension. |
|
1978 | Python files with the .py extension. | |
1982 |
|
1979 | |||
1983 | Parameters |
|
1980 | Parameters | |
1984 | ---------- |
|
1981 | ---------- | |
1985 | fname : string |
|
1982 | fname : string | |
1986 | The name of the file to be executed. |
|
1983 | The name of the file to be executed. | |
1987 | where : tuple |
|
1984 | where : tuple | |
1988 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1985 | One or two namespaces, passed to execfile() as (globals,locals). | |
1989 | If only one is given, it is passed as both. |
|
1986 | If only one is given, it is passed as both. | |
1990 | exit_ignore : bool (False) |
|
1987 | exit_ignore : bool (False) | |
1991 | If True, then silence SystemExit for non-zero status (it is always |
|
1988 | If True, then silence SystemExit for non-zero status (it is always | |
1992 | silenced for zero status, as it is so common). |
|
1989 | silenced for zero status, as it is so common). | |
1993 | """ |
|
1990 | """ | |
1994 | kw.setdefault('exit_ignore', False) |
|
1991 | kw.setdefault('exit_ignore', False) | |
1995 |
|
1992 | |||
1996 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1993 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1997 |
|
1994 | |||
1998 | # Make sure we have a .py file |
|
1995 | # Make sure we have a .py file | |
1999 | if not fname.endswith('.py'): |
|
1996 | if not fname.endswith('.py'): | |
2000 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1997 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2001 |
|
1998 | |||
2002 | # Make sure we can open the file |
|
1999 | # Make sure we can open the file | |
2003 | try: |
|
2000 | try: | |
2004 | with open(fname) as thefile: |
|
2001 | with open(fname) as thefile: | |
2005 | pass |
|
2002 | pass | |
2006 | except: |
|
2003 | except: | |
2007 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2004 | warn('Could not open file <%s> for safe execution.' % fname) | |
2008 | return |
|
2005 | return | |
2009 |
|
2006 | |||
2010 | # Find things also in current directory. This is needed to mimic the |
|
2007 | # Find things also in current directory. This is needed to mimic the | |
2011 | # behavior of running a script from the system command line, where |
|
2008 | # behavior of running a script from the system command line, where | |
2012 | # Python inserts the script's directory into sys.path |
|
2009 | # Python inserts the script's directory into sys.path | |
2013 | dname = os.path.dirname(fname) |
|
2010 | dname = os.path.dirname(fname) | |
2014 |
|
2011 | |||
2015 | with prepended_to_syspath(dname): |
|
2012 | with prepended_to_syspath(dname): | |
2016 | try: |
|
2013 | try: | |
2017 | execfile(fname,*where) |
|
2014 | execfile(fname,*where) | |
2018 | except SystemExit, status: |
|
2015 | except SystemExit, status: | |
2019 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2016 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2020 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2017 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2021 | # these are considered normal by the OS: |
|
2018 | # these are considered normal by the OS: | |
2022 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2019 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2023 | # 0 |
|
2020 | # 0 | |
2024 | # > python -c'import sys;sys.exit()'; echo $? |
|
2021 | # > python -c'import sys;sys.exit()'; echo $? | |
2025 | # 0 |
|
2022 | # 0 | |
2026 | # For other exit status, we show the exception unless |
|
2023 | # For other exit status, we show the exception unless | |
2027 | # explicitly silenced, but only in short form. |
|
2024 | # explicitly silenced, but only in short form. | |
2028 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2025 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2029 | self.showtraceback(exception_only=True) |
|
2026 | self.showtraceback(exception_only=True) | |
2030 | except: |
|
2027 | except: | |
2031 | self.showtraceback() |
|
2028 | self.showtraceback() | |
2032 |
|
2029 | |||
2033 | def safe_execfile_ipy(self, fname): |
|
2030 | def safe_execfile_ipy(self, fname): | |
2034 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2031 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2035 |
|
2032 | |||
2036 | Parameters |
|
2033 | Parameters | |
2037 | ---------- |
|
2034 | ---------- | |
2038 | fname : str |
|
2035 | fname : str | |
2039 | The name of the file to execute. The filename must have a |
|
2036 | The name of the file to execute. The filename must have a | |
2040 | .ipy extension. |
|
2037 | .ipy extension. | |
2041 | """ |
|
2038 | """ | |
2042 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2039 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2043 |
|
2040 | |||
2044 | # Make sure we have a .py file |
|
2041 | # Make sure we have a .py file | |
2045 | if not fname.endswith('.ipy'): |
|
2042 | if not fname.endswith('.ipy'): | |
2046 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2043 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2047 |
|
2044 | |||
2048 | # Make sure we can open the file |
|
2045 | # Make sure we can open the file | |
2049 | try: |
|
2046 | try: | |
2050 | with open(fname) as thefile: |
|
2047 | with open(fname) as thefile: | |
2051 | pass |
|
2048 | pass | |
2052 | except: |
|
2049 | except: | |
2053 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2050 | warn('Could not open file <%s> for safe execution.' % fname) | |
2054 | return |
|
2051 | return | |
2055 |
|
2052 | |||
2056 | # Find things also in current directory. This is needed to mimic the |
|
2053 | # Find things also in current directory. This is needed to mimic the | |
2057 | # behavior of running a script from the system command line, where |
|
2054 | # behavior of running a script from the system command line, where | |
2058 | # Python inserts the script's directory into sys.path |
|
2055 | # Python inserts the script's directory into sys.path | |
2059 | dname = os.path.dirname(fname) |
|
2056 | dname = os.path.dirname(fname) | |
2060 |
|
2057 | |||
2061 | with prepended_to_syspath(dname): |
|
2058 | with prepended_to_syspath(dname): | |
2062 | try: |
|
2059 | try: | |
2063 | with open(fname) as thefile: |
|
2060 | with open(fname) as thefile: | |
2064 | # self.run_cell currently captures all exceptions |
|
2061 | # self.run_cell currently captures all exceptions | |
2065 | # raised in user code. It would be nice if there were |
|
2062 | # raised in user code. It would be nice if there were | |
2066 | # versions of runlines, execfile that did raise, so |
|
2063 | # versions of runlines, execfile that did raise, so | |
2067 | # we could catch the errors. |
|
2064 | # we could catch the errors. | |
2068 | self.run_cell(thefile.read()) |
|
2065 | self.run_cell(thefile.read()) | |
2069 | except: |
|
2066 | except: | |
2070 | self.showtraceback() |
|
2067 | self.showtraceback() | |
2071 | warn('Unknown failure executing file: <%s>' % fname) |
|
2068 | warn('Unknown failure executing file: <%s>' % fname) | |
2072 |
|
2069 | |||
2073 | def run_cell(self, cell): |
|
2070 | def run_cell(self, cell): | |
2074 | """Run the contents of an entire multiline 'cell' of code. |
|
2071 | """Run the contents of an entire multiline 'cell' of code. | |
2075 |
|
2072 | |||
2076 | The cell is split into separate blocks which can be executed |
|
2073 | The cell is split into separate blocks which can be executed | |
2077 | individually. Then, based on how many blocks there are, they are |
|
2074 | individually. Then, based on how many blocks there are, they are | |
2078 | executed as follows: |
|
2075 | executed as follows: | |
2079 |
|
2076 | |||
2080 | - A single block: 'single' mode. |
|
2077 | - A single block: 'single' mode. | |
2081 |
|
2078 | |||
2082 | If there's more than one block, it depends: |
|
2079 | If there's more than one block, it depends: | |
2083 |
|
2080 | |||
2084 | - if the last one is no more than two lines long, run all but the last |
|
2081 | - if the last one is no more than two lines long, run all but the last | |
2085 | in 'exec' mode and the very last one in 'single' mode. This makes it |
|
2082 | in 'exec' mode and the very last one in 'single' mode. This makes it | |
2086 | easy to type simple expressions at the end to see computed values. - |
|
2083 | easy to type simple expressions at the end to see computed values. - | |
2087 | otherwise (last one is also multiline), run all in 'exec' mode |
|
2084 | otherwise (last one is also multiline), run all in 'exec' mode | |
2088 |
|
2085 | |||
2089 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, |
|
2086 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, | |
2090 | results are displayed and output prompts are computed. In 'exec' mode, |
|
2087 | results are displayed and output prompts are computed. In 'exec' mode, | |
2091 | no results are displayed unless :func:`print` is called explicitly; |
|
2088 | no results are displayed unless :func:`print` is called explicitly; | |
2092 | this mode is more akin to running a script. |
|
2089 | this mode is more akin to running a script. | |
2093 |
|
2090 | |||
2094 | Parameters |
|
2091 | Parameters | |
2095 | ---------- |
|
2092 | ---------- | |
2096 | cell : str |
|
2093 | cell : str | |
2097 | A single or multiline string. |
|
2094 | A single or multiline string. | |
2098 | """ |
|
2095 | """ | |
2099 |
|
2096 | |||
2100 | # We need to break up the input into executable blocks that can be run |
|
2097 | # We need to break up the input into executable blocks that can be run | |
2101 | # in 'single' mode, to provide comfortable user behavior. |
|
2098 | # in 'single' mode, to provide comfortable user behavior. | |
2102 | blocks = self.input_splitter.split_blocks(cell) |
|
2099 | blocks = self.input_splitter.split_blocks(cell) | |
2103 |
|
2100 | |||
2104 | if not blocks: |
|
2101 | if not blocks: | |
2105 | return |
|
2102 | return | |
2106 |
|
2103 | |||
2107 | # Store the 'ipython' version of the cell as well, since that's what |
|
2104 | # Store the 'ipython' version of the cell as well, since that's what | |
2108 | # needs to go into the translated history and get executed (the |
|
2105 | # needs to go into the translated history and get executed (the | |
2109 | # original cell may contain non-python syntax). |
|
2106 | # original cell may contain non-python syntax). | |
2110 | ipy_cell = ''.join(blocks) |
|
2107 | ipy_cell = ''.join(blocks) | |
2111 |
|
2108 | |||
2112 | # Store raw and processed history |
|
2109 | # Store raw and processed history | |
2113 | self.history_manager.store_inputs(ipy_cell, cell) |
|
2110 | self.history_manager.store_inputs(ipy_cell, cell) | |
2114 |
|
2111 | |||
2115 | self.logger.log(ipy_cell, cell) |
|
2112 | self.logger.log(ipy_cell, cell) | |
2116 |
|
2113 | |||
2117 | # All user code execution must happen with our context managers active |
|
2114 | # All user code execution must happen with our context managers active | |
2118 | with nested(self.builtin_trap, self.display_trap): |
|
2115 | with nested(self.builtin_trap, self.display_trap): | |
2119 |
|
2116 | |||
2120 | # Single-block input should behave like an interactive prompt |
|
2117 | # Single-block input should behave like an interactive prompt | |
2121 | if len(blocks) == 1: |
|
2118 | if len(blocks) == 1: | |
2122 | # since we return here, we need to update the execution count |
|
2119 | # since we return here, we need to update the execution count | |
2123 | out = self.run_one_block(blocks[0]) |
|
2120 | out = self.run_one_block(blocks[0]) | |
2124 | self.execution_count += 1 |
|
2121 | self.execution_count += 1 | |
2125 | return out |
|
2122 | return out | |
2126 |
|
2123 | |||
2127 | # In multi-block input, if the last block is a simple (one-two |
|
2124 | # In multi-block input, if the last block is a simple (one-two | |
2128 | # lines) expression, run it in single mode so it produces output. |
|
2125 | # lines) expression, run it in single mode so it produces output. | |
2129 | # Otherwise just feed the whole thing to run_code. This seems like |
|
2126 | # Otherwise just feed the whole thing to run_code. This seems like | |
2130 | # a reasonable usability design. |
|
2127 | # a reasonable usability design. | |
2131 | last = blocks[-1] |
|
2128 | last = blocks[-1] | |
2132 | last_nlines = len(last.splitlines()) |
|
2129 | last_nlines = len(last.splitlines()) | |
2133 |
|
2130 | |||
2134 | # Note: below, whenever we call run_code, we must sync history |
|
2131 | # Note: below, whenever we call run_code, we must sync history | |
2135 | # ourselves, because run_code is NOT meant to manage history at all. |
|
2132 | # ourselves, because run_code is NOT meant to manage history at all. | |
2136 | if last_nlines < 2: |
|
2133 | if last_nlines < 2: | |
2137 | # Here we consider the cell split between 'body' and 'last', |
|
2134 | # Here we consider the cell split between 'body' and 'last', | |
2138 | # store all history and execute 'body', and if successful, then |
|
2135 | # store all history and execute 'body', and if successful, then | |
2139 | # proceed to execute 'last'. |
|
2136 | # proceed to execute 'last'. | |
2140 |
|
2137 | |||
2141 | # Get the main body to run as a cell |
|
2138 | # Get the main body to run as a cell | |
2142 | ipy_body = ''.join(blocks[:-1]) |
|
2139 | ipy_body = ''.join(blocks[:-1]) | |
2143 | retcode = self.run_source(ipy_body, symbol='exec', |
|
2140 | retcode = self.run_source(ipy_body, symbol='exec', | |
2144 | post_execute=False) |
|
2141 | post_execute=False) | |
2145 | if retcode==0: |
|
2142 | if retcode==0: | |
2146 | # And the last expression via runlines so it produces output |
|
2143 | # And the last expression via runlines so it produces output | |
2147 | self.run_one_block(last) |
|
2144 | self.run_one_block(last) | |
2148 | else: |
|
2145 | else: | |
2149 | # Run the whole cell as one entity, storing both raw and |
|
2146 | # Run the whole cell as one entity, storing both raw and | |
2150 | # processed input in history |
|
2147 | # processed input in history | |
2151 | self.run_source(ipy_cell, symbol='exec') |
|
2148 | self.run_source(ipy_cell, symbol='exec') | |
2152 |
|
2149 | |||
2153 | # Each cell is a *single* input, regardless of how many lines it has |
|
2150 | # Each cell is a *single* input, regardless of how many lines it has | |
2154 | self.execution_count += 1 |
|
2151 | self.execution_count += 1 | |
2155 |
|
2152 | |||
2156 | def run_one_block(self, block): |
|
2153 | def run_one_block(self, block): | |
2157 | """Run a single interactive block of source code. |
|
2154 | """Run a single interactive block of source code. | |
2158 |
|
2155 | |||
2159 | If the block is single-line, dynamic transformations are applied to it |
|
2156 | If the block is single-line, dynamic transformations are applied to it | |
2160 | (like automagics, autocall and alias recognition). |
|
2157 | (like automagics, autocall and alias recognition). | |
2161 |
|
2158 | |||
2162 | If the block is multi-line, it must consist of valid Python code only. |
|
2159 | If the block is multi-line, it must consist of valid Python code only. | |
2163 |
|
2160 | |||
2164 | Parameters |
|
2161 | Parameters | |
2165 | ---------- |
|
2162 | ---------- | |
2166 | block : string |
|
2163 | block : string | |
2167 | A (possibly multiline) string of code to be executed. |
|
2164 | A (possibly multiline) string of code to be executed. | |
2168 |
|
2165 | |||
2169 | Returns |
|
2166 | Returns | |
2170 | ------- |
|
2167 | ------- | |
2171 | The output of the underlying execution method used, be it |
|
2168 | The output of the underlying execution method used, be it | |
2172 | :meth:`run_source` or :meth:`run_single_line`. |
|
2169 | :meth:`run_source` or :meth:`run_single_line`. | |
2173 | """ |
|
2170 | """ | |
2174 | if len(block.splitlines()) <= 1: |
|
2171 | if len(block.splitlines()) <= 1: | |
2175 | out = self.run_single_line(block) |
|
2172 | out = self.run_single_line(block) | |
2176 | else: |
|
2173 | else: | |
2177 | # Call run_source, which correctly compiles the input cell. |
|
2174 | # Call run_source, which correctly compiles the input cell. | |
2178 | # run_code must only be called when we know we have a code object, |
|
2175 | # run_code must only be called when we know we have a code object, | |
2179 | # as it does a naked exec and the compilation mode may not be what |
|
2176 | # as it does a naked exec and the compilation mode may not be what | |
2180 | # we wanted. |
|
2177 | # we wanted. | |
2181 | out = self.run_source(block) |
|
2178 | out = self.run_source(block) | |
2182 | return out |
|
2179 | return out | |
2183 |
|
2180 | |||
2184 | def run_single_line(self, line): |
|
2181 | def run_single_line(self, line): | |
2185 | """Run a single-line interactive statement. |
|
2182 | """Run a single-line interactive statement. | |
2186 |
|
2183 | |||
2187 | This assumes the input has been transformed to IPython syntax by |
|
2184 | This assumes the input has been transformed to IPython syntax by | |
2188 | applying all static transformations (those with an explicit prefix like |
|
2185 | applying all static transformations (those with an explicit prefix like | |
2189 | % or !), but it will further try to apply the dynamic ones. |
|
2186 | % or !), but it will further try to apply the dynamic ones. | |
2190 |
|
2187 | |||
2191 | It does not update history. |
|
2188 | It does not update history. | |
2192 | """ |
|
2189 | """ | |
2193 | tline = self.prefilter_manager.prefilter_line(line) |
|
2190 | tline = self.prefilter_manager.prefilter_line(line) | |
2194 | return self.run_source(tline) |
|
2191 | return self.run_source(tline) | |
2195 |
|
2192 | |||
2196 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2193 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2197 | # input logic has been 100% moved to frontends and is stable. |
|
2194 | # input logic has been 100% moved to frontends and is stable. | |
2198 | def runlines(self, lines, clean=False): |
|
2195 | def runlines(self, lines, clean=False): | |
2199 | """Run a string of one or more lines of source. |
|
2196 | """Run a string of one or more lines of source. | |
2200 |
|
2197 | |||
2201 | This method is capable of running a string containing multiple source |
|
2198 | This method is capable of running a string containing multiple source | |
2202 | lines, as if they had been entered at the IPython prompt. Since it |
|
2199 | lines, as if they had been entered at the IPython prompt. Since it | |
2203 | exposes IPython's processing machinery, the given strings can contain |
|
2200 | exposes IPython's processing machinery, the given strings can contain | |
2204 | magic calls (%magic), special shell access (!cmd), etc. |
|
2201 | magic calls (%magic), special shell access (!cmd), etc. | |
2205 | """ |
|
2202 | """ | |
2206 |
|
2203 | |||
2207 | if isinstance(lines, (list, tuple)): |
|
2204 | if isinstance(lines, (list, tuple)): | |
2208 | lines = '\n'.join(lines) |
|
2205 | lines = '\n'.join(lines) | |
2209 |
|
2206 | |||
2210 | if clean: |
|
2207 | if clean: | |
2211 | lines = self._cleanup_ipy_script(lines) |
|
2208 | lines = self._cleanup_ipy_script(lines) | |
2212 |
|
2209 | |||
2213 | # We must start with a clean buffer, in case this is run from an |
|
2210 | # We must start with a clean buffer, in case this is run from an | |
2214 | # interactive IPython session (via a magic, for example). |
|
2211 | # interactive IPython session (via a magic, for example). | |
2215 | self.reset_buffer() |
|
2212 | self.reset_buffer() | |
2216 | lines = lines.splitlines() |
|
2213 | lines = lines.splitlines() | |
2217 |
|
2214 | |||
2218 | # Since we will prefilter all lines, store the user's raw input too |
|
2215 | # Since we will prefilter all lines, store the user's raw input too | |
2219 | # before we apply any transformations |
|
2216 | # before we apply any transformations | |
2220 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2217 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2221 |
|
2218 | |||
2222 | more = False |
|
2219 | more = False | |
2223 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2220 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2224 | with nested(self.builtin_trap, self.display_trap): |
|
2221 | with nested(self.builtin_trap, self.display_trap): | |
2225 | for line in lines: |
|
2222 | for line in lines: | |
2226 | # skip blank lines so we don't mess up the prompt counter, but |
|
2223 | # skip blank lines so we don't mess up the prompt counter, but | |
2227 | # do NOT skip even a blank line if we are in a code block (more |
|
2224 | # do NOT skip even a blank line if we are in a code block (more | |
2228 | # is true) |
|
2225 | # is true) | |
2229 |
|
2226 | |||
2230 | if line or more: |
|
2227 | if line or more: | |
2231 | more = self.push_line(prefilter_lines(line, more)) |
|
2228 | more = self.push_line(prefilter_lines(line, more)) | |
2232 | # IPython's run_source returns None if there was an error |
|
2229 | # IPython's run_source returns None if there was an error | |
2233 | # compiling the code. This allows us to stop processing |
|
2230 | # compiling the code. This allows us to stop processing | |
2234 | # right away, so the user gets the error message at the |
|
2231 | # right away, so the user gets the error message at the | |
2235 | # right place. |
|
2232 | # right place. | |
2236 | if more is None: |
|
2233 | if more is None: | |
2237 | break |
|
2234 | break | |
2238 | # final newline in case the input didn't have it, so that the code |
|
2235 | # final newline in case the input didn't have it, so that the code | |
2239 | # actually does get executed |
|
2236 | # actually does get executed | |
2240 | if more: |
|
2237 | if more: | |
2241 | self.push_line('\n') |
|
2238 | self.push_line('\n') | |
2242 |
|
2239 | |||
2243 | def run_source(self, source, filename=None, |
|
2240 | def run_source(self, source, filename=None, | |
2244 | symbol='single', post_execute=True): |
|
2241 | symbol='single', post_execute=True): | |
2245 | """Compile and run some source in the interpreter. |
|
2242 | """Compile and run some source in the interpreter. | |
2246 |
|
2243 | |||
2247 | Arguments are as for compile_command(). |
|
2244 | Arguments are as for compile_command(). | |
2248 |
|
2245 | |||
2249 | One several things can happen: |
|
2246 | One several things can happen: | |
2250 |
|
2247 | |||
2251 | 1) The input is incorrect; compile_command() raised an |
|
2248 | 1) The input is incorrect; compile_command() raised an | |
2252 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2249 | exception (SyntaxError or OverflowError). A syntax traceback | |
2253 | will be printed by calling the showsyntaxerror() method. |
|
2250 | will be printed by calling the showsyntaxerror() method. | |
2254 |
|
2251 | |||
2255 | 2) The input is incomplete, and more input is required; |
|
2252 | 2) The input is incomplete, and more input is required; | |
2256 | compile_command() returned None. Nothing happens. |
|
2253 | compile_command() returned None. Nothing happens. | |
2257 |
|
2254 | |||
2258 | 3) The input is complete; compile_command() returned a code |
|
2255 | 3) The input is complete; compile_command() returned a code | |
2259 | object. The code is executed by calling self.run_code() (which |
|
2256 | object. The code is executed by calling self.run_code() (which | |
2260 | also handles run-time exceptions, except for SystemExit). |
|
2257 | also handles run-time exceptions, except for SystemExit). | |
2261 |
|
2258 | |||
2262 | The return value is: |
|
2259 | The return value is: | |
2263 |
|
2260 | |||
2264 | - True in case 2 |
|
2261 | - True in case 2 | |
2265 |
|
2262 | |||
2266 | - False in the other cases, unless an exception is raised, where |
|
2263 | - False in the other cases, unless an exception is raised, where | |
2267 | None is returned instead. This can be used by external callers to |
|
2264 | None is returned instead. This can be used by external callers to | |
2268 | know whether to continue feeding input or not. |
|
2265 | know whether to continue feeding input or not. | |
2269 |
|
2266 | |||
2270 | The return value can be used to decide whether to use sys.ps1 or |
|
2267 | The return value can be used to decide whether to use sys.ps1 or | |
2271 | sys.ps2 to prompt the next line.""" |
|
2268 | sys.ps2 to prompt the next line.""" | |
2272 |
|
2269 | |||
2273 | # We need to ensure that the source is unicode from here on. |
|
2270 | # We need to ensure that the source is unicode from here on. | |
2274 | if type(source)==str: |
|
2271 | if type(source)==str: | |
2275 | usource = source.decode(self.stdin_encoding) |
|
2272 | usource = source.decode(self.stdin_encoding) | |
2276 | else: |
|
2273 | else: | |
2277 | usource = source |
|
2274 | usource = source | |
2278 |
|
2275 | |||
2279 | if 0: # dbg |
|
2276 | if 0: # dbg | |
2280 | print 'Source:', repr(source) # dbg |
|
2277 | print 'Source:', repr(source) # dbg | |
2281 | print 'USource:', repr(usource) # dbg |
|
2278 | print 'USource:', repr(usource) # dbg | |
2282 | print 'type:', type(source) # dbg |
|
2279 | print 'type:', type(source) # dbg | |
2283 | print 'encoding', self.stdin_encoding # dbg |
|
2280 | print 'encoding', self.stdin_encoding # dbg | |
2284 |
|
2281 | |||
2285 | try: |
|
2282 | try: | |
2286 | code = self.compile(usource, symbol, self.execution_count) |
|
2283 | code = self.compile(usource, symbol, self.execution_count) | |
2287 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2284 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2288 | # Case 1 |
|
2285 | # Case 1 | |
2289 | self.showsyntaxerror(filename) |
|
2286 | self.showsyntaxerror(filename) | |
2290 | return None |
|
2287 | return None | |
2291 |
|
2288 | |||
2292 | if code is None: |
|
2289 | if code is None: | |
2293 | # Case 2 |
|
2290 | # Case 2 | |
2294 | return True |
|
2291 | return True | |
2295 |
|
2292 | |||
2296 | # Case 3 |
|
2293 | # Case 3 | |
2297 | # We store the code object so that threaded shells and |
|
2294 | # We store the code object so that threaded shells and | |
2298 | # custom exception handlers can access all this info if needed. |
|
2295 | # custom exception handlers can access all this info if needed. | |
2299 | # The source corresponding to this can be obtained from the |
|
2296 | # The source corresponding to this can be obtained from the | |
2300 | # buffer attribute as '\n'.join(self.buffer). |
|
2297 | # buffer attribute as '\n'.join(self.buffer). | |
2301 | self.code_to_run = code |
|
2298 | self.code_to_run = code | |
2302 | # now actually execute the code object |
|
2299 | # now actually execute the code object | |
2303 | if self.run_code(code, post_execute) == 0: |
|
2300 | if self.run_code(code, post_execute) == 0: | |
2304 | return False |
|
2301 | return False | |
2305 | else: |
|
2302 | else: | |
2306 | return None |
|
2303 | return None | |
2307 |
|
2304 | |||
2308 | # For backwards compatibility |
|
2305 | # For backwards compatibility | |
2309 | runsource = run_source |
|
2306 | runsource = run_source | |
2310 |
|
2307 | |||
2311 | def run_code(self, code_obj, post_execute=True): |
|
2308 | def run_code(self, code_obj, post_execute=True): | |
2312 | """Execute a code object. |
|
2309 | """Execute a code object. | |
2313 |
|
2310 | |||
2314 | When an exception occurs, self.showtraceback() is called to display a |
|
2311 | When an exception occurs, self.showtraceback() is called to display a | |
2315 | traceback. |
|
2312 | traceback. | |
2316 |
|
2313 | |||
2317 | Return value: a flag indicating whether the code to be run completed |
|
2314 | Return value: a flag indicating whether the code to be run completed | |
2318 | successfully: |
|
2315 | successfully: | |
2319 |
|
2316 | |||
2320 | - 0: successful execution. |
|
2317 | - 0: successful execution. | |
2321 | - 1: an error occurred. |
|
2318 | - 1: an error occurred. | |
2322 | """ |
|
2319 | """ | |
2323 |
|
2320 | |||
2324 | # Set our own excepthook in case the user code tries to call it |
|
2321 | # Set our own excepthook in case the user code tries to call it | |
2325 | # directly, so that the IPython crash handler doesn't get triggered |
|
2322 | # directly, so that the IPython crash handler doesn't get triggered | |
2326 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2323 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2327 |
|
2324 | |||
2328 | # we save the original sys.excepthook in the instance, in case config |
|
2325 | # we save the original sys.excepthook in the instance, in case config | |
2329 | # code (such as magics) needs access to it. |
|
2326 | # code (such as magics) needs access to it. | |
2330 | self.sys_excepthook = old_excepthook |
|
2327 | self.sys_excepthook = old_excepthook | |
2331 | outflag = 1 # happens in more places, so it's easier as default |
|
2328 | outflag = 1 # happens in more places, so it's easier as default | |
2332 | try: |
|
2329 | try: | |
2333 | try: |
|
2330 | try: | |
2334 | self.hooks.pre_run_code_hook() |
|
2331 | self.hooks.pre_run_code_hook() | |
2335 | #rprint('Running code', repr(code_obj)) # dbg |
|
2332 | #rprint('Running code', repr(code_obj)) # dbg | |
2336 | exec code_obj in self.user_global_ns, self.user_ns |
|
2333 | exec code_obj in self.user_global_ns, self.user_ns | |
2337 | finally: |
|
2334 | finally: | |
2338 | # Reset our crash handler in place |
|
2335 | # Reset our crash handler in place | |
2339 | sys.excepthook = old_excepthook |
|
2336 | sys.excepthook = old_excepthook | |
2340 | except SystemExit: |
|
2337 | except SystemExit: | |
2341 | self.reset_buffer() |
|
2338 | self.reset_buffer() | |
2342 | self.showtraceback(exception_only=True) |
|
2339 | self.showtraceback(exception_only=True) | |
2343 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2340 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2344 | except self.custom_exceptions: |
|
2341 | except self.custom_exceptions: | |
2345 | etype,value,tb = sys.exc_info() |
|
2342 | etype,value,tb = sys.exc_info() | |
2346 | self.CustomTB(etype,value,tb) |
|
2343 | self.CustomTB(etype,value,tb) | |
2347 | except: |
|
2344 | except: | |
2348 | self.showtraceback() |
|
2345 | self.showtraceback() | |
2349 | else: |
|
2346 | else: | |
2350 | outflag = 0 |
|
2347 | outflag = 0 | |
2351 | if softspace(sys.stdout, 0): |
|
2348 | if softspace(sys.stdout, 0): | |
2352 |
|
2349 | |||
2353 |
|
2350 | |||
2354 | # Execute any registered post-execution functions. Here, any errors |
|
2351 | # Execute any registered post-execution functions. Here, any errors | |
2355 | # are reported only minimally and just on the terminal, because the |
|
2352 | # are reported only minimally and just on the terminal, because the | |
2356 | # main exception channel may be occupied with a user traceback. |
|
2353 | # main exception channel may be occupied with a user traceback. | |
2357 | # FIXME: we need to think this mechanism a little more carefully. |
|
2354 | # FIXME: we need to think this mechanism a little more carefully. | |
2358 | if post_execute: |
|
2355 | if post_execute: | |
2359 | for func in self._post_execute: |
|
2356 | for func in self._post_execute: | |
2360 | try: |
|
2357 | try: | |
2361 | func() |
|
2358 | func() | |
2362 | except: |
|
2359 | except: | |
2363 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2360 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2364 | func |
|
2361 | func | |
2365 | print >> io.Term.cout, head |
|
2362 | print >> io.Term.cout, head | |
2366 | print >> io.Term.cout, self._simple_error() |
|
2363 | print >> io.Term.cout, self._simple_error() | |
2367 | print >> io.Term.cout, 'Removing from post_execute' |
|
2364 | print >> io.Term.cout, 'Removing from post_execute' | |
2368 | self._post_execute.remove(func) |
|
2365 | self._post_execute.remove(func) | |
2369 |
|
2366 | |||
2370 | # Flush out code object which has been run (and source) |
|
2367 | # Flush out code object which has been run (and source) | |
2371 | self.code_to_run = None |
|
2368 | self.code_to_run = None | |
2372 | return outflag |
|
2369 | return outflag | |
2373 |
|
2370 | |||
2374 | # For backwards compatibility |
|
2371 | # For backwards compatibility | |
2375 | runcode = run_code |
|
2372 | runcode = run_code | |
2376 |
|
2373 | |||
2377 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2374 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2378 | # input logic has been 100% moved to frontends and is stable. |
|
2375 | # input logic has been 100% moved to frontends and is stable. | |
2379 | def push_line(self, line): |
|
2376 | def push_line(self, line): | |
2380 | """Push a line to the interpreter. |
|
2377 | """Push a line to the interpreter. | |
2381 |
|
2378 | |||
2382 | The line should not have a trailing newline; it may have |
|
2379 | The line should not have a trailing newline; it may have | |
2383 | internal newlines. The line is appended to a buffer and the |
|
2380 | internal newlines. The line is appended to a buffer and the | |
2384 | interpreter's run_source() method is called with the |
|
2381 | interpreter's run_source() method is called with the | |
2385 | concatenated contents of the buffer as source. If this |
|
2382 | concatenated contents of the buffer as source. If this | |
2386 | indicates that the command was executed or invalid, the buffer |
|
2383 | indicates that the command was executed or invalid, the buffer | |
2387 | is reset; otherwise, the command is incomplete, and the buffer |
|
2384 | is reset; otherwise, the command is incomplete, and the buffer | |
2388 | is left as it was after the line was appended. The return |
|
2385 | is left as it was after the line was appended. The return | |
2389 | value is 1 if more input is required, 0 if the line was dealt |
|
2386 | value is 1 if more input is required, 0 if the line was dealt | |
2390 | with in some way (this is the same as run_source()). |
|
2387 | with in some way (this is the same as run_source()). | |
2391 | """ |
|
2388 | """ | |
2392 |
|
2389 | |||
2393 | # autoindent management should be done here, and not in the |
|
2390 | # autoindent management should be done here, and not in the | |
2394 | # interactive loop, since that one is only seen by keyboard input. We |
|
2391 | # interactive loop, since that one is only seen by keyboard input. We | |
2395 | # need this done correctly even for code run via runlines (which uses |
|
2392 | # need this done correctly even for code run via runlines (which uses | |
2396 | # push). |
|
2393 | # push). | |
2397 |
|
2394 | |||
2398 | #print 'push line: <%s>' % line # dbg |
|
2395 | #print 'push line: <%s>' % line # dbg | |
2399 | self.buffer.append(line) |
|
2396 | self.buffer.append(line) | |
2400 | full_source = '\n'.join(self.buffer) |
|
2397 | full_source = '\n'.join(self.buffer) | |
2401 | more = self.run_source(full_source, self.filename) |
|
2398 | more = self.run_source(full_source, self.filename) | |
2402 | if not more: |
|
2399 | if not more: | |
2403 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), |
|
2400 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), | |
2404 | full_source) |
|
2401 | full_source) | |
2405 | self.reset_buffer() |
|
2402 | self.reset_buffer() | |
2406 | self.execution_count += 1 |
|
2403 | self.execution_count += 1 | |
2407 | return more |
|
2404 | return more | |
2408 |
|
2405 | |||
2409 | def reset_buffer(self): |
|
2406 | def reset_buffer(self): | |
2410 | """Reset the input buffer.""" |
|
2407 | """Reset the input buffer.""" | |
2411 | self.buffer[:] = [] |
|
2408 | self.buffer[:] = [] | |
2412 | self.buffer_raw[:] = [] |
|
2409 | self.buffer_raw[:] = [] | |
2413 | self.input_splitter.reset() |
|
2410 | self.input_splitter.reset() | |
2414 |
|
2411 | |||
2415 | # For backwards compatibility |
|
2412 | # For backwards compatibility | |
2416 | resetbuffer = reset_buffer |
|
2413 | resetbuffer = reset_buffer | |
2417 |
|
2414 | |||
2418 | def _is_secondary_block_start(self, s): |
|
2415 | def _is_secondary_block_start(self, s): | |
2419 | if not s.endswith(':'): |
|
2416 | if not s.endswith(':'): | |
2420 | return False |
|
2417 | return False | |
2421 | if (s.startswith('elif') or |
|
2418 | if (s.startswith('elif') or | |
2422 | s.startswith('else') or |
|
2419 | s.startswith('else') or | |
2423 | s.startswith('except') or |
|
2420 | s.startswith('except') or | |
2424 | s.startswith('finally')): |
|
2421 | s.startswith('finally')): | |
2425 | return True |
|
2422 | return True | |
2426 |
|
2423 | |||
2427 | def _cleanup_ipy_script(self, script): |
|
2424 | def _cleanup_ipy_script(self, script): | |
2428 | """Make a script safe for self.runlines() |
|
2425 | """Make a script safe for self.runlines() | |
2429 |
|
2426 | |||
2430 | Currently, IPython is lines based, with blocks being detected by |
|
2427 | Currently, IPython is lines based, with blocks being detected by | |
2431 | empty lines. This is a problem for block based scripts that may |
|
2428 | empty lines. This is a problem for block based scripts that may | |
2432 | not have empty lines after blocks. This script adds those empty |
|
2429 | not have empty lines after blocks. This script adds those empty | |
2433 | lines to make scripts safe for running in the current line based |
|
2430 | lines to make scripts safe for running in the current line based | |
2434 | IPython. |
|
2431 | IPython. | |
2435 | """ |
|
2432 | """ | |
2436 | res = [] |
|
2433 | res = [] | |
2437 | lines = script.splitlines() |
|
2434 | lines = script.splitlines() | |
2438 | level = 0 |
|
2435 | level = 0 | |
2439 |
|
2436 | |||
2440 | for l in lines: |
|
2437 | for l in lines: | |
2441 | lstripped = l.lstrip() |
|
2438 | lstripped = l.lstrip() | |
2442 | stripped = l.strip() |
|
2439 | stripped = l.strip() | |
2443 | if not stripped: |
|
2440 | if not stripped: | |
2444 | continue |
|
2441 | continue | |
2445 | newlevel = len(l) - len(lstripped) |
|
2442 | newlevel = len(l) - len(lstripped) | |
2446 | if level > 0 and newlevel == 0 and \ |
|
2443 | if level > 0 and newlevel == 0 and \ | |
2447 | not self._is_secondary_block_start(stripped): |
|
2444 | not self._is_secondary_block_start(stripped): | |
2448 | # add empty line |
|
2445 | # add empty line | |
2449 | res.append('') |
|
2446 | res.append('') | |
2450 | res.append(l) |
|
2447 | res.append(l) | |
2451 | level = newlevel |
|
2448 | level = newlevel | |
2452 |
|
2449 | |||
2453 | return '\n'.join(res) + '\n' |
|
2450 | return '\n'.join(res) + '\n' | |
2454 |
|
2451 | |||
2455 | #------------------------------------------------------------------------- |
|
2452 | #------------------------------------------------------------------------- | |
2456 | # Things related to GUI support and pylab |
|
2453 | # Things related to GUI support and pylab | |
2457 | #------------------------------------------------------------------------- |
|
2454 | #------------------------------------------------------------------------- | |
2458 |
|
2455 | |||
2459 | def enable_pylab(self, gui=None): |
|
2456 | def enable_pylab(self, gui=None): | |
2460 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2457 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2461 |
|
2458 | |||
2462 | #------------------------------------------------------------------------- |
|
2459 | #------------------------------------------------------------------------- | |
2463 | # Utilities |
|
2460 | # Utilities | |
2464 | #------------------------------------------------------------------------- |
|
2461 | #------------------------------------------------------------------------- | |
2465 |
|
2462 | |||
2466 | def var_expand(self,cmd,depth=0): |
|
2463 | def var_expand(self,cmd,depth=0): | |
2467 | """Expand python variables in a string. |
|
2464 | """Expand python variables in a string. | |
2468 |
|
2465 | |||
2469 | The depth argument indicates how many frames above the caller should |
|
2466 | The depth argument indicates how many frames above the caller should | |
2470 | be walked to look for the local namespace where to expand variables. |
|
2467 | be walked to look for the local namespace where to expand variables. | |
2471 |
|
2468 | |||
2472 | The global namespace for expansion is always the user's interactive |
|
2469 | The global namespace for expansion is always the user's interactive | |
2473 | namespace. |
|
2470 | namespace. | |
2474 | """ |
|
2471 | """ | |
2475 |
|
2472 | |||
2476 | return str(ItplNS(cmd, |
|
2473 | return str(ItplNS(cmd, | |
2477 | self.user_ns, # globals |
|
2474 | self.user_ns, # globals | |
2478 | # Skip our own frame in searching for locals: |
|
2475 | # Skip our own frame in searching for locals: | |
2479 | sys._getframe(depth+1).f_locals # locals |
|
2476 | sys._getframe(depth+1).f_locals # locals | |
2480 | )) |
|
2477 | )) | |
2481 |
|
2478 | |||
2482 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2479 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2483 | """Make a new tempfile and return its filename. |
|
2480 | """Make a new tempfile and return its filename. | |
2484 |
|
2481 | |||
2485 | This makes a call to tempfile.mktemp, but it registers the created |
|
2482 | This makes a call to tempfile.mktemp, but it registers the created | |
2486 | filename internally so ipython cleans it up at exit time. |
|
2483 | filename internally so ipython cleans it up at exit time. | |
2487 |
|
2484 | |||
2488 | Optional inputs: |
|
2485 | Optional inputs: | |
2489 |
|
2486 | |||
2490 | - data(None): if data is given, it gets written out to the temp file |
|
2487 | - data(None): if data is given, it gets written out to the temp file | |
2491 | immediately, and the file is closed again.""" |
|
2488 | immediately, and the file is closed again.""" | |
2492 |
|
2489 | |||
2493 | filename = tempfile.mktemp('.py', prefix) |
|
2490 | filename = tempfile.mktemp('.py', prefix) | |
2494 | self.tempfiles.append(filename) |
|
2491 | self.tempfiles.append(filename) | |
2495 |
|
2492 | |||
2496 | if data: |
|
2493 | if data: | |
2497 | tmp_file = open(filename,'w') |
|
2494 | tmp_file = open(filename,'w') | |
2498 | tmp_file.write(data) |
|
2495 | tmp_file.write(data) | |
2499 | tmp_file.close() |
|
2496 | tmp_file.close() | |
2500 | return filename |
|
2497 | return filename | |
2501 |
|
2498 | |||
2502 | # TODO: This should be removed when Term is refactored. |
|
2499 | # TODO: This should be removed when Term is refactored. | |
2503 | def write(self,data): |
|
2500 | def write(self,data): | |
2504 | """Write a string to the default output""" |
|
2501 | """Write a string to the default output""" | |
2505 | io.Term.cout.write(data) |
|
2502 | io.Term.cout.write(data) | |
2506 |
|
2503 | |||
2507 | # TODO: This should be removed when Term is refactored. |
|
2504 | # TODO: This should be removed when Term is refactored. | |
2508 | def write_err(self,data): |
|
2505 | def write_err(self,data): | |
2509 | """Write a string to the default error output""" |
|
2506 | """Write a string to the default error output""" | |
2510 | io.Term.cerr.write(data) |
|
2507 | io.Term.cerr.write(data) | |
2511 |
|
2508 | |||
2512 | def ask_yes_no(self,prompt,default=True): |
|
2509 | def ask_yes_no(self,prompt,default=True): | |
2513 | if self.quiet: |
|
2510 | if self.quiet: | |
2514 | return True |
|
2511 | return True | |
2515 | return ask_yes_no(prompt,default) |
|
2512 | return ask_yes_no(prompt,default) | |
2516 |
|
2513 | |||
2517 | def show_usage(self): |
|
2514 | def show_usage(self): | |
2518 | """Show a usage message""" |
|
2515 | """Show a usage message""" | |
2519 | page.page(IPython.core.usage.interactive_usage) |
|
2516 | page.page(IPython.core.usage.interactive_usage) | |
2520 |
|
2517 | |||
2521 | #------------------------------------------------------------------------- |
|
2518 | #------------------------------------------------------------------------- | |
2522 | # Things related to IPython exiting |
|
2519 | # Things related to IPython exiting | |
2523 | #------------------------------------------------------------------------- |
|
2520 | #------------------------------------------------------------------------- | |
2524 | def atexit_operations(self): |
|
2521 | def atexit_operations(self): | |
2525 | """This will be executed at the time of exit. |
|
2522 | """This will be executed at the time of exit. | |
2526 |
|
2523 | |||
2527 | Cleanup operations and saving of persistent data that is done |
|
2524 | Cleanup operations and saving of persistent data that is done | |
2528 | unconditionally by IPython should be performed here. |
|
2525 | unconditionally by IPython should be performed here. | |
2529 |
|
2526 | |||
2530 | For things that may depend on startup flags or platform specifics (such |
|
2527 | For things that may depend on startup flags or platform specifics (such | |
2531 | as having readline or not), register a separate atexit function in the |
|
2528 | as having readline or not), register a separate atexit function in the | |
2532 | code that has the appropriate information, rather than trying to |
|
2529 | code that has the appropriate information, rather than trying to | |
2533 | clutter |
|
2530 | clutter | |
2534 | """ |
|
2531 | """ | |
2535 | # Cleanup all tempfiles left around |
|
2532 | # Cleanup all tempfiles left around | |
2536 | for tfile in self.tempfiles: |
|
2533 | for tfile in self.tempfiles: | |
2537 | try: |
|
2534 | try: | |
2538 | os.unlink(tfile) |
|
2535 | os.unlink(tfile) | |
2539 | except OSError: |
|
2536 | except OSError: | |
2540 | pass |
|
2537 | pass | |
2541 |
|
2538 | |||
2542 | self.save_history() |
|
2539 | self.save_history() | |
2543 |
|
2540 | |||
2544 | # Clear all user namespaces to release all references cleanly. |
|
2541 | # Clear all user namespaces to release all references cleanly. | |
2545 | self.reset() |
|
2542 | self.reset() | |
2546 |
|
2543 | |||
2547 | # Run user hooks |
|
2544 | # Run user hooks | |
2548 | self.hooks.shutdown_hook() |
|
2545 | self.hooks.shutdown_hook() | |
2549 |
|
2546 | |||
2550 | def cleanup(self): |
|
2547 | def cleanup(self): | |
2551 | self.restore_sys_module_state() |
|
2548 | self.restore_sys_module_state() | |
2552 |
|
2549 | |||
2553 |
|
2550 | |||
2554 | class InteractiveShellABC(object): |
|
2551 | class InteractiveShellABC(object): | |
2555 | """An abstract base class for InteractiveShell.""" |
|
2552 | """An abstract base class for InteractiveShell.""" | |
2556 | __metaclass__ = abc.ABCMeta |
|
2553 | __metaclass__ = abc.ABCMeta | |
2557 |
|
2554 | |||
2558 | InteractiveShellABC.register(InteractiveShell) |
|
2555 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,39 +1,39 b'' | |||||
1 | """Support for interactive macros in IPython""" |
|
1 | """Support for interactive macros in IPython""" | |
2 |
|
2 | |||
3 | #***************************************************************************** |
|
3 | #***************************************************************************** | |
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #***************************************************************************** |
|
8 | #***************************************************************************** | |
9 |
|
9 | |||
10 | import IPython.utils.io |
|
10 | import IPython.utils.io | |
11 | from IPython.core.autocall import IPyAutocall |
|
11 | from IPython.core.autocall import IPyAutocall | |
12 |
|
12 | |||
13 | class Macro(IPyAutocall): |
|
13 | class Macro(IPyAutocall): | |
14 | """Simple class to store the value of macros as strings. |
|
14 | """Simple class to store the value of macros as strings. | |
15 |
|
15 | |||
16 | Macro is just a callable that executes a string of IPython |
|
16 | Macro is just a callable that executes a string of IPython | |
17 | input when called. |
|
17 | input when called. | |
18 |
|
18 | |||
19 | Args to macro are available in _margv list if you need them. |
|
19 | Args to macro are available in _margv list if you need them. | |
20 | """ |
|
20 | """ | |
21 |
|
21 | |||
22 |
def __init__(self, |
|
22 | def __init__(self,code): | |
23 | """store the macro value, as a single string which can be executed""" |
|
23 | """store the macro value, as a single string which can be executed""" | |
24 |
self.value = |
|
24 | self.value = code.rstrip()+'\n' | |
25 |
|
25 | |||
26 | def __str__(self): |
|
26 | def __str__(self): | |
27 | return self.value |
|
27 | return self.value | |
28 |
|
28 | |||
29 | def __repr__(self): |
|
29 | def __repr__(self): | |
30 | return 'IPython.macro.Macro(%s)' % repr(self.value) |
|
30 | return 'IPython.macro.Macro(%s)' % repr(self.value) | |
31 |
|
31 | |||
32 | def __call__(self,*args): |
|
32 | def __call__(self,*args): | |
33 | IPython.utils.io.Term.cout.flush() |
|
33 | IPython.utils.io.Term.cout.flush() | |
34 | self._ip.user_ns['_margv'] = args |
|
34 | self._ip.user_ns['_margv'] = args | |
35 | self._ip.run_cell(self.value) |
|
35 | self._ip.run_cell(self.value) | |
36 |
|
36 | |||
37 | def __getstate__(self): |
|
37 | def __getstate__(self): | |
38 | """ needed for safe pickling via %store """ |
|
38 | """ needed for safe pickling via %store """ | |
39 | return {'value': self.value} |
|
39 | return {'value': self.value} |
@@ -1,3509 +1,3506 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | 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, StringTypes, format_screen |
|
60 | from IPython.utils.text import LSString, SList, StringTypes, 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 |
|
89 | |||
90 | #*************************************************************************** |
|
90 | #*************************************************************************** | |
91 | # Main class implementing Magic functionality |
|
91 | # Main class implementing Magic functionality | |
92 |
|
92 | |||
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
94 | # on construction of the main InteractiveShell object. Something odd is going |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
96 | # eventually this needs to be clarified. |
|
96 | # eventually this needs to be clarified. | |
97 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
97 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
99 | # make Magic a configurable that InteractiveShell does not subclass. |
|
99 | # make Magic a configurable that InteractiveShell does not subclass. | |
100 |
|
100 | |||
101 | class Magic: |
|
101 | class Magic: | |
102 | """Magic functions for InteractiveShell. |
|
102 | """Magic functions for InteractiveShell. | |
103 |
|
103 | |||
104 | Shell functions which can be reached as %function_name. All magic |
|
104 | Shell functions which can be reached as %function_name. All magic | |
105 | functions should accept a string, which they can parse for their own |
|
105 | functions should accept a string, which they can parse for their own | |
106 | needs. This can make some functions easier to type, eg `%cd ../` |
|
106 | needs. This can make some functions easier to type, eg `%cd ../` | |
107 | vs. `%cd("../")` |
|
107 | vs. `%cd("../")` | |
108 |
|
108 | |||
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
110 | at the command line, but it is is needed in the definition. """ |
|
110 | at the command line, but it is is needed in the definition. """ | |
111 |
|
111 | |||
112 | # class globals |
|
112 | # class globals | |
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
115 |
|
115 | |||
116 | #...................................................................... |
|
116 | #...................................................................... | |
117 | # some utility functions |
|
117 | # some utility functions | |
118 |
|
118 | |||
119 | def __init__(self,shell): |
|
119 | def __init__(self,shell): | |
120 |
|
120 | |||
121 | self.options_table = {} |
|
121 | self.options_table = {} | |
122 | if profile is None: |
|
122 | if profile is None: | |
123 | self.magic_prun = self.profile_missing_notice |
|
123 | self.magic_prun = self.profile_missing_notice | |
124 | self.shell = shell |
|
124 | self.shell = shell | |
125 |
|
125 | |||
126 | # namespace for holding state we may need |
|
126 | # namespace for holding state we may need | |
127 | self._magic_state = Bunch() |
|
127 | self._magic_state = Bunch() | |
128 |
|
128 | |||
129 | def profile_missing_notice(self, *args, **kwargs): |
|
129 | def profile_missing_notice(self, *args, **kwargs): | |
130 | error("""\ |
|
130 | error("""\ | |
131 | The profile module could not be found. It has been removed from the standard |
|
131 | The profile module could not be found. It has been removed from the standard | |
132 | python packages because of its non-free license. To use profiling, install the |
|
132 | python packages because of its non-free license. To use profiling, install the | |
133 | python-profiler package from non-free.""") |
|
133 | python-profiler package from non-free.""") | |
134 |
|
134 | |||
135 | def default_option(self,fn,optstr): |
|
135 | def default_option(self,fn,optstr): | |
136 | """Make an entry in the options_table for fn, with value optstr""" |
|
136 | """Make an entry in the options_table for fn, with value optstr""" | |
137 |
|
137 | |||
138 | if fn not in self.lsmagic(): |
|
138 | if fn not in self.lsmagic(): | |
139 | error("%s is not a magic function" % fn) |
|
139 | error("%s is not a magic function" % fn) | |
140 | self.options_table[fn] = optstr |
|
140 | self.options_table[fn] = optstr | |
141 |
|
141 | |||
142 | def lsmagic(self): |
|
142 | def lsmagic(self): | |
143 | """Return a list of currently available magic functions. |
|
143 | """Return a list of currently available magic functions. | |
144 |
|
144 | |||
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
146 | ['magic_ls','magic_cd',...]""" |
|
146 | ['magic_ls','magic_cd',...]""" | |
147 |
|
147 | |||
148 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
148 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
149 |
|
149 | |||
150 | # magics in class definition |
|
150 | # magics in class definition | |
151 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
151 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
152 | callable(Magic.__dict__[fn]) |
|
152 | callable(Magic.__dict__[fn]) | |
153 | # in instance namespace (run-time user additions) |
|
153 | # in instance namespace (run-time user additions) | |
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
155 | callable(self.__dict__[fn]) |
|
155 | callable(self.__dict__[fn]) | |
156 | # and bound magics by user (so they can access self): |
|
156 | # and bound magics by user (so they can access self): | |
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
158 | callable(self.__class__.__dict__[fn]) |
|
158 | callable(self.__class__.__dict__[fn]) | |
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
160 | filter(inst_magic,self.__dict__.keys()) + \ |
|
160 | filter(inst_magic,self.__dict__.keys()) + \ | |
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
162 | out = [] |
|
162 | out = [] | |
163 | for fn in set(magics): |
|
163 | for fn in set(magics): | |
164 | out.append(fn.replace('magic_','',1)) |
|
164 | out.append(fn.replace('magic_','',1)) | |
165 | out.sort() |
|
165 | out.sort() | |
166 | return out |
|
166 | return out | |
167 |
|
167 | |||
168 | def extract_input_slices(self,slices,raw=False): |
|
168 | def extract_input_slices(self,slices,raw=False): | |
169 | """Return as a string a set of input history slices. |
|
169 | """Return as a string a set of input history slices. | |
170 |
|
170 | |||
171 | Inputs: |
|
171 | Inputs: | |
172 |
|
172 | |||
173 | - slices: the set of slices is given as a list of strings (like |
|
173 | - slices: the set of slices is given as a list of strings (like | |
174 | ['1','4:8','9'], since this function is for use by magic functions |
|
174 | ['1','4:8','9'], since this function is for use by magic functions | |
175 | which get their arguments as strings. |
|
175 | which get their arguments as strings. | |
176 |
|
176 | |||
177 | Optional inputs: |
|
177 | Optional inputs: | |
178 |
|
178 | |||
179 | - raw(False): by default, the processed input is used. If this is |
|
179 | - raw(False): by default, the processed input is used. If this is | |
180 | true, the raw input history is used instead. |
|
180 | true, the raw input history is used instead. | |
181 |
|
181 | |||
182 | Note that slices can be called with two notations: |
|
182 | Note that slices can be called with two notations: | |
183 |
|
183 | |||
184 | N:M -> standard python form, means including items N...(M-1). |
|
184 | N:M -> standard python form, means including items N...(M-1). | |
185 |
|
185 | |||
186 | N-M -> include items N..M (closed endpoint).""" |
|
186 | N-M -> include items N..M (closed endpoint).""" | |
187 |
|
187 | history_manager = self.shell.history_manager | ||
188 | if raw: |
|
|||
189 | hist = self.shell.history_manager.input_hist_raw |
|
|||
190 | else: |
|
|||
191 | hist = self.shell.history_manager.input_hist_parsed |
|
|||
192 |
|
188 | |||
193 | cmds = [] |
|
189 | cmds = [] | |
194 | for chunk in slices: |
|
190 | for chunk in slices: | |
195 | if ':' in chunk: |
|
191 | if ':' in chunk: | |
196 | ini,fin = map(int,chunk.split(':')) |
|
192 | ini,fin = map(int,chunk.split(':')) | |
197 | elif '-' in chunk: |
|
193 | elif '-' in chunk: | |
198 | ini,fin = map(int,chunk.split('-')) |
|
194 | ini,fin = map(int,chunk.split('-')) | |
199 | fin += 1 |
|
195 | fin += 1 | |
200 | else: |
|
196 | else: | |
201 | ini = int(chunk) |
|
197 | ini = int(chunk) | |
202 | fin = ini+1 |
|
198 | fin = ini+1 | |
203 | cmds.append('\n'.join(hist[ini:fin])) |
|
199 | hist = history_manager.get_history((ini,fin), raw=raw, output=False) | |
|
200 | cmds.append('\n'.join(hist[i] for i in sorted(hist.iterkeys()))) | |||
204 | return cmds |
|
201 | return cmds | |
205 |
|
202 | |||
206 | def arg_err(self,func): |
|
203 | def arg_err(self,func): | |
207 | """Print docstring if incorrect arguments were passed""" |
|
204 | """Print docstring if incorrect arguments were passed""" | |
208 | print 'Error in arguments:' |
|
205 | print 'Error in arguments:' | |
209 | print oinspect.getdoc(func) |
|
206 | print oinspect.getdoc(func) | |
210 |
|
207 | |||
211 | def format_latex(self,strng): |
|
208 | def format_latex(self,strng): | |
212 | """Format a string for latex inclusion.""" |
|
209 | """Format a string for latex inclusion.""" | |
213 |
|
210 | |||
214 | # Characters that need to be escaped for latex: |
|
211 | # Characters that need to be escaped for latex: | |
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
212 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
216 | # Magic command names as headers: |
|
213 | # Magic command names as headers: | |
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
214 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
218 | re.MULTILINE) |
|
215 | re.MULTILINE) | |
219 | # Magic commands |
|
216 | # Magic commands | |
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
217 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
221 | re.MULTILINE) |
|
218 | re.MULTILINE) | |
222 | # Paragraph continue |
|
219 | # Paragraph continue | |
223 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
220 | par_re = re.compile(r'\\$',re.MULTILINE) | |
224 |
|
221 | |||
225 | # The "\n" symbol |
|
222 | # The "\n" symbol | |
226 | newline_re = re.compile(r'\\n') |
|
223 | newline_re = re.compile(r'\\n') | |
227 |
|
224 | |||
228 | # Now build the string for output: |
|
225 | # Now build the string for output: | |
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
226 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
227 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
231 | strng) |
|
228 | strng) | |
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
229 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
233 | strng = par_re.sub(r'\\\\',strng) |
|
230 | strng = par_re.sub(r'\\\\',strng) | |
234 | strng = escape_re.sub(r'\\\1',strng) |
|
231 | strng = escape_re.sub(r'\\\1',strng) | |
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
232 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
236 | return strng |
|
233 | return strng | |
237 |
|
234 | |||
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
235 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
239 | """Parse options passed to an argument string. |
|
236 | """Parse options passed to an argument string. | |
240 |
|
237 | |||
241 | The interface is similar to that of getopt(), but it returns back a |
|
238 | The interface is similar to that of getopt(), but it returns back a | |
242 | Struct with the options as keys and the stripped argument string still |
|
239 | Struct with the options as keys and the stripped argument string still | |
243 | as a string. |
|
240 | as a string. | |
244 |
|
241 | |||
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
242 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
246 | This allows us to easily expand variables, glob files, quote |
|
243 | This allows us to easily expand variables, glob files, quote | |
247 | arguments, etc. |
|
244 | arguments, etc. | |
248 |
|
245 | |||
249 | Options: |
|
246 | Options: | |
250 | -mode: default 'string'. If given as 'list', the argument string is |
|
247 | -mode: default 'string'. If given as 'list', the argument string is | |
251 | returned as a list (split on whitespace) instead of a string. |
|
248 | returned as a list (split on whitespace) instead of a string. | |
252 |
|
249 | |||
253 | -list_all: put all option values in lists. Normally only options |
|
250 | -list_all: put all option values in lists. Normally only options | |
254 | appearing more than once are put in a list. |
|
251 | appearing more than once are put in a list. | |
255 |
|
252 | |||
256 | -posix (True): whether to split the input line in POSIX mode or not, |
|
253 | -posix (True): whether to split the input line in POSIX mode or not, | |
257 | as per the conventions outlined in the shlex module from the |
|
254 | as per the conventions outlined in the shlex module from the | |
258 | standard library.""" |
|
255 | standard library.""" | |
259 |
|
256 | |||
260 | # inject default options at the beginning of the input line |
|
257 | # inject default options at the beginning of the input line | |
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
258 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
259 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
263 |
|
260 | |||
264 | mode = kw.get('mode','string') |
|
261 | mode = kw.get('mode','string') | |
265 | if mode not in ['string','list']: |
|
262 | if mode not in ['string','list']: | |
266 | raise ValueError,'incorrect mode given: %s' % mode |
|
263 | raise ValueError,'incorrect mode given: %s' % mode | |
267 | # Get options |
|
264 | # Get options | |
268 | list_all = kw.get('list_all',0) |
|
265 | list_all = kw.get('list_all',0) | |
269 | posix = kw.get('posix', os.name == 'posix') |
|
266 | posix = kw.get('posix', os.name == 'posix') | |
270 |
|
267 | |||
271 | # Check if we have more than one argument to warrant extra processing: |
|
268 | # Check if we have more than one argument to warrant extra processing: | |
272 | odict = {} # Dictionary with options |
|
269 | odict = {} # Dictionary with options | |
273 | args = arg_str.split() |
|
270 | args = arg_str.split() | |
274 | if len(args) >= 1: |
|
271 | if len(args) >= 1: | |
275 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
272 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
276 | # need to look for options |
|
273 | # need to look for options | |
277 | argv = arg_split(arg_str,posix) |
|
274 | argv = arg_split(arg_str,posix) | |
278 | # Do regular option processing |
|
275 | # Do regular option processing | |
279 | try: |
|
276 | try: | |
280 | opts,args = getopt(argv,opt_str,*long_opts) |
|
277 | opts,args = getopt(argv,opt_str,*long_opts) | |
281 | except GetoptError,e: |
|
278 | except GetoptError,e: | |
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
279 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
283 | " ".join(long_opts))) |
|
280 | " ".join(long_opts))) | |
284 | for o,a in opts: |
|
281 | for o,a in opts: | |
285 | if o.startswith('--'): |
|
282 | if o.startswith('--'): | |
286 | o = o[2:] |
|
283 | o = o[2:] | |
287 | else: |
|
284 | else: | |
288 | o = o[1:] |
|
285 | o = o[1:] | |
289 | try: |
|
286 | try: | |
290 | odict[o].append(a) |
|
287 | odict[o].append(a) | |
291 | except AttributeError: |
|
288 | except AttributeError: | |
292 | odict[o] = [odict[o],a] |
|
289 | odict[o] = [odict[o],a] | |
293 | except KeyError: |
|
290 | except KeyError: | |
294 | if list_all: |
|
291 | if list_all: | |
295 | odict[o] = [a] |
|
292 | odict[o] = [a] | |
296 | else: |
|
293 | else: | |
297 | odict[o] = a |
|
294 | odict[o] = a | |
298 |
|
295 | |||
299 | # Prepare opts,args for return |
|
296 | # Prepare opts,args for return | |
300 | opts = Struct(odict) |
|
297 | opts = Struct(odict) | |
301 | if mode == 'string': |
|
298 | if mode == 'string': | |
302 | args = ' '.join(args) |
|
299 | args = ' '.join(args) | |
303 |
|
300 | |||
304 | return opts,args |
|
301 | return opts,args | |
305 |
|
302 | |||
306 | #...................................................................... |
|
303 | #...................................................................... | |
307 | # And now the actual magic functions |
|
304 | # And now the actual magic functions | |
308 |
|
305 | |||
309 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
306 | # Functions for IPython shell work (vars,funcs, config, etc) | |
310 | def magic_lsmagic(self, parameter_s = ''): |
|
307 | def magic_lsmagic(self, parameter_s = ''): | |
311 | """List currently available magic functions.""" |
|
308 | """List currently available magic functions.""" | |
312 | mesc = ESC_MAGIC |
|
309 | mesc = ESC_MAGIC | |
313 | print 'Available magic functions:\n'+mesc+\ |
|
310 | print 'Available magic functions:\n'+mesc+\ | |
314 | (' '+mesc).join(self.lsmagic()) |
|
311 | (' '+mesc).join(self.lsmagic()) | |
315 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
312 | print '\n' + Magic.auto_status[self.shell.automagic] | |
316 | return None |
|
313 | return None | |
317 |
|
314 | |||
318 | def magic_magic(self, parameter_s = ''): |
|
315 | def magic_magic(self, parameter_s = ''): | |
319 | """Print information about the magic function system. |
|
316 | """Print information about the magic function system. | |
320 |
|
317 | |||
321 | Supported formats: -latex, -brief, -rest |
|
318 | Supported formats: -latex, -brief, -rest | |
322 | """ |
|
319 | """ | |
323 |
|
320 | |||
324 | mode = '' |
|
321 | mode = '' | |
325 | try: |
|
322 | try: | |
326 | if parameter_s.split()[0] == '-latex': |
|
323 | if parameter_s.split()[0] == '-latex': | |
327 | mode = 'latex' |
|
324 | mode = 'latex' | |
328 | if parameter_s.split()[0] == '-brief': |
|
325 | if parameter_s.split()[0] == '-brief': | |
329 | mode = 'brief' |
|
326 | mode = 'brief' | |
330 | if parameter_s.split()[0] == '-rest': |
|
327 | if parameter_s.split()[0] == '-rest': | |
331 | mode = 'rest' |
|
328 | mode = 'rest' | |
332 | rest_docs = [] |
|
329 | rest_docs = [] | |
333 | except: |
|
330 | except: | |
334 | pass |
|
331 | pass | |
335 |
|
332 | |||
336 | magic_docs = [] |
|
333 | magic_docs = [] | |
337 | for fname in self.lsmagic(): |
|
334 | for fname in self.lsmagic(): | |
338 | mname = 'magic_' + fname |
|
335 | mname = 'magic_' + fname | |
339 | for space in (Magic,self,self.__class__): |
|
336 | for space in (Magic,self,self.__class__): | |
340 | try: |
|
337 | try: | |
341 | fn = space.__dict__[mname] |
|
338 | fn = space.__dict__[mname] | |
342 | except KeyError: |
|
339 | except KeyError: | |
343 | pass |
|
340 | pass | |
344 | else: |
|
341 | else: | |
345 | break |
|
342 | break | |
346 | if mode == 'brief': |
|
343 | if mode == 'brief': | |
347 | # only first line |
|
344 | # only first line | |
348 | if fn.__doc__: |
|
345 | if fn.__doc__: | |
349 | fndoc = fn.__doc__.split('\n',1)[0] |
|
346 | fndoc = fn.__doc__.split('\n',1)[0] | |
350 | else: |
|
347 | else: | |
351 | fndoc = 'No documentation' |
|
348 | fndoc = 'No documentation' | |
352 | else: |
|
349 | else: | |
353 | if fn.__doc__: |
|
350 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.rstrip() |
|
351 | fndoc = fn.__doc__.rstrip() | |
355 | else: |
|
352 | else: | |
356 | fndoc = 'No documentation' |
|
353 | fndoc = 'No documentation' | |
357 |
|
354 | |||
358 |
|
355 | |||
359 | if mode == 'rest': |
|
356 | if mode == 'rest': | |
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
357 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
361 | fname,fndoc)) |
|
358 | fname,fndoc)) | |
362 |
|
359 | |||
363 | else: |
|
360 | else: | |
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
361 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
365 | fname,fndoc)) |
|
362 | fname,fndoc)) | |
366 |
|
363 | |||
367 | magic_docs = ''.join(magic_docs) |
|
364 | magic_docs = ''.join(magic_docs) | |
368 |
|
365 | |||
369 | if mode == 'rest': |
|
366 | if mode == 'rest': | |
370 | return "".join(rest_docs) |
|
367 | return "".join(rest_docs) | |
371 |
|
368 | |||
372 | if mode == 'latex': |
|
369 | if mode == 'latex': | |
373 | print self.format_latex(magic_docs) |
|
370 | print self.format_latex(magic_docs) | |
374 | return |
|
371 | return | |
375 | else: |
|
372 | else: | |
376 | magic_docs = format_screen(magic_docs) |
|
373 | magic_docs = format_screen(magic_docs) | |
377 | if mode == 'brief': |
|
374 | if mode == 'brief': | |
378 | return magic_docs |
|
375 | return magic_docs | |
379 |
|
376 | |||
380 | outmsg = """ |
|
377 | outmsg = """ | |
381 | IPython's 'magic' functions |
|
378 | IPython's 'magic' functions | |
382 | =========================== |
|
379 | =========================== | |
383 |
|
380 | |||
384 | The magic function system provides a series of functions which allow you to |
|
381 | The magic function system provides a series of functions which allow you to | |
385 | control the behavior of IPython itself, plus a lot of system-type |
|
382 | control the behavior of IPython itself, plus a lot of system-type | |
386 | features. All these functions are prefixed with a % character, but parameters |
|
383 | features. All these functions are prefixed with a % character, but parameters | |
387 | are given without parentheses or quotes. |
|
384 | are given without parentheses or quotes. | |
388 |
|
385 | |||
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
386 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
390 | %automagic function), you don't need to type in the % explicitly. By default, |
|
387 | %automagic function), you don't need to type in the % explicitly. By default, | |
391 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
388 | IPython ships with automagic on, so you should only rarely need the % escape. | |
392 |
|
389 | |||
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
390 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
394 | to 'mydir', if it exists. |
|
391 | to 'mydir', if it exists. | |
395 |
|
392 | |||
396 | You can define your own magic functions to extend the system. See the supplied |
|
393 | You can define your own magic functions to extend the system. See the supplied | |
397 | ipythonrc and example-magic.py files for details (in your ipython |
|
394 | ipythonrc and example-magic.py files for details (in your ipython | |
398 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). |
|
395 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). | |
399 |
|
396 | |||
400 | You can also define your own aliased names for magic functions. In your |
|
397 | You can also define your own aliased names for magic functions. In your | |
401 | ipythonrc file, placing a line like: |
|
398 | ipythonrc file, placing a line like: | |
402 |
|
399 | |||
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
400 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
404 |
|
401 | |||
405 | will define %pf as a new name for %profile. |
|
402 | will define %pf as a new name for %profile. | |
406 |
|
403 | |||
407 | You can also call magics in code using the magic() function, which IPython |
|
404 | You can also call magics in code using the magic() function, which IPython | |
408 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
405 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
409 |
|
406 | |||
410 | For a list of the available magic functions, use %lsmagic. For a description |
|
407 | For a list of the available magic functions, use %lsmagic. For a description | |
411 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
408 | of any of them, type %magic_name?, e.g. '%cd?'. | |
412 |
|
409 | |||
413 | Currently the magic system has the following functions:\n""" |
|
410 | Currently the magic system has the following functions:\n""" | |
414 |
|
411 | |||
415 | mesc = ESC_MAGIC |
|
412 | mesc = ESC_MAGIC | |
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
413 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
417 | "\n\n%s%s\n\n%s" % (outmsg, |
|
414 | "\n\n%s%s\n\n%s" % (outmsg, | |
418 | magic_docs,mesc,mesc, |
|
415 | magic_docs,mesc,mesc, | |
419 | (' '+mesc).join(self.lsmagic()), |
|
416 | (' '+mesc).join(self.lsmagic()), | |
420 | Magic.auto_status[self.shell.automagic] ) ) |
|
417 | Magic.auto_status[self.shell.automagic] ) ) | |
421 | page.page(outmsg) |
|
418 | page.page(outmsg) | |
422 |
|
419 | |||
423 | def magic_automagic(self, parameter_s = ''): |
|
420 | def magic_automagic(self, parameter_s = ''): | |
424 | """Make magic functions callable without having to type the initial %. |
|
421 | """Make magic functions callable without having to type the initial %. | |
425 |
|
422 | |||
426 | Without argumentsl toggles on/off (when off, you must call it as |
|
423 | Without argumentsl toggles on/off (when off, you must call it as | |
427 | %automagic, of course). With arguments it sets the value, and you can |
|
424 | %automagic, of course). With arguments it sets the value, and you can | |
428 | use any of (case insensitive): |
|
425 | use any of (case insensitive): | |
429 |
|
426 | |||
430 | - on,1,True: to activate |
|
427 | - on,1,True: to activate | |
431 |
|
428 | |||
432 | - off,0,False: to deactivate. |
|
429 | - off,0,False: to deactivate. | |
433 |
|
430 | |||
434 | Note that magic functions have lowest priority, so if there's a |
|
431 | Note that magic functions have lowest priority, so if there's a | |
435 | variable whose name collides with that of a magic fn, automagic won't |
|
432 | variable whose name collides with that of a magic fn, automagic won't | |
436 | work for that function (you get the variable instead). However, if you |
|
433 | work for that function (you get the variable instead). However, if you | |
437 | delete the variable (del var), the previously shadowed magic function |
|
434 | delete the variable (del var), the previously shadowed magic function | |
438 | becomes visible to automagic again.""" |
|
435 | becomes visible to automagic again.""" | |
439 |
|
436 | |||
440 | arg = parameter_s.lower() |
|
437 | arg = parameter_s.lower() | |
441 | if parameter_s in ('on','1','true'): |
|
438 | if parameter_s in ('on','1','true'): | |
442 | self.shell.automagic = True |
|
439 | self.shell.automagic = True | |
443 | elif parameter_s in ('off','0','false'): |
|
440 | elif parameter_s in ('off','0','false'): | |
444 | self.shell.automagic = False |
|
441 | self.shell.automagic = False | |
445 | else: |
|
442 | else: | |
446 | self.shell.automagic = not self.shell.automagic |
|
443 | self.shell.automagic = not self.shell.automagic | |
447 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
444 | print '\n' + Magic.auto_status[self.shell.automagic] | |
448 |
|
445 | |||
449 | @testdec.skip_doctest |
|
446 | @testdec.skip_doctest | |
450 | def magic_autocall(self, parameter_s = ''): |
|
447 | def magic_autocall(self, parameter_s = ''): | |
451 | """Make functions callable without having to type parentheses. |
|
448 | """Make functions callable without having to type parentheses. | |
452 |
|
449 | |||
453 | Usage: |
|
450 | Usage: | |
454 |
|
451 | |||
455 | %autocall [mode] |
|
452 | %autocall [mode] | |
456 |
|
453 | |||
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
454 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
458 | value is toggled on and off (remembering the previous state). |
|
455 | value is toggled on and off (remembering the previous state). | |
459 |
|
456 | |||
460 | In more detail, these values mean: |
|
457 | In more detail, these values mean: | |
461 |
|
458 | |||
462 | 0 -> fully disabled |
|
459 | 0 -> fully disabled | |
463 |
|
460 | |||
464 | 1 -> active, but do not apply if there are no arguments on the line. |
|
461 | 1 -> active, but do not apply if there are no arguments on the line. | |
465 |
|
462 | |||
466 | In this mode, you get: |
|
463 | In this mode, you get: | |
467 |
|
464 | |||
468 | In [1]: callable |
|
465 | In [1]: callable | |
469 | Out[1]: <built-in function callable> |
|
466 | Out[1]: <built-in function callable> | |
470 |
|
467 | |||
471 | In [2]: callable 'hello' |
|
468 | In [2]: callable 'hello' | |
472 | ------> callable('hello') |
|
469 | ------> callable('hello') | |
473 | Out[2]: False |
|
470 | Out[2]: False | |
474 |
|
471 | |||
475 | 2 -> Active always. Even if no arguments are present, the callable |
|
472 | 2 -> Active always. Even if no arguments are present, the callable | |
476 | object is called: |
|
473 | object is called: | |
477 |
|
474 | |||
478 | In [2]: float |
|
475 | In [2]: float | |
479 | ------> float() |
|
476 | ------> float() | |
480 | Out[2]: 0.0 |
|
477 | Out[2]: 0.0 | |
481 |
|
478 | |||
482 | Note that even with autocall off, you can still use '/' at the start of |
|
479 | Note that even with autocall off, you can still use '/' at the start of | |
483 | a line to treat the first argument on the command line as a function |
|
480 | a line to treat the first argument on the command line as a function | |
484 | and add parentheses to it: |
|
481 | and add parentheses to it: | |
485 |
|
482 | |||
486 | In [8]: /str 43 |
|
483 | In [8]: /str 43 | |
487 | ------> str(43) |
|
484 | ------> str(43) | |
488 | Out[8]: '43' |
|
485 | Out[8]: '43' | |
489 |
|
486 | |||
490 | # all-random (note for auto-testing) |
|
487 | # all-random (note for auto-testing) | |
491 | """ |
|
488 | """ | |
492 |
|
489 | |||
493 | if parameter_s: |
|
490 | if parameter_s: | |
494 | arg = int(parameter_s) |
|
491 | arg = int(parameter_s) | |
495 | else: |
|
492 | else: | |
496 | arg = 'toggle' |
|
493 | arg = 'toggle' | |
497 |
|
494 | |||
498 | if not arg in (0,1,2,'toggle'): |
|
495 | if not arg in (0,1,2,'toggle'): | |
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
496 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
500 | return |
|
497 | return | |
501 |
|
498 | |||
502 | if arg in (0,1,2): |
|
499 | if arg in (0,1,2): | |
503 | self.shell.autocall = arg |
|
500 | self.shell.autocall = arg | |
504 | else: # toggle |
|
501 | else: # toggle | |
505 | if self.shell.autocall: |
|
502 | if self.shell.autocall: | |
506 | self._magic_state.autocall_save = self.shell.autocall |
|
503 | self._magic_state.autocall_save = self.shell.autocall | |
507 | self.shell.autocall = 0 |
|
504 | self.shell.autocall = 0 | |
508 | else: |
|
505 | else: | |
509 | try: |
|
506 | try: | |
510 | self.shell.autocall = self._magic_state.autocall_save |
|
507 | self.shell.autocall = self._magic_state.autocall_save | |
511 | except AttributeError: |
|
508 | except AttributeError: | |
512 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
509 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
513 |
|
510 | |||
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
511 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
515 |
|
512 | |||
516 |
|
513 | |||
517 | def magic_page(self, parameter_s=''): |
|
514 | def magic_page(self, parameter_s=''): | |
518 | """Pretty print the object and display it through a pager. |
|
515 | """Pretty print the object and display it through a pager. | |
519 |
|
516 | |||
520 | %page [options] OBJECT |
|
517 | %page [options] OBJECT | |
521 |
|
518 | |||
522 | If no object is given, use _ (last output). |
|
519 | If no object is given, use _ (last output). | |
523 |
|
520 | |||
524 | Options: |
|
521 | Options: | |
525 |
|
522 | |||
526 | -r: page str(object), don't pretty-print it.""" |
|
523 | -r: page str(object), don't pretty-print it.""" | |
527 |
|
524 | |||
528 | # After a function contributed by Olivier Aubert, slightly modified. |
|
525 | # After a function contributed by Olivier Aubert, slightly modified. | |
529 |
|
526 | |||
530 | # Process options/args |
|
527 | # Process options/args | |
531 | opts,args = self.parse_options(parameter_s,'r') |
|
528 | opts,args = self.parse_options(parameter_s,'r') | |
532 | raw = 'r' in opts |
|
529 | raw = 'r' in opts | |
533 |
|
530 | |||
534 | oname = args and args or '_' |
|
531 | oname = args and args or '_' | |
535 | info = self._ofind(oname) |
|
532 | info = self._ofind(oname) | |
536 | if info['found']: |
|
533 | if info['found']: | |
537 | txt = (raw and str or pformat)( info['obj'] ) |
|
534 | txt = (raw and str or pformat)( info['obj'] ) | |
538 | page.page(txt) |
|
535 | page.page(txt) | |
539 | else: |
|
536 | else: | |
540 | print 'Object `%s` not found' % oname |
|
537 | print 'Object `%s` not found' % oname | |
541 |
|
538 | |||
542 | def magic_profile(self, parameter_s=''): |
|
539 | def magic_profile(self, parameter_s=''): | |
543 | """Print your currently active IPython profile.""" |
|
540 | """Print your currently active IPython profile.""" | |
544 | if self.shell.profile: |
|
541 | if self.shell.profile: | |
545 | printpl('Current IPython profile: $self.shell.profile.') |
|
542 | printpl('Current IPython profile: $self.shell.profile.') | |
546 | else: |
|
543 | else: | |
547 | print 'No profile active.' |
|
544 | print 'No profile active.' | |
548 |
|
545 | |||
549 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
546 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
550 | """Provide detailed information about an object. |
|
547 | """Provide detailed information about an object. | |
551 |
|
548 | |||
552 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
549 | '%pinfo object' is just a synonym for object? or ?object.""" | |
553 |
|
550 | |||
554 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
551 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
555 |
|
552 | |||
556 |
|
553 | |||
557 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
554 | # detail_level: 0 -> obj? , 1 -> obj?? | |
558 | detail_level = 0 |
|
555 | detail_level = 0 | |
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
556 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
560 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
557 | # happen if the user types 'pinfo foo?' at the cmd line. | |
561 | pinfo,qmark1,oname,qmark2 = \ |
|
558 | pinfo,qmark1,oname,qmark2 = \ | |
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
559 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
563 | if pinfo or qmark1 or qmark2: |
|
560 | if pinfo or qmark1 or qmark2: | |
564 | detail_level = 1 |
|
561 | detail_level = 1 | |
565 | if "*" in oname: |
|
562 | if "*" in oname: | |
566 | self.magic_psearch(oname) |
|
563 | self.magic_psearch(oname) | |
567 | else: |
|
564 | else: | |
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
565 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
569 | namespaces=namespaces) |
|
566 | namespaces=namespaces) | |
570 |
|
567 | |||
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
568 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
572 | """Provide extra detailed information about an object. |
|
569 | """Provide extra detailed information about an object. | |
573 |
|
570 | |||
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
571 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
572 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
576 | namespaces=namespaces) |
|
573 | namespaces=namespaces) | |
577 |
|
574 | |||
578 | @testdec.skip_doctest |
|
575 | @testdec.skip_doctest | |
579 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
576 | def magic_pdef(self, parameter_s='', namespaces=None): | |
580 | """Print the definition header for any callable object. |
|
577 | """Print the definition header for any callable object. | |
581 |
|
578 | |||
582 | If the object is a class, print the constructor information. |
|
579 | If the object is a class, print the constructor information. | |
583 |
|
580 | |||
584 | Examples |
|
581 | Examples | |
585 | -------- |
|
582 | -------- | |
586 | :: |
|
583 | :: | |
587 |
|
584 | |||
588 | In [3]: %pdef urllib.urlopen |
|
585 | In [3]: %pdef urllib.urlopen | |
589 | urllib.urlopen(url, data=None, proxies=None) |
|
586 | urllib.urlopen(url, data=None, proxies=None) | |
590 | """ |
|
587 | """ | |
591 | self._inspect('pdef',parameter_s, namespaces) |
|
588 | self._inspect('pdef',parameter_s, namespaces) | |
592 |
|
589 | |||
593 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
590 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
594 | """Print the docstring for an object. |
|
591 | """Print the docstring for an object. | |
595 |
|
592 | |||
596 | If the given object is a class, it will print both the class and the |
|
593 | If the given object is a class, it will print both the class and the | |
597 | constructor docstrings.""" |
|
594 | constructor docstrings.""" | |
598 | self._inspect('pdoc',parameter_s, namespaces) |
|
595 | self._inspect('pdoc',parameter_s, namespaces) | |
599 |
|
596 | |||
600 | def magic_psource(self, parameter_s='', namespaces=None): |
|
597 | def magic_psource(self, parameter_s='', namespaces=None): | |
601 | """Print (or run through pager) the source code for an object.""" |
|
598 | """Print (or run through pager) the source code for an object.""" | |
602 | self._inspect('psource',parameter_s, namespaces) |
|
599 | self._inspect('psource',parameter_s, namespaces) | |
603 |
|
600 | |||
604 | def magic_pfile(self, parameter_s=''): |
|
601 | def magic_pfile(self, parameter_s=''): | |
605 | """Print (or run through pager) the file where an object is defined. |
|
602 | """Print (or run through pager) the file where an object is defined. | |
606 |
|
603 | |||
607 | The file opens at the line where the object definition begins. IPython |
|
604 | The file opens at the line where the object definition begins. IPython | |
608 | will honor the environment variable PAGER if set, and otherwise will |
|
605 | will honor the environment variable PAGER if set, and otherwise will | |
609 | do its best to print the file in a convenient form. |
|
606 | do its best to print the file in a convenient form. | |
610 |
|
607 | |||
611 | If the given argument is not an object currently defined, IPython will |
|
608 | If the given argument is not an object currently defined, IPython will | |
612 | try to interpret it as a filename (automatically adding a .py extension |
|
609 | try to interpret it as a filename (automatically adding a .py extension | |
613 | if needed). You can thus use %pfile as a syntax highlighting code |
|
610 | if needed). You can thus use %pfile as a syntax highlighting code | |
614 | viewer.""" |
|
611 | viewer.""" | |
615 |
|
612 | |||
616 | # first interpret argument as an object name |
|
613 | # first interpret argument as an object name | |
617 | out = self._inspect('pfile',parameter_s) |
|
614 | out = self._inspect('pfile',parameter_s) | |
618 | # if not, try the input as a filename |
|
615 | # if not, try the input as a filename | |
619 | if out == 'not found': |
|
616 | if out == 'not found': | |
620 | try: |
|
617 | try: | |
621 | filename = get_py_filename(parameter_s) |
|
618 | filename = get_py_filename(parameter_s) | |
622 | except IOError,msg: |
|
619 | except IOError,msg: | |
623 | print msg |
|
620 | print msg | |
624 | return |
|
621 | return | |
625 | page.page(self.shell.inspector.format(file(filename).read())) |
|
622 | page.page(self.shell.inspector.format(file(filename).read())) | |
626 |
|
623 | |||
627 | def magic_psearch(self, parameter_s=''): |
|
624 | def magic_psearch(self, parameter_s=''): | |
628 | """Search for object in namespaces by wildcard. |
|
625 | """Search for object in namespaces by wildcard. | |
629 |
|
626 | |||
630 | %psearch [options] PATTERN [OBJECT TYPE] |
|
627 | %psearch [options] PATTERN [OBJECT TYPE] | |
631 |
|
628 | |||
632 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
629 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
633 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
630 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
634 | rest of the command line must be unchanged (options come first), so |
|
631 | rest of the command line must be unchanged (options come first), so | |
635 | for example the following forms are equivalent |
|
632 | for example the following forms are equivalent | |
636 |
|
633 | |||
637 | %psearch -i a* function |
|
634 | %psearch -i a* function | |
638 | -i a* function? |
|
635 | -i a* function? | |
639 | ?-i a* function |
|
636 | ?-i a* function | |
640 |
|
637 | |||
641 | Arguments: |
|
638 | Arguments: | |
642 |
|
639 | |||
643 | PATTERN |
|
640 | PATTERN | |
644 |
|
641 | |||
645 | where PATTERN is a string containing * as a wildcard similar to its |
|
642 | where PATTERN is a string containing * as a wildcard similar to its | |
646 | use in a shell. The pattern is matched in all namespaces on the |
|
643 | use in a shell. The pattern is matched in all namespaces on the | |
647 | search path. By default objects starting with a single _ are not |
|
644 | search path. By default objects starting with a single _ are not | |
648 | matched, many IPython generated objects have a single |
|
645 | matched, many IPython generated objects have a single | |
649 | underscore. The default is case insensitive matching. Matching is |
|
646 | underscore. The default is case insensitive matching. Matching is | |
650 | also done on the attributes of objects and not only on the objects |
|
647 | also done on the attributes of objects and not only on the objects | |
651 | in a module. |
|
648 | in a module. | |
652 |
|
649 | |||
653 | [OBJECT TYPE] |
|
650 | [OBJECT TYPE] | |
654 |
|
651 | |||
655 | Is the name of a python type from the types module. The name is |
|
652 | Is the name of a python type from the types module. The name is | |
656 | given in lowercase without the ending type, ex. StringType is |
|
653 | given in lowercase without the ending type, ex. StringType is | |
657 | written string. By adding a type here only objects matching the |
|
654 | written string. By adding a type here only objects matching the | |
658 | given type are matched. Using all here makes the pattern match all |
|
655 | given type are matched. Using all here makes the pattern match all | |
659 | types (this is the default). |
|
656 | types (this is the default). | |
660 |
|
657 | |||
661 | Options: |
|
658 | Options: | |
662 |
|
659 | |||
663 | -a: makes the pattern match even objects whose names start with a |
|
660 | -a: makes the pattern match even objects whose names start with a | |
664 | single underscore. These names are normally ommitted from the |
|
661 | single underscore. These names are normally ommitted from the | |
665 | search. |
|
662 | search. | |
666 |
|
663 | |||
667 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
664 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
668 | these options is given, the default is read from your ipythonrc |
|
665 | these options is given, the default is read from your ipythonrc | |
669 | file. The option name which sets this value is |
|
666 | file. The option name which sets this value is | |
670 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
667 | 'wildcards_case_sensitive'. If this option is not specified in your | |
671 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
668 | ipythonrc file, IPython's internal default is to do a case sensitive | |
672 | search. |
|
669 | search. | |
673 |
|
670 | |||
674 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
671 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
675 | specifiy can be searched in any of the following namespaces: |
|
672 | specifiy can be searched in any of the following namespaces: | |
676 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
673 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
677 | 'builtin' and 'user' are the search defaults. Note that you should |
|
674 | 'builtin' and 'user' are the search defaults. Note that you should | |
678 | not use quotes when specifying namespaces. |
|
675 | not use quotes when specifying namespaces. | |
679 |
|
676 | |||
680 | 'Builtin' contains the python module builtin, 'user' contains all |
|
677 | 'Builtin' contains the python module builtin, 'user' contains all | |
681 | user data, 'alias' only contain the shell aliases and no python |
|
678 | user data, 'alias' only contain the shell aliases and no python | |
682 | objects, 'internal' contains objects used by IPython. The |
|
679 | objects, 'internal' contains objects used by IPython. The | |
683 | 'user_global' namespace is only used by embedded IPython instances, |
|
680 | 'user_global' namespace is only used by embedded IPython instances, | |
684 | and it contains module-level globals. You can add namespaces to the |
|
681 | and it contains module-level globals. You can add namespaces to the | |
685 | search with -s or exclude them with -e (these options can be given |
|
682 | search with -s or exclude them with -e (these options can be given | |
686 | more than once). |
|
683 | more than once). | |
687 |
|
684 | |||
688 | Examples: |
|
685 | Examples: | |
689 |
|
686 | |||
690 | %psearch a* -> objects beginning with an a |
|
687 | %psearch a* -> objects beginning with an a | |
691 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
688 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
692 | %psearch a* function -> all functions beginning with an a |
|
689 | %psearch a* function -> all functions beginning with an a | |
693 | %psearch re.e* -> objects beginning with an e in module re |
|
690 | %psearch re.e* -> objects beginning with an e in module re | |
694 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
691 | %psearch r*.e* -> objects that start with e in modules starting in r | |
695 | %psearch r*.* string -> all strings in modules beginning with r |
|
692 | %psearch r*.* string -> all strings in modules beginning with r | |
696 |
|
693 | |||
697 | Case sensitve search: |
|
694 | Case sensitve search: | |
698 |
|
695 | |||
699 | %psearch -c a* list all object beginning with lower case a |
|
696 | %psearch -c a* list all object beginning with lower case a | |
700 |
|
697 | |||
701 | Show objects beginning with a single _: |
|
698 | Show objects beginning with a single _: | |
702 |
|
699 | |||
703 | %psearch -a _* list objects beginning with a single underscore""" |
|
700 | %psearch -a _* list objects beginning with a single underscore""" | |
704 | try: |
|
701 | try: | |
705 | parameter_s = parameter_s.encode('ascii') |
|
702 | parameter_s = parameter_s.encode('ascii') | |
706 | except UnicodeEncodeError: |
|
703 | except UnicodeEncodeError: | |
707 | print 'Python identifiers can only contain ascii characters.' |
|
704 | print 'Python identifiers can only contain ascii characters.' | |
708 | return |
|
705 | return | |
709 |
|
706 | |||
710 | # default namespaces to be searched |
|
707 | # default namespaces to be searched | |
711 | def_search = ['user','builtin'] |
|
708 | def_search = ['user','builtin'] | |
712 |
|
709 | |||
713 | # Process options/args |
|
710 | # Process options/args | |
714 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
711 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
715 | opt = opts.get |
|
712 | opt = opts.get | |
716 | shell = self.shell |
|
713 | shell = self.shell | |
717 | psearch = shell.inspector.psearch |
|
714 | psearch = shell.inspector.psearch | |
718 |
|
715 | |||
719 | # select case options |
|
716 | # select case options | |
720 | if opts.has_key('i'): |
|
717 | if opts.has_key('i'): | |
721 | ignore_case = True |
|
718 | ignore_case = True | |
722 | elif opts.has_key('c'): |
|
719 | elif opts.has_key('c'): | |
723 | ignore_case = False |
|
720 | ignore_case = False | |
724 | else: |
|
721 | else: | |
725 | ignore_case = not shell.wildcards_case_sensitive |
|
722 | ignore_case = not shell.wildcards_case_sensitive | |
726 |
|
723 | |||
727 | # Build list of namespaces to search from user options |
|
724 | # Build list of namespaces to search from user options | |
728 | def_search.extend(opt('s',[])) |
|
725 | def_search.extend(opt('s',[])) | |
729 | ns_exclude = ns_exclude=opt('e',[]) |
|
726 | ns_exclude = ns_exclude=opt('e',[]) | |
730 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
727 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
731 |
|
728 | |||
732 | # Call the actual search |
|
729 | # Call the actual search | |
733 | try: |
|
730 | try: | |
734 | psearch(args,shell.ns_table,ns_search, |
|
731 | psearch(args,shell.ns_table,ns_search, | |
735 | show_all=opt('a'),ignore_case=ignore_case) |
|
732 | show_all=opt('a'),ignore_case=ignore_case) | |
736 | except: |
|
733 | except: | |
737 | shell.showtraceback() |
|
734 | shell.showtraceback() | |
738 |
|
735 | |||
739 | @testdec.skip_doctest |
|
736 | @testdec.skip_doctest | |
740 | def magic_who_ls(self, parameter_s=''): |
|
737 | def magic_who_ls(self, parameter_s=''): | |
741 | """Return a sorted list of all interactive variables. |
|
738 | """Return a sorted list of all interactive variables. | |
742 |
|
739 | |||
743 | If arguments are given, only variables of types matching these |
|
740 | If arguments are given, only variables of types matching these | |
744 | arguments are returned. |
|
741 | arguments are returned. | |
745 |
|
742 | |||
746 | Examples |
|
743 | Examples | |
747 | -------- |
|
744 | -------- | |
748 |
|
745 | |||
749 | Define two variables and list them with who_ls:: |
|
746 | Define two variables and list them with who_ls:: | |
750 |
|
747 | |||
751 | In [1]: alpha = 123 |
|
748 | In [1]: alpha = 123 | |
752 |
|
749 | |||
753 | In [2]: beta = 'test' |
|
750 | In [2]: beta = 'test' | |
754 |
|
751 | |||
755 | In [3]: %who_ls |
|
752 | In [3]: %who_ls | |
756 | Out[3]: ['alpha', 'beta'] |
|
753 | Out[3]: ['alpha', 'beta'] | |
757 |
|
754 | |||
758 | In [4]: %who_ls int |
|
755 | In [4]: %who_ls int | |
759 | Out[4]: ['alpha'] |
|
756 | Out[4]: ['alpha'] | |
760 |
|
757 | |||
761 | In [5]: %who_ls str |
|
758 | In [5]: %who_ls str | |
762 | Out[5]: ['beta'] |
|
759 | Out[5]: ['beta'] | |
763 | """ |
|
760 | """ | |
764 |
|
761 | |||
765 | user_ns = self.shell.user_ns |
|
762 | user_ns = self.shell.user_ns | |
766 | internal_ns = self.shell.internal_ns |
|
763 | internal_ns = self.shell.internal_ns | |
767 | user_ns_hidden = self.shell.user_ns_hidden |
|
764 | user_ns_hidden = self.shell.user_ns_hidden | |
768 | out = [ i for i in user_ns |
|
765 | out = [ i for i in user_ns | |
769 | if not i.startswith('_') \ |
|
766 | if not i.startswith('_') \ | |
770 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
767 | and not (i in internal_ns or i in user_ns_hidden) ] | |
771 |
|
768 | |||
772 | typelist = parameter_s.split() |
|
769 | typelist = parameter_s.split() | |
773 | if typelist: |
|
770 | if typelist: | |
774 | typeset = set(typelist) |
|
771 | typeset = set(typelist) | |
775 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
772 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
776 |
|
773 | |||
777 | out.sort() |
|
774 | out.sort() | |
778 | return out |
|
775 | return out | |
779 |
|
776 | |||
780 | @testdec.skip_doctest |
|
777 | @testdec.skip_doctest | |
781 | def magic_who(self, parameter_s=''): |
|
778 | def magic_who(self, parameter_s=''): | |
782 | """Print all interactive variables, with some minimal formatting. |
|
779 | """Print all interactive variables, with some minimal formatting. | |
783 |
|
780 | |||
784 | If any arguments are given, only variables whose type matches one of |
|
781 | If any arguments are given, only variables whose type matches one of | |
785 | these are printed. For example: |
|
782 | these are printed. For example: | |
786 |
|
783 | |||
787 | %who function str |
|
784 | %who function str | |
788 |
|
785 | |||
789 | will only list functions and strings, excluding all other types of |
|
786 | will only list functions and strings, excluding all other types of | |
790 | variables. To find the proper type names, simply use type(var) at a |
|
787 | variables. To find the proper type names, simply use type(var) at a | |
791 | command line to see how python prints type names. For example: |
|
788 | command line to see how python prints type names. For example: | |
792 |
|
789 | |||
793 | In [1]: type('hello')\\ |
|
790 | In [1]: type('hello')\\ | |
794 | Out[1]: <type 'str'> |
|
791 | Out[1]: <type 'str'> | |
795 |
|
792 | |||
796 | indicates that the type name for strings is 'str'. |
|
793 | indicates that the type name for strings is 'str'. | |
797 |
|
794 | |||
798 | %who always excludes executed names loaded through your configuration |
|
795 | %who always excludes executed names loaded through your configuration | |
799 | file and things which are internal to IPython. |
|
796 | file and things which are internal to IPython. | |
800 |
|
797 | |||
801 | This is deliberate, as typically you may load many modules and the |
|
798 | This is deliberate, as typically you may load many modules and the | |
802 | purpose of %who is to show you only what you've manually defined. |
|
799 | purpose of %who is to show you only what you've manually defined. | |
803 |
|
800 | |||
804 | Examples |
|
801 | Examples | |
805 | -------- |
|
802 | -------- | |
806 |
|
803 | |||
807 | Define two variables and list them with who:: |
|
804 | Define two variables and list them with who:: | |
808 |
|
805 | |||
809 | In [1]: alpha = 123 |
|
806 | In [1]: alpha = 123 | |
810 |
|
807 | |||
811 | In [2]: beta = 'test' |
|
808 | In [2]: beta = 'test' | |
812 |
|
809 | |||
813 | In [3]: %who |
|
810 | In [3]: %who | |
814 | alpha beta |
|
811 | alpha beta | |
815 |
|
812 | |||
816 | In [4]: %who int |
|
813 | In [4]: %who int | |
817 | alpha |
|
814 | alpha | |
818 |
|
815 | |||
819 | In [5]: %who str |
|
816 | In [5]: %who str | |
820 | beta |
|
817 | beta | |
821 | """ |
|
818 | """ | |
822 |
|
819 | |||
823 | varlist = self.magic_who_ls(parameter_s) |
|
820 | varlist = self.magic_who_ls(parameter_s) | |
824 | if not varlist: |
|
821 | if not varlist: | |
825 | if parameter_s: |
|
822 | if parameter_s: | |
826 | print 'No variables match your requested type.' |
|
823 | print 'No variables match your requested type.' | |
827 | else: |
|
824 | else: | |
828 | print 'Interactive namespace is empty.' |
|
825 | print 'Interactive namespace is empty.' | |
829 | return |
|
826 | return | |
830 |
|
827 | |||
831 | # if we have variables, move on... |
|
828 | # if we have variables, move on... | |
832 | count = 0 |
|
829 | count = 0 | |
833 | for i in varlist: |
|
830 | for i in varlist: | |
834 | print i+'\t', |
|
831 | print i+'\t', | |
835 | count += 1 |
|
832 | count += 1 | |
836 | if count > 8: |
|
833 | if count > 8: | |
837 | count = 0 |
|
834 | count = 0 | |
838 |
|
835 | |||
839 |
|
836 | |||
840 |
|
837 | |||
841 | @testdec.skip_doctest |
|
838 | @testdec.skip_doctest | |
842 | def magic_whos(self, parameter_s=''): |
|
839 | def magic_whos(self, parameter_s=''): | |
843 | """Like %who, but gives some extra information about each variable. |
|
840 | """Like %who, but gives some extra information about each variable. | |
844 |
|
841 | |||
845 | The same type filtering of %who can be applied here. |
|
842 | The same type filtering of %who can be applied here. | |
846 |
|
843 | |||
847 | For all variables, the type is printed. Additionally it prints: |
|
844 | For all variables, the type is printed. Additionally it prints: | |
848 |
|
845 | |||
849 | - For {},[],(): their length. |
|
846 | - For {},[],(): their length. | |
850 |
|
847 | |||
851 | - For numpy and Numeric arrays, a summary with shape, number of |
|
848 | - For numpy and Numeric arrays, a summary with shape, number of | |
852 | elements, typecode and size in memory. |
|
849 | elements, typecode and size in memory. | |
853 |
|
850 | |||
854 | - Everything else: a string representation, snipping their middle if |
|
851 | - Everything else: a string representation, snipping their middle if | |
855 | too long. |
|
852 | too long. | |
856 |
|
853 | |||
857 | Examples |
|
854 | Examples | |
858 | -------- |
|
855 | -------- | |
859 |
|
856 | |||
860 | Define two variables and list them with whos:: |
|
857 | Define two variables and list them with whos:: | |
861 |
|
858 | |||
862 | In [1]: alpha = 123 |
|
859 | In [1]: alpha = 123 | |
863 |
|
860 | |||
864 | In [2]: beta = 'test' |
|
861 | In [2]: beta = 'test' | |
865 |
|
862 | |||
866 | In [3]: %whos |
|
863 | In [3]: %whos | |
867 | Variable Type Data/Info |
|
864 | Variable Type Data/Info | |
868 | -------------------------------- |
|
865 | -------------------------------- | |
869 | alpha int 123 |
|
866 | alpha int 123 | |
870 | beta str test |
|
867 | beta str test | |
871 | """ |
|
868 | """ | |
872 |
|
869 | |||
873 | varnames = self.magic_who_ls(parameter_s) |
|
870 | varnames = self.magic_who_ls(parameter_s) | |
874 | if not varnames: |
|
871 | if not varnames: | |
875 | if parameter_s: |
|
872 | if parameter_s: | |
876 | print 'No variables match your requested type.' |
|
873 | print 'No variables match your requested type.' | |
877 | else: |
|
874 | else: | |
878 | print 'Interactive namespace is empty.' |
|
875 | print 'Interactive namespace is empty.' | |
879 | return |
|
876 | return | |
880 |
|
877 | |||
881 | # if we have variables, move on... |
|
878 | # if we have variables, move on... | |
882 |
|
879 | |||
883 | # for these types, show len() instead of data: |
|
880 | # for these types, show len() instead of data: | |
884 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
881 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
885 |
|
882 | |||
886 | # for numpy/Numeric arrays, display summary info |
|
883 | # for numpy/Numeric arrays, display summary info | |
887 | try: |
|
884 | try: | |
888 | import numpy |
|
885 | import numpy | |
889 | except ImportError: |
|
886 | except ImportError: | |
890 | ndarray_type = None |
|
887 | ndarray_type = None | |
891 | else: |
|
888 | else: | |
892 | ndarray_type = numpy.ndarray.__name__ |
|
889 | ndarray_type = numpy.ndarray.__name__ | |
893 | try: |
|
890 | try: | |
894 | import Numeric |
|
891 | import Numeric | |
895 | except ImportError: |
|
892 | except ImportError: | |
896 | array_type = None |
|
893 | array_type = None | |
897 | else: |
|
894 | else: | |
898 | array_type = Numeric.ArrayType.__name__ |
|
895 | array_type = Numeric.ArrayType.__name__ | |
899 |
|
896 | |||
900 | # Find all variable names and types so we can figure out column sizes |
|
897 | # Find all variable names and types so we can figure out column sizes | |
901 | def get_vars(i): |
|
898 | def get_vars(i): | |
902 | return self.shell.user_ns[i] |
|
899 | return self.shell.user_ns[i] | |
903 |
|
900 | |||
904 | # some types are well known and can be shorter |
|
901 | # some types are well known and can be shorter | |
905 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
902 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
906 | def type_name(v): |
|
903 | def type_name(v): | |
907 | tn = type(v).__name__ |
|
904 | tn = type(v).__name__ | |
908 | return abbrevs.get(tn,tn) |
|
905 | return abbrevs.get(tn,tn) | |
909 |
|
906 | |||
910 | varlist = map(get_vars,varnames) |
|
907 | varlist = map(get_vars,varnames) | |
911 |
|
908 | |||
912 | typelist = [] |
|
909 | typelist = [] | |
913 | for vv in varlist: |
|
910 | for vv in varlist: | |
914 | tt = type_name(vv) |
|
911 | tt = type_name(vv) | |
915 |
|
912 | |||
916 | if tt=='instance': |
|
913 | if tt=='instance': | |
917 | typelist.append( abbrevs.get(str(vv.__class__), |
|
914 | typelist.append( abbrevs.get(str(vv.__class__), | |
918 | str(vv.__class__))) |
|
915 | str(vv.__class__))) | |
919 | else: |
|
916 | else: | |
920 | typelist.append(tt) |
|
917 | typelist.append(tt) | |
921 |
|
918 | |||
922 | # column labels and # of spaces as separator |
|
919 | # column labels and # of spaces as separator | |
923 | varlabel = 'Variable' |
|
920 | varlabel = 'Variable' | |
924 | typelabel = 'Type' |
|
921 | typelabel = 'Type' | |
925 | datalabel = 'Data/Info' |
|
922 | datalabel = 'Data/Info' | |
926 | colsep = 3 |
|
923 | colsep = 3 | |
927 | # variable format strings |
|
924 | # variable format strings | |
928 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
925 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
929 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
926 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
930 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
927 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
931 | # find the size of the columns to format the output nicely |
|
928 | # find the size of the columns to format the output nicely | |
932 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
929 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
933 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
930 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
934 | # table header |
|
931 | # table header | |
935 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
932 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
936 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
933 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
937 | # and the table itself |
|
934 | # and the table itself | |
938 | kb = 1024 |
|
935 | kb = 1024 | |
939 | Mb = 1048576 # kb**2 |
|
936 | Mb = 1048576 # kb**2 | |
940 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
937 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
941 | print itpl(vformat), |
|
938 | print itpl(vformat), | |
942 | if vtype in seq_types: |
|
939 | if vtype in seq_types: | |
943 | print len(var) |
|
940 | print len(var) | |
944 | elif vtype in [array_type,ndarray_type]: |
|
941 | elif vtype in [array_type,ndarray_type]: | |
945 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
942 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
946 | if vtype==ndarray_type: |
|
943 | if vtype==ndarray_type: | |
947 | # numpy |
|
944 | # numpy | |
948 | vsize = var.size |
|
945 | vsize = var.size | |
949 | vbytes = vsize*var.itemsize |
|
946 | vbytes = vsize*var.itemsize | |
950 | vdtype = var.dtype |
|
947 | vdtype = var.dtype | |
951 | else: |
|
948 | else: | |
952 | # Numeric |
|
949 | # Numeric | |
953 | vsize = Numeric.size(var) |
|
950 | vsize = Numeric.size(var) | |
954 | vbytes = vsize*var.itemsize() |
|
951 | vbytes = vsize*var.itemsize() | |
955 | vdtype = var.typecode() |
|
952 | vdtype = var.typecode() | |
956 |
|
953 | |||
957 | if vbytes < 100000: |
|
954 | if vbytes < 100000: | |
958 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
955 | print aformat % (vshape,vsize,vdtype,vbytes) | |
959 | else: |
|
956 | else: | |
960 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
957 | print aformat % (vshape,vsize,vdtype,vbytes), | |
961 | if vbytes < Mb: |
|
958 | if vbytes < Mb: | |
962 | print '(%s kb)' % (vbytes/kb,) |
|
959 | print '(%s kb)' % (vbytes/kb,) | |
963 | else: |
|
960 | else: | |
964 | print '(%s Mb)' % (vbytes/Mb,) |
|
961 | print '(%s Mb)' % (vbytes/Mb,) | |
965 | else: |
|
962 | else: | |
966 | try: |
|
963 | try: | |
967 | vstr = str(var) |
|
964 | vstr = str(var) | |
968 | except UnicodeEncodeError: |
|
965 | except UnicodeEncodeError: | |
969 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
966 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
970 | 'backslashreplace') |
|
967 | 'backslashreplace') | |
971 | vstr = vstr.replace('\n','\\n') |
|
968 | vstr = vstr.replace('\n','\\n') | |
972 | if len(vstr) < 50: |
|
969 | if len(vstr) < 50: | |
973 | print vstr |
|
970 | print vstr | |
974 | else: |
|
971 | else: | |
975 | printpl(vfmt_short) |
|
972 | printpl(vfmt_short) | |
976 |
|
973 | |||
977 | def magic_reset(self, parameter_s=''): |
|
974 | def magic_reset(self, parameter_s=''): | |
978 | """Resets the namespace by removing all names defined by the user. |
|
975 | """Resets the namespace by removing all names defined by the user. | |
979 |
|
976 | |||
980 | Input/Output history are left around in case you need them. |
|
977 | Input/Output history are left around in case you need them. | |
981 |
|
978 | |||
982 | Parameters |
|
979 | Parameters | |
983 | ---------- |
|
980 | ---------- | |
984 | -y : force reset without asking for confirmation. |
|
981 | -y : force reset without asking for confirmation. | |
985 |
|
982 | |||
986 | Examples |
|
983 | Examples | |
987 | -------- |
|
984 | -------- | |
988 | In [6]: a = 1 |
|
985 | In [6]: a = 1 | |
989 |
|
986 | |||
990 | In [7]: a |
|
987 | In [7]: a | |
991 | Out[7]: 1 |
|
988 | Out[7]: 1 | |
992 |
|
989 | |||
993 | In [8]: 'a' in _ip.user_ns |
|
990 | In [8]: 'a' in _ip.user_ns | |
994 | Out[8]: True |
|
991 | Out[8]: True | |
995 |
|
992 | |||
996 | In [9]: %reset -f |
|
993 | In [9]: %reset -f | |
997 |
|
994 | |||
998 | In [10]: 'a' in _ip.user_ns |
|
995 | In [10]: 'a' in _ip.user_ns | |
999 | Out[10]: False |
|
996 | Out[10]: False | |
1000 | """ |
|
997 | """ | |
1001 |
|
998 | |||
1002 | if parameter_s == '-f': |
|
999 | if parameter_s == '-f': | |
1003 | ans = True |
|
1000 | ans = True | |
1004 | else: |
|
1001 | else: | |
1005 | ans = self.shell.ask_yes_no( |
|
1002 | ans = self.shell.ask_yes_no( | |
1006 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1003 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1007 | if not ans: |
|
1004 | if not ans: | |
1008 | print 'Nothing done.' |
|
1005 | print 'Nothing done.' | |
1009 | return |
|
1006 | return | |
1010 | user_ns = self.shell.user_ns |
|
1007 | user_ns = self.shell.user_ns | |
1011 | for i in self.magic_who_ls(): |
|
1008 | for i in self.magic_who_ls(): | |
1012 | del(user_ns[i]) |
|
1009 | del(user_ns[i]) | |
1013 |
|
1010 | |||
1014 | # Also flush the private list of module references kept for script |
|
1011 | # Also flush the private list of module references kept for script | |
1015 | # execution protection |
|
1012 | # execution protection | |
1016 | self.shell.clear_main_mod_cache() |
|
1013 | self.shell.clear_main_mod_cache() | |
1017 |
|
1014 | |||
1018 | def magic_reset_selective(self, parameter_s=''): |
|
1015 | def magic_reset_selective(self, parameter_s=''): | |
1019 | """Resets the namespace by removing names defined by the user. |
|
1016 | """Resets the namespace by removing names defined by the user. | |
1020 |
|
1017 | |||
1021 | Input/Output history are left around in case you need them. |
|
1018 | Input/Output history are left around in case you need them. | |
1022 |
|
1019 | |||
1023 | %reset_selective [-f] regex |
|
1020 | %reset_selective [-f] regex | |
1024 |
|
1021 | |||
1025 | No action is taken if regex is not included |
|
1022 | No action is taken if regex is not included | |
1026 |
|
1023 | |||
1027 | Options |
|
1024 | Options | |
1028 | -f : force reset without asking for confirmation. |
|
1025 | -f : force reset without asking for confirmation. | |
1029 |
|
1026 | |||
1030 | Examples |
|
1027 | Examples | |
1031 | -------- |
|
1028 | -------- | |
1032 |
|
1029 | |||
1033 | We first fully reset the namespace so your output looks identical to |
|
1030 | We first fully reset the namespace so your output looks identical to | |
1034 | this example for pedagogical reasons; in practice you do not need a |
|
1031 | this example for pedagogical reasons; in practice you do not need a | |
1035 | full reset. |
|
1032 | full reset. | |
1036 |
|
1033 | |||
1037 | In [1]: %reset -f |
|
1034 | In [1]: %reset -f | |
1038 |
|
1035 | |||
1039 | Now, with a clean namespace we can make a few variables and use |
|
1036 | Now, with a clean namespace we can make a few variables and use | |
1040 | %reset_selective to only delete names that match our regexp: |
|
1037 | %reset_selective to only delete names that match our regexp: | |
1041 |
|
1038 | |||
1042 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1039 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1043 |
|
1040 | |||
1044 | In [3]: who_ls |
|
1041 | In [3]: who_ls | |
1045 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1042 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1046 |
|
1043 | |||
1047 | In [4]: %reset_selective -f b[2-3]m |
|
1044 | In [4]: %reset_selective -f b[2-3]m | |
1048 |
|
1045 | |||
1049 | In [5]: who_ls |
|
1046 | In [5]: who_ls | |
1050 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1047 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1051 |
|
1048 | |||
1052 | In [6]: %reset_selective -f d |
|
1049 | In [6]: %reset_selective -f d | |
1053 |
|
1050 | |||
1054 | In [7]: who_ls |
|
1051 | In [7]: who_ls | |
1055 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1052 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1056 |
|
1053 | |||
1057 | In [8]: %reset_selective -f c |
|
1054 | In [8]: %reset_selective -f c | |
1058 |
|
1055 | |||
1059 | In [9]: who_ls |
|
1056 | In [9]: who_ls | |
1060 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1057 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1061 |
|
1058 | |||
1062 | In [10]: %reset_selective -f b |
|
1059 | In [10]: %reset_selective -f b | |
1063 |
|
1060 | |||
1064 | In [11]: who_ls |
|
1061 | In [11]: who_ls | |
1065 | Out[11]: ['a'] |
|
1062 | Out[11]: ['a'] | |
1066 | """ |
|
1063 | """ | |
1067 |
|
1064 | |||
1068 | opts, regex = self.parse_options(parameter_s,'f') |
|
1065 | opts, regex = self.parse_options(parameter_s,'f') | |
1069 |
|
1066 | |||
1070 | if opts.has_key('f'): |
|
1067 | if opts.has_key('f'): | |
1071 | ans = True |
|
1068 | ans = True | |
1072 | else: |
|
1069 | else: | |
1073 | ans = self.shell.ask_yes_no( |
|
1070 | ans = self.shell.ask_yes_no( | |
1074 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1071 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1075 | if not ans: |
|
1072 | if not ans: | |
1076 | print 'Nothing done.' |
|
1073 | print 'Nothing done.' | |
1077 | return |
|
1074 | return | |
1078 | user_ns = self.shell.user_ns |
|
1075 | user_ns = self.shell.user_ns | |
1079 | if not regex: |
|
1076 | if not regex: | |
1080 | print 'No regex pattern specified. Nothing done.' |
|
1077 | print 'No regex pattern specified. Nothing done.' | |
1081 | return |
|
1078 | return | |
1082 | else: |
|
1079 | else: | |
1083 | try: |
|
1080 | try: | |
1084 | m = re.compile(regex) |
|
1081 | m = re.compile(regex) | |
1085 | except TypeError: |
|
1082 | except TypeError: | |
1086 | raise TypeError('regex must be a string or compiled pattern') |
|
1083 | raise TypeError('regex must be a string or compiled pattern') | |
1087 | for i in self.magic_who_ls(): |
|
1084 | for i in self.magic_who_ls(): | |
1088 | if m.search(i): |
|
1085 | if m.search(i): | |
1089 | del(user_ns[i]) |
|
1086 | del(user_ns[i]) | |
1090 |
|
1087 | |||
1091 | def magic_logstart(self,parameter_s=''): |
|
1088 | def magic_logstart(self,parameter_s=''): | |
1092 | """Start logging anywhere in a session. |
|
1089 | """Start logging anywhere in a session. | |
1093 |
|
1090 | |||
1094 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1091 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1095 |
|
1092 | |||
1096 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1093 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1097 | current directory, in 'rotate' mode (see below). |
|
1094 | current directory, in 'rotate' mode (see below). | |
1098 |
|
1095 | |||
1099 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1096 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1100 | history up to that point and then continues logging. |
|
1097 | history up to that point and then continues logging. | |
1101 |
|
1098 | |||
1102 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1099 | %logstart takes a second optional parameter: logging mode. This can be one | |
1103 | of (note that the modes are given unquoted):\\ |
|
1100 | of (note that the modes are given unquoted):\\ | |
1104 | append: well, that says it.\\ |
|
1101 | append: well, that says it.\\ | |
1105 | backup: rename (if exists) to name~ and start name.\\ |
|
1102 | backup: rename (if exists) to name~ and start name.\\ | |
1106 | global: single logfile in your home dir, appended to.\\ |
|
1103 | global: single logfile in your home dir, appended to.\\ | |
1107 | over : overwrite existing log.\\ |
|
1104 | over : overwrite existing log.\\ | |
1108 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1105 | rotate: create rotating logs name.1~, name.2~, etc. | |
1109 |
|
1106 | |||
1110 | Options: |
|
1107 | Options: | |
1111 |
|
1108 | |||
1112 | -o: log also IPython's output. In this mode, all commands which |
|
1109 | -o: log also IPython's output. In this mode, all commands which | |
1113 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1110 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1114 | their corresponding input line. The output lines are always |
|
1111 | their corresponding input line. The output lines are always | |
1115 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1112 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1116 | Python code. |
|
1113 | Python code. | |
1117 |
|
1114 | |||
1118 | Since this marker is always the same, filtering only the output from |
|
1115 | Since this marker is always the same, filtering only the output from | |
1119 | a log is very easy, using for example a simple awk call: |
|
1116 | a log is very easy, using for example a simple awk call: | |
1120 |
|
1117 | |||
1121 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1118 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1122 |
|
1119 | |||
1123 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1120 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1124 | input, so that user lines are logged in their final form, converted |
|
1121 | input, so that user lines are logged in their final form, converted | |
1125 | into valid Python. For example, %Exit is logged as |
|
1122 | into valid Python. For example, %Exit is logged as | |
1126 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1123 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1127 | exactly as typed, with no transformations applied. |
|
1124 | exactly as typed, with no transformations applied. | |
1128 |
|
1125 | |||
1129 | -t: put timestamps before each input line logged (these are put in |
|
1126 | -t: put timestamps before each input line logged (these are put in | |
1130 | comments).""" |
|
1127 | comments).""" | |
1131 |
|
1128 | |||
1132 | opts,par = self.parse_options(parameter_s,'ort') |
|
1129 | opts,par = self.parse_options(parameter_s,'ort') | |
1133 | log_output = 'o' in opts |
|
1130 | log_output = 'o' in opts | |
1134 | log_raw_input = 'r' in opts |
|
1131 | log_raw_input = 'r' in opts | |
1135 | timestamp = 't' in opts |
|
1132 | timestamp = 't' in opts | |
1136 |
|
1133 | |||
1137 | logger = self.shell.logger |
|
1134 | logger = self.shell.logger | |
1138 |
|
1135 | |||
1139 | # if no args are given, the defaults set in the logger constructor by |
|
1136 | # if no args are given, the defaults set in the logger constructor by | |
1140 | # ipytohn remain valid |
|
1137 | # ipytohn remain valid | |
1141 | if par: |
|
1138 | if par: | |
1142 | try: |
|
1139 | try: | |
1143 | logfname,logmode = par.split() |
|
1140 | logfname,logmode = par.split() | |
1144 | except: |
|
1141 | except: | |
1145 | logfname = par |
|
1142 | logfname = par | |
1146 | logmode = 'backup' |
|
1143 | logmode = 'backup' | |
1147 | else: |
|
1144 | else: | |
1148 | logfname = logger.logfname |
|
1145 | logfname = logger.logfname | |
1149 | logmode = logger.logmode |
|
1146 | logmode = logger.logmode | |
1150 | # put logfname into rc struct as if it had been called on the command |
|
1147 | # put logfname into rc struct as if it had been called on the command | |
1151 | # line, so it ends up saved in the log header Save it in case we need |
|
1148 | # line, so it ends up saved in the log header Save it in case we need | |
1152 | # to restore it... |
|
1149 | # to restore it... | |
1153 | old_logfile = self.shell.logfile |
|
1150 | old_logfile = self.shell.logfile | |
1154 | if logfname: |
|
1151 | if logfname: | |
1155 | logfname = os.path.expanduser(logfname) |
|
1152 | logfname = os.path.expanduser(logfname) | |
1156 | self.shell.logfile = logfname |
|
1153 | self.shell.logfile = logfname | |
1157 |
|
1154 | |||
1158 | loghead = '# IPython log file\n\n' |
|
1155 | loghead = '# IPython log file\n\n' | |
1159 | try: |
|
1156 | try: | |
1160 | started = logger.logstart(logfname,loghead,logmode, |
|
1157 | started = logger.logstart(logfname,loghead,logmode, | |
1161 | log_output,timestamp,log_raw_input) |
|
1158 | log_output,timestamp,log_raw_input) | |
1162 | except: |
|
1159 | except: | |
1163 | self.shell.logfile = old_logfile |
|
1160 | self.shell.logfile = old_logfile | |
1164 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1161 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1165 | else: |
|
1162 | else: | |
1166 | # log input history up to this point, optionally interleaving |
|
1163 | # log input history up to this point, optionally interleaving | |
1167 | # output if requested |
|
1164 | # output if requested | |
1168 |
|
1165 | |||
1169 | if timestamp: |
|
1166 | if timestamp: | |
1170 | # disable timestamping for the previous history, since we've |
|
1167 | # disable timestamping for the previous history, since we've | |
1171 | # lost those already (no time machine here). |
|
1168 | # lost those already (no time machine here). | |
1172 | logger.timestamp = False |
|
1169 | logger.timestamp = False | |
1173 |
|
1170 | |||
1174 | if log_raw_input: |
|
1171 | if log_raw_input: | |
1175 | input_hist = self.shell.history_manager.input_hist_raw |
|
1172 | input_hist = self.shell.history_manager.input_hist_raw | |
1176 | else: |
|
1173 | else: | |
1177 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1174 | input_hist = self.shell.history_manager.input_hist_parsed | |
1178 |
|
1175 | |||
1179 | if log_output: |
|
1176 | if log_output: | |
1180 | log_write = logger.log_write |
|
1177 | log_write = logger.log_write | |
1181 | output_hist = self.shell.history_manager.output_hist |
|
1178 | output_hist = self.shell.history_manager.output_hist | |
1182 | for n in range(1,len(input_hist)-1): |
|
1179 | for n in range(1,len(input_hist)-1): | |
1183 | log_write(input_hist[n].rstrip()) |
|
1180 | log_write(input_hist[n].rstrip()) | |
1184 | if n in output_hist: |
|
1181 | if n in output_hist: | |
1185 | log_write(repr(output_hist[n]),'output') |
|
1182 | log_write(repr(output_hist[n]),'output') | |
1186 | else: |
|
1183 | else: | |
1187 | logger.log_write(''.join(input_hist[1:])) |
|
1184 | logger.log_write(''.join(input_hist[1:])) | |
1188 | if timestamp: |
|
1185 | if timestamp: | |
1189 | # re-enable timestamping |
|
1186 | # re-enable timestamping | |
1190 | logger.timestamp = True |
|
1187 | logger.timestamp = True | |
1191 |
|
1188 | |||
1192 | print ('Activating auto-logging. ' |
|
1189 | print ('Activating auto-logging. ' | |
1193 | 'Current session state plus future input saved.') |
|
1190 | 'Current session state plus future input saved.') | |
1194 | logger.logstate() |
|
1191 | logger.logstate() | |
1195 |
|
1192 | |||
1196 | def magic_logstop(self,parameter_s=''): |
|
1193 | def magic_logstop(self,parameter_s=''): | |
1197 | """Fully stop logging and close log file. |
|
1194 | """Fully stop logging and close log file. | |
1198 |
|
1195 | |||
1199 | In order to start logging again, a new %logstart call needs to be made, |
|
1196 | In order to start logging again, a new %logstart call needs to be made, | |
1200 | possibly (though not necessarily) with a new filename, mode and other |
|
1197 | possibly (though not necessarily) with a new filename, mode and other | |
1201 | options.""" |
|
1198 | options.""" | |
1202 | self.logger.logstop() |
|
1199 | self.logger.logstop() | |
1203 |
|
1200 | |||
1204 | def magic_logoff(self,parameter_s=''): |
|
1201 | def magic_logoff(self,parameter_s=''): | |
1205 | """Temporarily stop logging. |
|
1202 | """Temporarily stop logging. | |
1206 |
|
1203 | |||
1207 | You must have previously started logging.""" |
|
1204 | You must have previously started logging.""" | |
1208 | self.shell.logger.switch_log(0) |
|
1205 | self.shell.logger.switch_log(0) | |
1209 |
|
1206 | |||
1210 | def magic_logon(self,parameter_s=''): |
|
1207 | def magic_logon(self,parameter_s=''): | |
1211 | """Restart logging. |
|
1208 | """Restart logging. | |
1212 |
|
1209 | |||
1213 | This function is for restarting logging which you've temporarily |
|
1210 | This function is for restarting logging which you've temporarily | |
1214 | stopped with %logoff. For starting logging for the first time, you |
|
1211 | stopped with %logoff. For starting logging for the first time, you | |
1215 | must use the %logstart function, which allows you to specify an |
|
1212 | must use the %logstart function, which allows you to specify an | |
1216 | optional log filename.""" |
|
1213 | optional log filename.""" | |
1217 |
|
1214 | |||
1218 | self.shell.logger.switch_log(1) |
|
1215 | self.shell.logger.switch_log(1) | |
1219 |
|
1216 | |||
1220 | def magic_logstate(self,parameter_s=''): |
|
1217 | def magic_logstate(self,parameter_s=''): | |
1221 | """Print the status of the logging system.""" |
|
1218 | """Print the status of the logging system.""" | |
1222 |
|
1219 | |||
1223 | self.shell.logger.logstate() |
|
1220 | self.shell.logger.logstate() | |
1224 |
|
1221 | |||
1225 | def magic_pdb(self, parameter_s=''): |
|
1222 | def magic_pdb(self, parameter_s=''): | |
1226 | """Control the automatic calling of the pdb interactive debugger. |
|
1223 | """Control the automatic calling of the pdb interactive debugger. | |
1227 |
|
1224 | |||
1228 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1225 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1229 | argument it works as a toggle. |
|
1226 | argument it works as a toggle. | |
1230 |
|
1227 | |||
1231 | When an exception is triggered, IPython can optionally call the |
|
1228 | When an exception is triggered, IPython can optionally call the | |
1232 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1229 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1233 | this feature on and off. |
|
1230 | this feature on and off. | |
1234 |
|
1231 | |||
1235 | The initial state of this feature is set in your ipythonrc |
|
1232 | The initial state of this feature is set in your ipythonrc | |
1236 | configuration file (the variable is called 'pdb'). |
|
1233 | configuration file (the variable is called 'pdb'). | |
1237 |
|
1234 | |||
1238 | If you want to just activate the debugger AFTER an exception has fired, |
|
1235 | If you want to just activate the debugger AFTER an exception has fired, | |
1239 | without having to type '%pdb on' and rerunning your code, you can use |
|
1236 | without having to type '%pdb on' and rerunning your code, you can use | |
1240 | the %debug magic.""" |
|
1237 | the %debug magic.""" | |
1241 |
|
1238 | |||
1242 | par = parameter_s.strip().lower() |
|
1239 | par = parameter_s.strip().lower() | |
1243 |
|
1240 | |||
1244 | if par: |
|
1241 | if par: | |
1245 | try: |
|
1242 | try: | |
1246 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1243 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1247 | except KeyError: |
|
1244 | except KeyError: | |
1248 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1245 | print ('Incorrect argument. Use on/1, off/0, ' | |
1249 | 'or nothing for a toggle.') |
|
1246 | 'or nothing for a toggle.') | |
1250 | return |
|
1247 | return | |
1251 | else: |
|
1248 | else: | |
1252 | # toggle |
|
1249 | # toggle | |
1253 | new_pdb = not self.shell.call_pdb |
|
1250 | new_pdb = not self.shell.call_pdb | |
1254 |
|
1251 | |||
1255 | # set on the shell |
|
1252 | # set on the shell | |
1256 | self.shell.call_pdb = new_pdb |
|
1253 | self.shell.call_pdb = new_pdb | |
1257 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1254 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1258 |
|
1255 | |||
1259 | def magic_debug(self, parameter_s=''): |
|
1256 | def magic_debug(self, parameter_s=''): | |
1260 | """Activate the interactive debugger in post-mortem mode. |
|
1257 | """Activate the interactive debugger in post-mortem mode. | |
1261 |
|
1258 | |||
1262 | If an exception has just occurred, this lets you inspect its stack |
|
1259 | If an exception has just occurred, this lets you inspect its stack | |
1263 | frames interactively. Note that this will always work only on the last |
|
1260 | frames interactively. Note that this will always work only on the last | |
1264 | traceback that occurred, so you must call this quickly after an |
|
1261 | traceback that occurred, so you must call this quickly after an | |
1265 | exception that you wish to inspect has fired, because if another one |
|
1262 | exception that you wish to inspect has fired, because if another one | |
1266 | occurs, it clobbers the previous one. |
|
1263 | occurs, it clobbers the previous one. | |
1267 |
|
1264 | |||
1268 | If you want IPython to automatically do this on every exception, see |
|
1265 | If you want IPython to automatically do this on every exception, see | |
1269 | the %pdb magic for more details. |
|
1266 | the %pdb magic for more details. | |
1270 | """ |
|
1267 | """ | |
1271 | self.shell.debugger(force=True) |
|
1268 | self.shell.debugger(force=True) | |
1272 |
|
1269 | |||
1273 | @testdec.skip_doctest |
|
1270 | @testdec.skip_doctest | |
1274 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1271 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1275 | opts=None,arg_lst=None,prog_ns=None): |
|
1272 | opts=None,arg_lst=None,prog_ns=None): | |
1276 |
|
1273 | |||
1277 | """Run a statement through the python code profiler. |
|
1274 | """Run a statement through the python code profiler. | |
1278 |
|
1275 | |||
1279 | Usage: |
|
1276 | Usage: | |
1280 | %prun [options] statement |
|
1277 | %prun [options] statement | |
1281 |
|
1278 | |||
1282 | The given statement (which doesn't require quote marks) is run via the |
|
1279 | The given statement (which doesn't require quote marks) is run via the | |
1283 | python profiler in a manner similar to the profile.run() function. |
|
1280 | python profiler in a manner similar to the profile.run() function. | |
1284 | Namespaces are internally managed to work correctly; profile.run |
|
1281 | Namespaces are internally managed to work correctly; profile.run | |
1285 | cannot be used in IPython because it makes certain assumptions about |
|
1282 | cannot be used in IPython because it makes certain assumptions about | |
1286 | namespaces which do not hold under IPython. |
|
1283 | namespaces which do not hold under IPython. | |
1287 |
|
1284 | |||
1288 | Options: |
|
1285 | Options: | |
1289 |
|
1286 | |||
1290 | -l <limit>: you can place restrictions on what or how much of the |
|
1287 | -l <limit>: you can place restrictions on what or how much of the | |
1291 | profile gets printed. The limit value can be: |
|
1288 | profile gets printed. The limit value can be: | |
1292 |
|
1289 | |||
1293 | * A string: only information for function names containing this string |
|
1290 | * A string: only information for function names containing this string | |
1294 | is printed. |
|
1291 | is printed. | |
1295 |
|
1292 | |||
1296 | * An integer: only these many lines are printed. |
|
1293 | * An integer: only these many lines are printed. | |
1297 |
|
1294 | |||
1298 | * A float (between 0 and 1): this fraction of the report is printed |
|
1295 | * A float (between 0 and 1): this fraction of the report is printed | |
1299 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1296 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1300 |
|
1297 | |||
1301 | You can combine several limits with repeated use of the option. For |
|
1298 | You can combine several limits with repeated use of the option. For | |
1302 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1299 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1303 | information about class constructors. |
|
1300 | information about class constructors. | |
1304 |
|
1301 | |||
1305 | -r: return the pstats.Stats object generated by the profiling. This |
|
1302 | -r: return the pstats.Stats object generated by the profiling. This | |
1306 | object has all the information about the profile in it, and you can |
|
1303 | object has all the information about the profile in it, and you can | |
1307 | later use it for further analysis or in other functions. |
|
1304 | later use it for further analysis or in other functions. | |
1308 |
|
1305 | |||
1309 | -s <key>: sort profile by given key. You can provide more than one key |
|
1306 | -s <key>: sort profile by given key. You can provide more than one key | |
1310 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1307 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1311 | default sorting key is 'time'. |
|
1308 | default sorting key is 'time'. | |
1312 |
|
1309 | |||
1313 | The following is copied verbatim from the profile documentation |
|
1310 | The following is copied verbatim from the profile documentation | |
1314 | referenced below: |
|
1311 | referenced below: | |
1315 |
|
1312 | |||
1316 | When more than one key is provided, additional keys are used as |
|
1313 | When more than one key is provided, additional keys are used as | |
1317 | secondary criteria when the there is equality in all keys selected |
|
1314 | secondary criteria when the there is equality in all keys selected | |
1318 | before them. |
|
1315 | before them. | |
1319 |
|
1316 | |||
1320 | Abbreviations can be used for any key names, as long as the |
|
1317 | Abbreviations can be used for any key names, as long as the | |
1321 | abbreviation is unambiguous. The following are the keys currently |
|
1318 | abbreviation is unambiguous. The following are the keys currently | |
1322 | defined: |
|
1319 | defined: | |
1323 |
|
1320 | |||
1324 | Valid Arg Meaning |
|
1321 | Valid Arg Meaning | |
1325 | "calls" call count |
|
1322 | "calls" call count | |
1326 | "cumulative" cumulative time |
|
1323 | "cumulative" cumulative time | |
1327 | "file" file name |
|
1324 | "file" file name | |
1328 | "module" file name |
|
1325 | "module" file name | |
1329 | "pcalls" primitive call count |
|
1326 | "pcalls" primitive call count | |
1330 | "line" line number |
|
1327 | "line" line number | |
1331 | "name" function name |
|
1328 | "name" function name | |
1332 | "nfl" name/file/line |
|
1329 | "nfl" name/file/line | |
1333 | "stdname" standard name |
|
1330 | "stdname" standard name | |
1334 | "time" internal time |
|
1331 | "time" internal time | |
1335 |
|
1332 | |||
1336 | Note that all sorts on statistics are in descending order (placing |
|
1333 | Note that all sorts on statistics are in descending order (placing | |
1337 | most time consuming items first), where as name, file, and line number |
|
1334 | most time consuming items first), where as name, file, and line number | |
1338 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1335 | searches are in ascending order (i.e., alphabetical). The subtle | |
1339 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1336 | distinction between "nfl" and "stdname" is that the standard name is a | |
1340 | sort of the name as printed, which means that the embedded line |
|
1337 | sort of the name as printed, which means that the embedded line | |
1341 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1338 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1342 | would (if the file names were the same) appear in the string order |
|
1339 | would (if the file names were the same) appear in the string order | |
1343 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1340 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1344 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1341 | line numbers. In fact, sort_stats("nfl") is the same as | |
1345 | sort_stats("name", "file", "line"). |
|
1342 | sort_stats("name", "file", "line"). | |
1346 |
|
1343 | |||
1347 | -T <filename>: save profile results as shown on screen to a text |
|
1344 | -T <filename>: save profile results as shown on screen to a text | |
1348 | file. The profile is still shown on screen. |
|
1345 | file. The profile is still shown on screen. | |
1349 |
|
1346 | |||
1350 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1347 | -D <filename>: save (via dump_stats) profile statistics to given | |
1351 | filename. This data is in a format understod by the pstats module, and |
|
1348 | filename. This data is in a format understod by the pstats module, and | |
1352 | is generated by a call to the dump_stats() method of profile |
|
1349 | is generated by a call to the dump_stats() method of profile | |
1353 | objects. The profile is still shown on screen. |
|
1350 | objects. The profile is still shown on screen. | |
1354 |
|
1351 | |||
1355 | If you want to run complete programs under the profiler's control, use |
|
1352 | If you want to run complete programs under the profiler's control, use | |
1356 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1353 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1357 | contains profiler specific options as described here. |
|
1354 | contains profiler specific options as described here. | |
1358 |
|
1355 | |||
1359 | You can read the complete documentation for the profile module with:: |
|
1356 | You can read the complete documentation for the profile module with:: | |
1360 |
|
1357 | |||
1361 | In [1]: import profile; profile.help() |
|
1358 | In [1]: import profile; profile.help() | |
1362 | """ |
|
1359 | """ | |
1363 |
|
1360 | |||
1364 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1361 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1365 | # protect user quote marks |
|
1362 | # protect user quote marks | |
1366 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1363 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1367 |
|
1364 | |||
1368 | if user_mode: # regular user call |
|
1365 | if user_mode: # regular user call | |
1369 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1366 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1370 | list_all=1) |
|
1367 | list_all=1) | |
1371 | namespace = self.shell.user_ns |
|
1368 | namespace = self.shell.user_ns | |
1372 | else: # called to run a program by %run -p |
|
1369 | else: # called to run a program by %run -p | |
1373 | try: |
|
1370 | try: | |
1374 | filename = get_py_filename(arg_lst[0]) |
|
1371 | filename = get_py_filename(arg_lst[0]) | |
1375 | except IOError,msg: |
|
1372 | except IOError,msg: | |
1376 | error(msg) |
|
1373 | error(msg) | |
1377 | return |
|
1374 | return | |
1378 |
|
1375 | |||
1379 | arg_str = 'execfile(filename,prog_ns)' |
|
1376 | arg_str = 'execfile(filename,prog_ns)' | |
1380 | namespace = locals() |
|
1377 | namespace = locals() | |
1381 |
|
1378 | |||
1382 | opts.merge(opts_def) |
|
1379 | opts.merge(opts_def) | |
1383 |
|
1380 | |||
1384 | prof = profile.Profile() |
|
1381 | prof = profile.Profile() | |
1385 | try: |
|
1382 | try: | |
1386 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1383 | prof = prof.runctx(arg_str,namespace,namespace) | |
1387 | sys_exit = '' |
|
1384 | sys_exit = '' | |
1388 | except SystemExit: |
|
1385 | except SystemExit: | |
1389 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1386 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1390 |
|
1387 | |||
1391 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1388 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1392 |
|
1389 | |||
1393 | lims = opts.l |
|
1390 | lims = opts.l | |
1394 | if lims: |
|
1391 | if lims: | |
1395 | lims = [] # rebuild lims with ints/floats/strings |
|
1392 | lims = [] # rebuild lims with ints/floats/strings | |
1396 | for lim in opts.l: |
|
1393 | for lim in opts.l: | |
1397 | try: |
|
1394 | try: | |
1398 | lims.append(int(lim)) |
|
1395 | lims.append(int(lim)) | |
1399 | except ValueError: |
|
1396 | except ValueError: | |
1400 | try: |
|
1397 | try: | |
1401 | lims.append(float(lim)) |
|
1398 | lims.append(float(lim)) | |
1402 | except ValueError: |
|
1399 | except ValueError: | |
1403 | lims.append(lim) |
|
1400 | lims.append(lim) | |
1404 |
|
1401 | |||
1405 | # Trap output. |
|
1402 | # Trap output. | |
1406 | stdout_trap = StringIO() |
|
1403 | stdout_trap = StringIO() | |
1407 |
|
1404 | |||
1408 | if hasattr(stats,'stream'): |
|
1405 | if hasattr(stats,'stream'): | |
1409 | # In newer versions of python, the stats object has a 'stream' |
|
1406 | # In newer versions of python, the stats object has a 'stream' | |
1410 | # attribute to write into. |
|
1407 | # attribute to write into. | |
1411 | stats.stream = stdout_trap |
|
1408 | stats.stream = stdout_trap | |
1412 | stats.print_stats(*lims) |
|
1409 | stats.print_stats(*lims) | |
1413 | else: |
|
1410 | else: | |
1414 | # For older versions, we manually redirect stdout during printing |
|
1411 | # For older versions, we manually redirect stdout during printing | |
1415 | sys_stdout = sys.stdout |
|
1412 | sys_stdout = sys.stdout | |
1416 | try: |
|
1413 | try: | |
1417 | sys.stdout = stdout_trap |
|
1414 | sys.stdout = stdout_trap | |
1418 | stats.print_stats(*lims) |
|
1415 | stats.print_stats(*lims) | |
1419 | finally: |
|
1416 | finally: | |
1420 | sys.stdout = sys_stdout |
|
1417 | sys.stdout = sys_stdout | |
1421 |
|
1418 | |||
1422 | output = stdout_trap.getvalue() |
|
1419 | output = stdout_trap.getvalue() | |
1423 | output = output.rstrip() |
|
1420 | output = output.rstrip() | |
1424 |
|
1421 | |||
1425 | page.page(output) |
|
1422 | page.page(output) | |
1426 | print sys_exit, |
|
1423 | print sys_exit, | |
1427 |
|
1424 | |||
1428 | dump_file = opts.D[0] |
|
1425 | dump_file = opts.D[0] | |
1429 | text_file = opts.T[0] |
|
1426 | text_file = opts.T[0] | |
1430 | if dump_file: |
|
1427 | if dump_file: | |
1431 | prof.dump_stats(dump_file) |
|
1428 | prof.dump_stats(dump_file) | |
1432 | print '\n*** Profile stats marshalled to file',\ |
|
1429 | print '\n*** Profile stats marshalled to file',\ | |
1433 | `dump_file`+'.',sys_exit |
|
1430 | `dump_file`+'.',sys_exit | |
1434 | if text_file: |
|
1431 | if text_file: | |
1435 | pfile = file(text_file,'w') |
|
1432 | pfile = file(text_file,'w') | |
1436 | pfile.write(output) |
|
1433 | pfile.write(output) | |
1437 | pfile.close() |
|
1434 | pfile.close() | |
1438 | print '\n*** Profile printout saved to text file',\ |
|
1435 | print '\n*** Profile printout saved to text file',\ | |
1439 | `text_file`+'.',sys_exit |
|
1436 | `text_file`+'.',sys_exit | |
1440 |
|
1437 | |||
1441 | if opts.has_key('r'): |
|
1438 | if opts.has_key('r'): | |
1442 | return stats |
|
1439 | return stats | |
1443 | else: |
|
1440 | else: | |
1444 | return None |
|
1441 | return None | |
1445 |
|
1442 | |||
1446 | @testdec.skip_doctest |
|
1443 | @testdec.skip_doctest | |
1447 | def magic_run(self, parameter_s ='',runner=None, |
|
1444 | def magic_run(self, parameter_s ='',runner=None, | |
1448 | file_finder=get_py_filename): |
|
1445 | file_finder=get_py_filename): | |
1449 | """Run the named file inside IPython as a program. |
|
1446 | """Run the named file inside IPython as a program. | |
1450 |
|
1447 | |||
1451 | Usage:\\ |
|
1448 | Usage:\\ | |
1452 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1449 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1453 |
|
1450 | |||
1454 | Parameters after the filename are passed as command-line arguments to |
|
1451 | Parameters after the filename are passed as command-line arguments to | |
1455 | the program (put in sys.argv). Then, control returns to IPython's |
|
1452 | the program (put in sys.argv). Then, control returns to IPython's | |
1456 | prompt. |
|
1453 | prompt. | |
1457 |
|
1454 | |||
1458 | This is similar to running at a system prompt:\\ |
|
1455 | This is similar to running at a system prompt:\\ | |
1459 | $ python file args\\ |
|
1456 | $ python file args\\ | |
1460 | but with the advantage of giving you IPython's tracebacks, and of |
|
1457 | but with the advantage of giving you IPython's tracebacks, and of | |
1461 | loading all variables into your interactive namespace for further use |
|
1458 | loading all variables into your interactive namespace for further use | |
1462 | (unless -p is used, see below). |
|
1459 | (unless -p is used, see below). | |
1463 |
|
1460 | |||
1464 | The file is executed in a namespace initially consisting only of |
|
1461 | The file is executed in a namespace initially consisting only of | |
1465 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1462 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1466 | sees its environment as if it were being run as a stand-alone program |
|
1463 | sees its environment as if it were being run as a stand-alone program | |
1467 | (except for sharing global objects such as previously imported |
|
1464 | (except for sharing global objects such as previously imported | |
1468 | modules). But after execution, the IPython interactive namespace gets |
|
1465 | modules). But after execution, the IPython interactive namespace gets | |
1469 | updated with all variables defined in the program (except for __name__ |
|
1466 | updated with all variables defined in the program (except for __name__ | |
1470 | and sys.argv). This allows for very convenient loading of code for |
|
1467 | and sys.argv). This allows for very convenient loading of code for | |
1471 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1468 | interactive work, while giving each program a 'clean sheet' to run in. | |
1472 |
|
1469 | |||
1473 | Options: |
|
1470 | Options: | |
1474 |
|
1471 | |||
1475 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1472 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1476 | without extension (as python does under import). This allows running |
|
1473 | without extension (as python does under import). This allows running | |
1477 | scripts and reloading the definitions in them without calling code |
|
1474 | scripts and reloading the definitions in them without calling code | |
1478 | protected by an ' if __name__ == "__main__" ' clause. |
|
1475 | protected by an ' if __name__ == "__main__" ' clause. | |
1479 |
|
1476 | |||
1480 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1477 | -i: run the file in IPython's namespace instead of an empty one. This | |
1481 | is useful if you are experimenting with code written in a text editor |
|
1478 | is useful if you are experimenting with code written in a text editor | |
1482 | which depends on variables defined interactively. |
|
1479 | which depends on variables defined interactively. | |
1483 |
|
1480 | |||
1484 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1481 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1485 | being run. This is particularly useful if IPython is being used to |
|
1482 | being run. This is particularly useful if IPython is being used to | |
1486 | run unittests, which always exit with a sys.exit() call. In such |
|
1483 | run unittests, which always exit with a sys.exit() call. In such | |
1487 | cases you are interested in the output of the test results, not in |
|
1484 | cases you are interested in the output of the test results, not in | |
1488 | seeing a traceback of the unittest module. |
|
1485 | seeing a traceback of the unittest module. | |
1489 |
|
1486 | |||
1490 | -t: print timing information at the end of the run. IPython will give |
|
1487 | -t: print timing information at the end of the run. IPython will give | |
1491 | you an estimated CPU time consumption for your script, which under |
|
1488 | you an estimated CPU time consumption for your script, which under | |
1492 | Unix uses the resource module to avoid the wraparound problems of |
|
1489 | Unix uses the resource module to avoid the wraparound problems of | |
1493 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1490 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1494 | is also given (for Windows platforms this is reported as 0.0). |
|
1491 | is also given (for Windows platforms this is reported as 0.0). | |
1495 |
|
1492 | |||
1496 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1493 | If -t is given, an additional -N<N> option can be given, where <N> | |
1497 | must be an integer indicating how many times you want the script to |
|
1494 | must be an integer indicating how many times you want the script to | |
1498 | run. The final timing report will include total and per run results. |
|
1495 | run. The final timing report will include total and per run results. | |
1499 |
|
1496 | |||
1500 | For example (testing the script uniq_stable.py): |
|
1497 | For example (testing the script uniq_stable.py): | |
1501 |
|
1498 | |||
1502 | In [1]: run -t uniq_stable |
|
1499 | In [1]: run -t uniq_stable | |
1503 |
|
1500 | |||
1504 | IPython CPU timings (estimated):\\ |
|
1501 | IPython CPU timings (estimated):\\ | |
1505 | User : 0.19597 s.\\ |
|
1502 | User : 0.19597 s.\\ | |
1506 | System: 0.0 s.\\ |
|
1503 | System: 0.0 s.\\ | |
1507 |
|
1504 | |||
1508 | In [2]: run -t -N5 uniq_stable |
|
1505 | In [2]: run -t -N5 uniq_stable | |
1509 |
|
1506 | |||
1510 | IPython CPU timings (estimated):\\ |
|
1507 | IPython CPU timings (estimated):\\ | |
1511 | Total runs performed: 5\\ |
|
1508 | Total runs performed: 5\\ | |
1512 | Times : Total Per run\\ |
|
1509 | Times : Total Per run\\ | |
1513 | User : 0.910862 s, 0.1821724 s.\\ |
|
1510 | User : 0.910862 s, 0.1821724 s.\\ | |
1514 | System: 0.0 s, 0.0 s. |
|
1511 | System: 0.0 s, 0.0 s. | |
1515 |
|
1512 | |||
1516 | -d: run your program under the control of pdb, the Python debugger. |
|
1513 | -d: run your program under the control of pdb, the Python debugger. | |
1517 | This allows you to execute your program step by step, watch variables, |
|
1514 | This allows you to execute your program step by step, watch variables, | |
1518 | etc. Internally, what IPython does is similar to calling: |
|
1515 | etc. Internally, what IPython does is similar to calling: | |
1519 |
|
1516 | |||
1520 | pdb.run('execfile("YOURFILENAME")') |
|
1517 | pdb.run('execfile("YOURFILENAME")') | |
1521 |
|
1518 | |||
1522 | with a breakpoint set on line 1 of your file. You can change the line |
|
1519 | with a breakpoint set on line 1 of your file. You can change the line | |
1523 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1520 | number for this automatic breakpoint to be <N> by using the -bN option | |
1524 | (where N must be an integer). For example: |
|
1521 | (where N must be an integer). For example: | |
1525 |
|
1522 | |||
1526 | %run -d -b40 myscript |
|
1523 | %run -d -b40 myscript | |
1527 |
|
1524 | |||
1528 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1525 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1529 | the first breakpoint must be set on a line which actually does |
|
1526 | the first breakpoint must be set on a line which actually does | |
1530 | something (not a comment or docstring) for it to stop execution. |
|
1527 | something (not a comment or docstring) for it to stop execution. | |
1531 |
|
1528 | |||
1532 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1529 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1533 | first enter 'c' (without qoutes) to start execution up to the first |
|
1530 | first enter 'c' (without qoutes) to start execution up to the first | |
1534 | breakpoint. |
|
1531 | breakpoint. | |
1535 |
|
1532 | |||
1536 | Entering 'help' gives information about the use of the debugger. You |
|
1533 | Entering 'help' gives information about the use of the debugger. You | |
1537 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1534 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1538 | at a prompt. |
|
1535 | at a prompt. | |
1539 |
|
1536 | |||
1540 | -p: run program under the control of the Python profiler module (which |
|
1537 | -p: run program under the control of the Python profiler module (which | |
1541 | prints a detailed report of execution times, function calls, etc). |
|
1538 | prints a detailed report of execution times, function calls, etc). | |
1542 |
|
1539 | |||
1543 | You can pass other options after -p which affect the behavior of the |
|
1540 | You can pass other options after -p which affect the behavior of the | |
1544 | profiler itself. See the docs for %prun for details. |
|
1541 | profiler itself. See the docs for %prun for details. | |
1545 |
|
1542 | |||
1546 | In this mode, the program's variables do NOT propagate back to the |
|
1543 | In this mode, the program's variables do NOT propagate back to the | |
1547 | IPython interactive namespace (because they remain in the namespace |
|
1544 | IPython interactive namespace (because they remain in the namespace | |
1548 | where the profiler executes them). |
|
1545 | where the profiler executes them). | |
1549 |
|
1546 | |||
1550 | Internally this triggers a call to %prun, see its documentation for |
|
1547 | Internally this triggers a call to %prun, see its documentation for | |
1551 | details on the options available specifically for profiling. |
|
1548 | details on the options available specifically for profiling. | |
1552 |
|
1549 | |||
1553 | There is one special usage for which the text above doesn't apply: |
|
1550 | There is one special usage for which the text above doesn't apply: | |
1554 | if the filename ends with .ipy, the file is run as ipython script, |
|
1551 | if the filename ends with .ipy, the file is run as ipython script, | |
1555 | just as if the commands were written on IPython prompt. |
|
1552 | just as if the commands were written on IPython prompt. | |
1556 | """ |
|
1553 | """ | |
1557 |
|
1554 | |||
1558 | # get arguments and set sys.argv for program to be run. |
|
1555 | # get arguments and set sys.argv for program to be run. | |
1559 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1556 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1560 | mode='list',list_all=1) |
|
1557 | mode='list',list_all=1) | |
1561 |
|
1558 | |||
1562 | try: |
|
1559 | try: | |
1563 | filename = file_finder(arg_lst[0]) |
|
1560 | filename = file_finder(arg_lst[0]) | |
1564 | except IndexError: |
|
1561 | except IndexError: | |
1565 | warn('you must provide at least a filename.') |
|
1562 | warn('you must provide at least a filename.') | |
1566 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1563 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1567 | return |
|
1564 | return | |
1568 | except IOError,msg: |
|
1565 | except IOError,msg: | |
1569 | error(msg) |
|
1566 | error(msg) | |
1570 | return |
|
1567 | return | |
1571 |
|
1568 | |||
1572 | if filename.lower().endswith('.ipy'): |
|
1569 | if filename.lower().endswith('.ipy'): | |
1573 | self.shell.safe_execfile_ipy(filename) |
|
1570 | self.shell.safe_execfile_ipy(filename) | |
1574 | return |
|
1571 | return | |
1575 |
|
1572 | |||
1576 | # Control the response to exit() calls made by the script being run |
|
1573 | # Control the response to exit() calls made by the script being run | |
1577 | exit_ignore = opts.has_key('e') |
|
1574 | exit_ignore = opts.has_key('e') | |
1578 |
|
1575 | |||
1579 | # Make sure that the running script gets a proper sys.argv as if it |
|
1576 | # Make sure that the running script gets a proper sys.argv as if it | |
1580 | # were run from a system shell. |
|
1577 | # were run from a system shell. | |
1581 | save_argv = sys.argv # save it for later restoring |
|
1578 | save_argv = sys.argv # save it for later restoring | |
1582 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1579 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1583 |
|
1580 | |||
1584 | if opts.has_key('i'): |
|
1581 | if opts.has_key('i'): | |
1585 | # Run in user's interactive namespace |
|
1582 | # Run in user's interactive namespace | |
1586 | prog_ns = self.shell.user_ns |
|
1583 | prog_ns = self.shell.user_ns | |
1587 | __name__save = self.shell.user_ns['__name__'] |
|
1584 | __name__save = self.shell.user_ns['__name__'] | |
1588 | prog_ns['__name__'] = '__main__' |
|
1585 | prog_ns['__name__'] = '__main__' | |
1589 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1586 | main_mod = self.shell.new_main_mod(prog_ns) | |
1590 | else: |
|
1587 | else: | |
1591 | # Run in a fresh, empty namespace |
|
1588 | # Run in a fresh, empty namespace | |
1592 | if opts.has_key('n'): |
|
1589 | if opts.has_key('n'): | |
1593 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1590 | name = os.path.splitext(os.path.basename(filename))[0] | |
1594 | else: |
|
1591 | else: | |
1595 | name = '__main__' |
|
1592 | name = '__main__' | |
1596 |
|
1593 | |||
1597 | main_mod = self.shell.new_main_mod() |
|
1594 | main_mod = self.shell.new_main_mod() | |
1598 | prog_ns = main_mod.__dict__ |
|
1595 | prog_ns = main_mod.__dict__ | |
1599 | prog_ns['__name__'] = name |
|
1596 | prog_ns['__name__'] = name | |
1600 |
|
1597 | |||
1601 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1598 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1602 | # set the __file__ global in the script's namespace |
|
1599 | # set the __file__ global in the script's namespace | |
1603 | prog_ns['__file__'] = filename |
|
1600 | prog_ns['__file__'] = filename | |
1604 |
|
1601 | |||
1605 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1602 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1606 | # that, if we overwrite __main__, we replace it at the end |
|
1603 | # that, if we overwrite __main__, we replace it at the end | |
1607 | main_mod_name = prog_ns['__name__'] |
|
1604 | main_mod_name = prog_ns['__name__'] | |
1608 |
|
1605 | |||
1609 | if main_mod_name == '__main__': |
|
1606 | if main_mod_name == '__main__': | |
1610 | restore_main = sys.modules['__main__'] |
|
1607 | restore_main = sys.modules['__main__'] | |
1611 | else: |
|
1608 | else: | |
1612 | restore_main = False |
|
1609 | restore_main = False | |
1613 |
|
1610 | |||
1614 | # This needs to be undone at the end to prevent holding references to |
|
1611 | # This needs to be undone at the end to prevent holding references to | |
1615 | # every single object ever created. |
|
1612 | # every single object ever created. | |
1616 | sys.modules[main_mod_name] = main_mod |
|
1613 | sys.modules[main_mod_name] = main_mod | |
1617 |
|
1614 | |||
1618 | stats = None |
|
1615 | stats = None | |
1619 | try: |
|
1616 | try: | |
1620 | self.shell.save_history() |
|
1617 | self.shell.save_history() | |
1621 |
|
1618 | |||
1622 | if opts.has_key('p'): |
|
1619 | if opts.has_key('p'): | |
1623 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1620 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1624 | else: |
|
1621 | else: | |
1625 | if opts.has_key('d'): |
|
1622 | if opts.has_key('d'): | |
1626 | deb = debugger.Pdb(self.shell.colors) |
|
1623 | deb = debugger.Pdb(self.shell.colors) | |
1627 | # reset Breakpoint state, which is moronically kept |
|
1624 | # reset Breakpoint state, which is moronically kept | |
1628 | # in a class |
|
1625 | # in a class | |
1629 | bdb.Breakpoint.next = 1 |
|
1626 | bdb.Breakpoint.next = 1 | |
1630 | bdb.Breakpoint.bplist = {} |
|
1627 | bdb.Breakpoint.bplist = {} | |
1631 | bdb.Breakpoint.bpbynumber = [None] |
|
1628 | bdb.Breakpoint.bpbynumber = [None] | |
1632 | # Set an initial breakpoint to stop execution |
|
1629 | # Set an initial breakpoint to stop execution | |
1633 | maxtries = 10 |
|
1630 | maxtries = 10 | |
1634 | bp = int(opts.get('b',[1])[0]) |
|
1631 | bp = int(opts.get('b',[1])[0]) | |
1635 | checkline = deb.checkline(filename,bp) |
|
1632 | checkline = deb.checkline(filename,bp) | |
1636 | if not checkline: |
|
1633 | if not checkline: | |
1637 | for bp in range(bp+1,bp+maxtries+1): |
|
1634 | for bp in range(bp+1,bp+maxtries+1): | |
1638 | if deb.checkline(filename,bp): |
|
1635 | if deb.checkline(filename,bp): | |
1639 | break |
|
1636 | break | |
1640 | else: |
|
1637 | else: | |
1641 | msg = ("\nI failed to find a valid line to set " |
|
1638 | msg = ("\nI failed to find a valid line to set " | |
1642 | "a breakpoint\n" |
|
1639 | "a breakpoint\n" | |
1643 | "after trying up to line: %s.\n" |
|
1640 | "after trying up to line: %s.\n" | |
1644 | "Please set a valid breakpoint manually " |
|
1641 | "Please set a valid breakpoint manually " | |
1645 | "with the -b option." % bp) |
|
1642 | "with the -b option." % bp) | |
1646 | error(msg) |
|
1643 | error(msg) | |
1647 | return |
|
1644 | return | |
1648 | # if we find a good linenumber, set the breakpoint |
|
1645 | # if we find a good linenumber, set the breakpoint | |
1649 | deb.do_break('%s:%s' % (filename,bp)) |
|
1646 | deb.do_break('%s:%s' % (filename,bp)) | |
1650 | # Start file run |
|
1647 | # Start file run | |
1651 | print "NOTE: Enter 'c' at the", |
|
1648 | print "NOTE: Enter 'c' at the", | |
1652 | print "%s prompt to start your script." % deb.prompt |
|
1649 | print "%s prompt to start your script." % deb.prompt | |
1653 | try: |
|
1650 | try: | |
1654 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1651 | deb.run('execfile("%s")' % filename,prog_ns) | |
1655 |
|
1652 | |||
1656 | except: |
|
1653 | except: | |
1657 | etype, value, tb = sys.exc_info() |
|
1654 | etype, value, tb = sys.exc_info() | |
1658 | # Skip three frames in the traceback: the %run one, |
|
1655 | # Skip three frames in the traceback: the %run one, | |
1659 | # one inside bdb.py, and the command-line typed by the |
|
1656 | # one inside bdb.py, and the command-line typed by the | |
1660 | # user (run by exec in pdb itself). |
|
1657 | # user (run by exec in pdb itself). | |
1661 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1658 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1662 | else: |
|
1659 | else: | |
1663 | if runner is None: |
|
1660 | if runner is None: | |
1664 | runner = self.shell.safe_execfile |
|
1661 | runner = self.shell.safe_execfile | |
1665 | if opts.has_key('t'): |
|
1662 | if opts.has_key('t'): | |
1666 | # timed execution |
|
1663 | # timed execution | |
1667 | try: |
|
1664 | try: | |
1668 | nruns = int(opts['N'][0]) |
|
1665 | nruns = int(opts['N'][0]) | |
1669 | if nruns < 1: |
|
1666 | if nruns < 1: | |
1670 | error('Number of runs must be >=1') |
|
1667 | error('Number of runs must be >=1') | |
1671 | return |
|
1668 | return | |
1672 | except (KeyError): |
|
1669 | except (KeyError): | |
1673 | nruns = 1 |
|
1670 | nruns = 1 | |
1674 | if nruns == 1: |
|
1671 | if nruns == 1: | |
1675 | t0 = clock2() |
|
1672 | t0 = clock2() | |
1676 | runner(filename,prog_ns,prog_ns, |
|
1673 | runner(filename,prog_ns,prog_ns, | |
1677 | exit_ignore=exit_ignore) |
|
1674 | exit_ignore=exit_ignore) | |
1678 | t1 = clock2() |
|
1675 | t1 = clock2() | |
1679 | t_usr = t1[0]-t0[0] |
|
1676 | t_usr = t1[0]-t0[0] | |
1680 | t_sys = t1[1]-t0[1] |
|
1677 | t_sys = t1[1]-t0[1] | |
1681 | print "\nIPython CPU timings (estimated):" |
|
1678 | print "\nIPython CPU timings (estimated):" | |
1682 | print " User : %10s s." % t_usr |
|
1679 | print " User : %10s s." % t_usr | |
1683 | print " System: %10s s." % t_sys |
|
1680 | print " System: %10s s." % t_sys | |
1684 | else: |
|
1681 | else: | |
1685 | runs = range(nruns) |
|
1682 | runs = range(nruns) | |
1686 | t0 = clock2() |
|
1683 | t0 = clock2() | |
1687 | for nr in runs: |
|
1684 | for nr in runs: | |
1688 | runner(filename,prog_ns,prog_ns, |
|
1685 | runner(filename,prog_ns,prog_ns, | |
1689 | exit_ignore=exit_ignore) |
|
1686 | exit_ignore=exit_ignore) | |
1690 | t1 = clock2() |
|
1687 | t1 = clock2() | |
1691 | t_usr = t1[0]-t0[0] |
|
1688 | t_usr = t1[0]-t0[0] | |
1692 | t_sys = t1[1]-t0[1] |
|
1689 | t_sys = t1[1]-t0[1] | |
1693 | print "\nIPython CPU timings (estimated):" |
|
1690 | print "\nIPython CPU timings (estimated):" | |
1694 | print "Total runs performed:",nruns |
|
1691 | print "Total runs performed:",nruns | |
1695 | print " Times : %10s %10s" % ('Total','Per run') |
|
1692 | print " Times : %10s %10s" % ('Total','Per run') | |
1696 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1693 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1697 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1694 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1698 |
|
1695 | |||
1699 | else: |
|
1696 | else: | |
1700 | # regular execution |
|
1697 | # regular execution | |
1701 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1698 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1702 |
|
1699 | |||
1703 | if opts.has_key('i'): |
|
1700 | if opts.has_key('i'): | |
1704 | self.shell.user_ns['__name__'] = __name__save |
|
1701 | self.shell.user_ns['__name__'] = __name__save | |
1705 | else: |
|
1702 | else: | |
1706 | # The shell MUST hold a reference to prog_ns so after %run |
|
1703 | # The shell MUST hold a reference to prog_ns so after %run | |
1707 | # exits, the python deletion mechanism doesn't zero it out |
|
1704 | # exits, the python deletion mechanism doesn't zero it out | |
1708 | # (leaving dangling references). |
|
1705 | # (leaving dangling references). | |
1709 | self.shell.cache_main_mod(prog_ns,filename) |
|
1706 | self.shell.cache_main_mod(prog_ns,filename) | |
1710 | # update IPython interactive namespace |
|
1707 | # update IPython interactive namespace | |
1711 |
|
1708 | |||
1712 | # Some forms of read errors on the file may mean the |
|
1709 | # Some forms of read errors on the file may mean the | |
1713 | # __name__ key was never set; using pop we don't have to |
|
1710 | # __name__ key was never set; using pop we don't have to | |
1714 | # worry about a possible KeyError. |
|
1711 | # worry about a possible KeyError. | |
1715 | prog_ns.pop('__name__', None) |
|
1712 | prog_ns.pop('__name__', None) | |
1716 |
|
1713 | |||
1717 | self.shell.user_ns.update(prog_ns) |
|
1714 | self.shell.user_ns.update(prog_ns) | |
1718 | finally: |
|
1715 | finally: | |
1719 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1716 | # It's a bit of a mystery why, but __builtins__ can change from | |
1720 | # being a module to becoming a dict missing some key data after |
|
1717 | # being a module to becoming a dict missing some key data after | |
1721 | # %run. As best I can see, this is NOT something IPython is doing |
|
1718 | # %run. As best I can see, this is NOT something IPython is doing | |
1722 | # at all, and similar problems have been reported before: |
|
1719 | # at all, and similar problems have been reported before: | |
1723 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1720 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1724 | # Since this seems to be done by the interpreter itself, the best |
|
1721 | # Since this seems to be done by the interpreter itself, the best | |
1725 | # we can do is to at least restore __builtins__ for the user on |
|
1722 | # we can do is to at least restore __builtins__ for the user on | |
1726 | # exit. |
|
1723 | # exit. | |
1727 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1724 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1728 |
|
1725 | |||
1729 | # Ensure key global structures are restored |
|
1726 | # Ensure key global structures are restored | |
1730 | sys.argv = save_argv |
|
1727 | sys.argv = save_argv | |
1731 | if restore_main: |
|
1728 | if restore_main: | |
1732 | sys.modules['__main__'] = restore_main |
|
1729 | sys.modules['__main__'] = restore_main | |
1733 | else: |
|
1730 | else: | |
1734 | # Remove from sys.modules the reference to main_mod we'd |
|
1731 | # Remove from sys.modules the reference to main_mod we'd | |
1735 | # added. Otherwise it will trap references to objects |
|
1732 | # added. Otherwise it will trap references to objects | |
1736 | # contained therein. |
|
1733 | # contained therein. | |
1737 | del sys.modules[main_mod_name] |
|
1734 | del sys.modules[main_mod_name] | |
1738 |
|
1735 | |||
1739 | self.shell.reload_history() |
|
1736 | self.shell.reload_history() | |
1740 |
|
1737 | |||
1741 | return stats |
|
1738 | return stats | |
1742 |
|
1739 | |||
1743 | @testdec.skip_doctest |
|
1740 | @testdec.skip_doctest | |
1744 | def magic_timeit(self, parameter_s =''): |
|
1741 | def magic_timeit(self, parameter_s =''): | |
1745 | """Time execution of a Python statement or expression |
|
1742 | """Time execution of a Python statement or expression | |
1746 |
|
1743 | |||
1747 | Usage:\\ |
|
1744 | Usage:\\ | |
1748 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1745 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1749 |
|
1746 | |||
1750 | Time execution of a Python statement or expression using the timeit |
|
1747 | Time execution of a Python statement or expression using the timeit | |
1751 | module. |
|
1748 | module. | |
1752 |
|
1749 | |||
1753 | Options: |
|
1750 | Options: | |
1754 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1751 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1755 | is not given, a fitting value is chosen. |
|
1752 | is not given, a fitting value is chosen. | |
1756 |
|
1753 | |||
1757 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1754 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1758 | Default: 3 |
|
1755 | Default: 3 | |
1759 |
|
1756 | |||
1760 | -t: use time.time to measure the time, which is the default on Unix. |
|
1757 | -t: use time.time to measure the time, which is the default on Unix. | |
1761 | This function measures wall time. |
|
1758 | This function measures wall time. | |
1762 |
|
1759 | |||
1763 | -c: use time.clock to measure the time, which is the default on |
|
1760 | -c: use time.clock to measure the time, which is the default on | |
1764 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1761 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1765 | instead and returns the CPU user time. |
|
1762 | instead and returns the CPU user time. | |
1766 |
|
1763 | |||
1767 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1764 | -p<P>: use a precision of <P> digits to display the timing result. | |
1768 | Default: 3 |
|
1765 | Default: 3 | |
1769 |
|
1766 | |||
1770 |
|
1767 | |||
1771 | Examples: |
|
1768 | Examples: | |
1772 |
|
1769 | |||
1773 | In [1]: %timeit pass |
|
1770 | In [1]: %timeit pass | |
1774 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1771 | 10000000 loops, best of 3: 53.3 ns per loop | |
1775 |
|
1772 | |||
1776 | In [2]: u = None |
|
1773 | In [2]: u = None | |
1777 |
|
1774 | |||
1778 | In [3]: %timeit u is None |
|
1775 | In [3]: %timeit u is None | |
1779 | 10000000 loops, best of 3: 184 ns per loop |
|
1776 | 10000000 loops, best of 3: 184 ns per loop | |
1780 |
|
1777 | |||
1781 | In [4]: %timeit -r 4 u == None |
|
1778 | In [4]: %timeit -r 4 u == None | |
1782 | 1000000 loops, best of 4: 242 ns per loop |
|
1779 | 1000000 loops, best of 4: 242 ns per loop | |
1783 |
|
1780 | |||
1784 | In [5]: import time |
|
1781 | In [5]: import time | |
1785 |
|
1782 | |||
1786 | In [6]: %timeit -n1 time.sleep(2) |
|
1783 | In [6]: %timeit -n1 time.sleep(2) | |
1787 | 1 loops, best of 3: 2 s per loop |
|
1784 | 1 loops, best of 3: 2 s per loop | |
1788 |
|
1785 | |||
1789 |
|
1786 | |||
1790 | The times reported by %timeit will be slightly higher than those |
|
1787 | The times reported by %timeit will be slightly higher than those | |
1791 | reported by the timeit.py script when variables are accessed. This is |
|
1788 | reported by the timeit.py script when variables are accessed. This is | |
1792 | due to the fact that %timeit executes the statement in the namespace |
|
1789 | due to the fact that %timeit executes the statement in the namespace | |
1793 | of the shell, compared with timeit.py, which uses a single setup |
|
1790 | of the shell, compared with timeit.py, which uses a single setup | |
1794 | statement to import function or create variables. Generally, the bias |
|
1791 | statement to import function or create variables. Generally, the bias | |
1795 | does not matter as long as results from timeit.py are not mixed with |
|
1792 | does not matter as long as results from timeit.py are not mixed with | |
1796 | those from %timeit.""" |
|
1793 | those from %timeit.""" | |
1797 |
|
1794 | |||
1798 | import timeit |
|
1795 | import timeit | |
1799 | import math |
|
1796 | import math | |
1800 |
|
1797 | |||
1801 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1798 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1802 | # certain terminals. Until we figure out a robust way of |
|
1799 | # certain terminals. Until we figure out a robust way of | |
1803 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1800 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1804 | # microseconds. I am really NOT happy about disabling the proper |
|
1801 | # microseconds. I am really NOT happy about disabling the proper | |
1805 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1802 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1806 | # right solution for this is, I'm all ears... |
|
1803 | # right solution for this is, I'm all ears... | |
1807 | # |
|
1804 | # | |
1808 | # Note: using |
|
1805 | # Note: using | |
1809 | # |
|
1806 | # | |
1810 | # s = u'\xb5' |
|
1807 | # s = u'\xb5' | |
1811 | # s.encode(sys.getdefaultencoding()) |
|
1808 | # s.encode(sys.getdefaultencoding()) | |
1812 | # |
|
1809 | # | |
1813 | # is not sufficient, as I've seen terminals where that fails but |
|
1810 | # is not sufficient, as I've seen terminals where that fails but | |
1814 | # print s |
|
1811 | # print s | |
1815 | # |
|
1812 | # | |
1816 | # succeeds |
|
1813 | # succeeds | |
1817 | # |
|
1814 | # | |
1818 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1815 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1819 |
|
1816 | |||
1820 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1817 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1821 | units = [u"s", u"ms",u'us',"ns"] |
|
1818 | units = [u"s", u"ms",u'us',"ns"] | |
1822 |
|
1819 | |||
1823 | scaling = [1, 1e3, 1e6, 1e9] |
|
1820 | scaling = [1, 1e3, 1e6, 1e9] | |
1824 |
|
1821 | |||
1825 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1822 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1826 | posix=False) |
|
1823 | posix=False) | |
1827 | if stmt == "": |
|
1824 | if stmt == "": | |
1828 | return |
|
1825 | return | |
1829 | timefunc = timeit.default_timer |
|
1826 | timefunc = timeit.default_timer | |
1830 | number = int(getattr(opts, "n", 0)) |
|
1827 | number = int(getattr(opts, "n", 0)) | |
1831 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1828 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1832 | precision = int(getattr(opts, "p", 3)) |
|
1829 | precision = int(getattr(opts, "p", 3)) | |
1833 | if hasattr(opts, "t"): |
|
1830 | if hasattr(opts, "t"): | |
1834 | timefunc = time.time |
|
1831 | timefunc = time.time | |
1835 | if hasattr(opts, "c"): |
|
1832 | if hasattr(opts, "c"): | |
1836 | timefunc = clock |
|
1833 | timefunc = clock | |
1837 |
|
1834 | |||
1838 | timer = timeit.Timer(timer=timefunc) |
|
1835 | timer = timeit.Timer(timer=timefunc) | |
1839 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1836 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1840 | # but is there a better way to achieve that the code stmt has access |
|
1837 | # but is there a better way to achieve that the code stmt has access | |
1841 | # to the shell namespace? |
|
1838 | # to the shell namespace? | |
1842 |
|
1839 | |||
1843 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1840 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1844 | 'setup': "pass"} |
|
1841 | 'setup': "pass"} | |
1845 | # Track compilation time so it can be reported if too long |
|
1842 | # Track compilation time so it can be reported if too long | |
1846 | # Minimum time above which compilation time will be reported |
|
1843 | # Minimum time above which compilation time will be reported | |
1847 | tc_min = 0.1 |
|
1844 | tc_min = 0.1 | |
1848 |
|
1845 | |||
1849 | t0 = clock() |
|
1846 | t0 = clock() | |
1850 | code = compile(src, "<magic-timeit>", "exec") |
|
1847 | code = compile(src, "<magic-timeit>", "exec") | |
1851 | tc = clock()-t0 |
|
1848 | tc = clock()-t0 | |
1852 |
|
1849 | |||
1853 | ns = {} |
|
1850 | ns = {} | |
1854 | exec code in self.shell.user_ns, ns |
|
1851 | exec code in self.shell.user_ns, ns | |
1855 | timer.inner = ns["inner"] |
|
1852 | timer.inner = ns["inner"] | |
1856 |
|
1853 | |||
1857 | if number == 0: |
|
1854 | if number == 0: | |
1858 | # determine number so that 0.2 <= total time < 2.0 |
|
1855 | # determine number so that 0.2 <= total time < 2.0 | |
1859 | number = 1 |
|
1856 | number = 1 | |
1860 | for i in range(1, 10): |
|
1857 | for i in range(1, 10): | |
1861 | if timer.timeit(number) >= 0.2: |
|
1858 | if timer.timeit(number) >= 0.2: | |
1862 | break |
|
1859 | break | |
1863 | number *= 10 |
|
1860 | number *= 10 | |
1864 |
|
1861 | |||
1865 | best = min(timer.repeat(repeat, number)) / number |
|
1862 | best = min(timer.repeat(repeat, number)) / number | |
1866 |
|
1863 | |||
1867 | if best > 0.0 and best < 1000.0: |
|
1864 | if best > 0.0 and best < 1000.0: | |
1868 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1865 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1869 | elif best >= 1000.0: |
|
1866 | elif best >= 1000.0: | |
1870 | order = 0 |
|
1867 | order = 0 | |
1871 | else: |
|
1868 | else: | |
1872 | order = 3 |
|
1869 | order = 3 | |
1873 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1870 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1874 | precision, |
|
1871 | precision, | |
1875 | best * scaling[order], |
|
1872 | best * scaling[order], | |
1876 | units[order]) |
|
1873 | units[order]) | |
1877 | if tc > tc_min: |
|
1874 | if tc > tc_min: | |
1878 | print "Compiler time: %.2f s" % tc |
|
1875 | print "Compiler time: %.2f s" % tc | |
1879 |
|
1876 | |||
1880 | @testdec.skip_doctest |
|
1877 | @testdec.skip_doctest | |
1881 | def magic_time(self,parameter_s = ''): |
|
1878 | def magic_time(self,parameter_s = ''): | |
1882 | """Time execution of a Python statement or expression. |
|
1879 | """Time execution of a Python statement or expression. | |
1883 |
|
1880 | |||
1884 | The CPU and wall clock times are printed, and the value of the |
|
1881 | The CPU and wall clock times are printed, and the value of the | |
1885 | expression (if any) is returned. Note that under Win32, system time |
|
1882 | expression (if any) is returned. Note that under Win32, system time | |
1886 | is always reported as 0, since it can not be measured. |
|
1883 | is always reported as 0, since it can not be measured. | |
1887 |
|
1884 | |||
1888 | This function provides very basic timing functionality. In Python |
|
1885 | This function provides very basic timing functionality. In Python | |
1889 | 2.3, the timeit module offers more control and sophistication, so this |
|
1886 | 2.3, the timeit module offers more control and sophistication, so this | |
1890 | could be rewritten to use it (patches welcome). |
|
1887 | could be rewritten to use it (patches welcome). | |
1891 |
|
1888 | |||
1892 | Some examples: |
|
1889 | Some examples: | |
1893 |
|
1890 | |||
1894 | In [1]: time 2**128 |
|
1891 | In [1]: time 2**128 | |
1895 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1892 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1896 | Wall time: 0.00 |
|
1893 | Wall time: 0.00 | |
1897 | Out[1]: 340282366920938463463374607431768211456L |
|
1894 | Out[1]: 340282366920938463463374607431768211456L | |
1898 |
|
1895 | |||
1899 | In [2]: n = 1000000 |
|
1896 | In [2]: n = 1000000 | |
1900 |
|
1897 | |||
1901 | In [3]: time sum(range(n)) |
|
1898 | In [3]: time sum(range(n)) | |
1902 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1899 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1903 | Wall time: 1.37 |
|
1900 | Wall time: 1.37 | |
1904 | Out[3]: 499999500000L |
|
1901 | Out[3]: 499999500000L | |
1905 |
|
1902 | |||
1906 | In [4]: time print 'hello world' |
|
1903 | In [4]: time print 'hello world' | |
1907 | hello world |
|
1904 | hello world | |
1908 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1905 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1909 | Wall time: 0.00 |
|
1906 | Wall time: 0.00 | |
1910 |
|
1907 | |||
1911 | Note that the time needed by Python to compile the given expression |
|
1908 | Note that the time needed by Python to compile the given expression | |
1912 | will be reported if it is more than 0.1s. In this example, the |
|
1909 | will be reported if it is more than 0.1s. In this example, the | |
1913 | actual exponentiation is done by Python at compilation time, so while |
|
1910 | actual exponentiation is done by Python at compilation time, so while | |
1914 | the expression can take a noticeable amount of time to compute, that |
|
1911 | the expression can take a noticeable amount of time to compute, that | |
1915 | time is purely due to the compilation: |
|
1912 | time is purely due to the compilation: | |
1916 |
|
1913 | |||
1917 | In [5]: time 3**9999; |
|
1914 | In [5]: time 3**9999; | |
1918 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1915 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1919 | Wall time: 0.00 s |
|
1916 | Wall time: 0.00 s | |
1920 |
|
1917 | |||
1921 | In [6]: time 3**999999; |
|
1918 | In [6]: time 3**999999; | |
1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1919 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1923 | Wall time: 0.00 s |
|
1920 | Wall time: 0.00 s | |
1924 | Compiler : 0.78 s |
|
1921 | Compiler : 0.78 s | |
1925 | """ |
|
1922 | """ | |
1926 |
|
1923 | |||
1927 | # fail immediately if the given expression can't be compiled |
|
1924 | # fail immediately if the given expression can't be compiled | |
1928 |
|
1925 | |||
1929 | expr = self.shell.prefilter(parameter_s,False) |
|
1926 | expr = self.shell.prefilter(parameter_s,False) | |
1930 |
|
1927 | |||
1931 | # Minimum time above which compilation time will be reported |
|
1928 | # Minimum time above which compilation time will be reported | |
1932 | tc_min = 0.1 |
|
1929 | tc_min = 0.1 | |
1933 |
|
1930 | |||
1934 | try: |
|
1931 | try: | |
1935 | mode = 'eval' |
|
1932 | mode = 'eval' | |
1936 | t0 = clock() |
|
1933 | t0 = clock() | |
1937 | code = compile(expr,'<timed eval>',mode) |
|
1934 | code = compile(expr,'<timed eval>',mode) | |
1938 | tc = clock()-t0 |
|
1935 | tc = clock()-t0 | |
1939 | except SyntaxError: |
|
1936 | except SyntaxError: | |
1940 | mode = 'exec' |
|
1937 | mode = 'exec' | |
1941 | t0 = clock() |
|
1938 | t0 = clock() | |
1942 | code = compile(expr,'<timed exec>',mode) |
|
1939 | code = compile(expr,'<timed exec>',mode) | |
1943 | tc = clock()-t0 |
|
1940 | tc = clock()-t0 | |
1944 | # skew measurement as little as possible |
|
1941 | # skew measurement as little as possible | |
1945 | glob = self.shell.user_ns |
|
1942 | glob = self.shell.user_ns | |
1946 | clk = clock2 |
|
1943 | clk = clock2 | |
1947 | wtime = time.time |
|
1944 | wtime = time.time | |
1948 | # time execution |
|
1945 | # time execution | |
1949 | wall_st = wtime() |
|
1946 | wall_st = wtime() | |
1950 | if mode=='eval': |
|
1947 | if mode=='eval': | |
1951 | st = clk() |
|
1948 | st = clk() | |
1952 | out = eval(code,glob) |
|
1949 | out = eval(code,glob) | |
1953 | end = clk() |
|
1950 | end = clk() | |
1954 | else: |
|
1951 | else: | |
1955 | st = clk() |
|
1952 | st = clk() | |
1956 | exec code in glob |
|
1953 | exec code in glob | |
1957 | end = clk() |
|
1954 | end = clk() | |
1958 | out = None |
|
1955 | out = None | |
1959 | wall_end = wtime() |
|
1956 | wall_end = wtime() | |
1960 | # Compute actual times and report |
|
1957 | # Compute actual times and report | |
1961 | wall_time = wall_end-wall_st |
|
1958 | wall_time = wall_end-wall_st | |
1962 | cpu_user = end[0]-st[0] |
|
1959 | cpu_user = end[0]-st[0] | |
1963 | cpu_sys = end[1]-st[1] |
|
1960 | cpu_sys = end[1]-st[1] | |
1964 | cpu_tot = cpu_user+cpu_sys |
|
1961 | cpu_tot = cpu_user+cpu_sys | |
1965 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1962 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1966 | (cpu_user,cpu_sys,cpu_tot) |
|
1963 | (cpu_user,cpu_sys,cpu_tot) | |
1967 | print "Wall time: %.2f s" % wall_time |
|
1964 | print "Wall time: %.2f s" % wall_time | |
1968 | if tc > tc_min: |
|
1965 | if tc > tc_min: | |
1969 | print "Compiler : %.2f s" % tc |
|
1966 | print "Compiler : %.2f s" % tc | |
1970 | return out |
|
1967 | return out | |
1971 |
|
1968 | |||
1972 | @testdec.skip_doctest |
|
1969 | @testdec.skip_doctest | |
1973 | def magic_macro(self,parameter_s = ''): |
|
1970 | def magic_macro(self,parameter_s = ''): | |
1974 | """Define a set of input lines as a macro for future re-execution. |
|
1971 | """Define a set of input lines as a macro for future re-execution. | |
1975 |
|
1972 | |||
1976 | Usage:\\ |
|
1973 | Usage:\\ | |
1977 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1974 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1978 |
|
1975 | |||
1979 | Options: |
|
1976 | Options: | |
1980 |
|
1977 | |||
1981 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1978 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1982 | so that magics are loaded in their transformed version to valid |
|
1979 | so that magics are loaded in their transformed version to valid | |
1983 | Python. If this option is given, the raw input as typed as the |
|
1980 | Python. If this option is given, the raw input as typed as the | |
1984 | command line is used instead. |
|
1981 | command line is used instead. | |
1985 |
|
1982 | |||
1986 | This will define a global variable called `name` which is a string |
|
1983 | This will define a global variable called `name` which is a string | |
1987 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1984 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1988 | above) from your input history into a single string. This variable |
|
1985 | above) from your input history into a single string. This variable | |
1989 | acts like an automatic function which re-executes those lines as if |
|
1986 | acts like an automatic function which re-executes those lines as if | |
1990 | you had typed them. You just type 'name' at the prompt and the code |
|
1987 | you had typed them. You just type 'name' at the prompt and the code | |
1991 | executes. |
|
1988 | executes. | |
1992 |
|
1989 | |||
1993 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1990 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1994 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1991 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1995 | using the lines numbered 5,6 and 7. |
|
1992 | using the lines numbered 5,6 and 7. | |
1996 |
|
1993 | |||
1997 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1994 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1998 | notation, where N:M means numbers N through M-1. |
|
1995 | notation, where N:M means numbers N through M-1. | |
1999 |
|
1996 | |||
2000 | For example, if your history contains (%hist prints it): |
|
1997 | For example, if your history contains (%hist prints it): | |
2001 |
|
1998 | |||
2002 | 44: x=1 |
|
1999 | 44: x=1 | |
2003 | 45: y=3 |
|
2000 | 45: y=3 | |
2004 | 46: z=x+y |
|
2001 | 46: z=x+y | |
2005 | 47: print x |
|
2002 | 47: print x | |
2006 | 48: a=5 |
|
2003 | 48: a=5 | |
2007 | 49: print 'x',x,'y',y |
|
2004 | 49: print 'x',x,'y',y | |
2008 |
|
2005 | |||
2009 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2006 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2010 | called my_macro with: |
|
2007 | called my_macro with: | |
2011 |
|
2008 | |||
2012 | In [55]: %macro my_macro 44-47 49 |
|
2009 | In [55]: %macro my_macro 44-47 49 | |
2013 |
|
2010 | |||
2014 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2011 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2015 | in one pass. |
|
2012 | in one pass. | |
2016 |
|
2013 | |||
2017 | You don't need to give the line-numbers in order, and any given line |
|
2014 | You don't need to give the line-numbers in order, and any given line | |
2018 | number can appear multiple times. You can assemble macros with any |
|
2015 | number can appear multiple times. You can assemble macros with any | |
2019 | lines from your input history in any order. |
|
2016 | lines from your input history in any order. | |
2020 |
|
2017 | |||
2021 | The macro is a simple object which holds its value in an attribute, |
|
2018 | The macro is a simple object which holds its value in an attribute, | |
2022 | but IPython's display system checks for macros and executes them as |
|
2019 | but IPython's display system checks for macros and executes them as | |
2023 | code instead of printing them when you type their name. |
|
2020 | code instead of printing them when you type their name. | |
2024 |
|
2021 | |||
2025 | You can view a macro's contents by explicitly printing it with: |
|
2022 | You can view a macro's contents by explicitly printing it with: | |
2026 |
|
2023 | |||
2027 | 'print macro_name'. |
|
2024 | 'print macro_name'. | |
2028 |
|
2025 | |||
2029 | For one-off cases which DON'T contain magic function calls in them you |
|
2026 | For one-off cases which DON'T contain magic function calls in them you | |
2030 | can obtain similar results by explicitly executing slices from your |
|
2027 | can obtain similar results by explicitly executing slices from your | |
2031 | input history with: |
|
2028 | input history with: | |
2032 |
|
2029 | |||
2033 | In [60]: exec In[44:48]+In[49]""" |
|
2030 | In [60]: exec In[44:48]+In[49]""" | |
2034 |
|
2031 | |||
2035 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2032 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2036 | if not args: |
|
2033 | if not args: | |
2037 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2034 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
2038 | macs.sort() |
|
2035 | macs.sort() | |
2039 | return macs |
|
2036 | return macs | |
2040 | if len(args) == 1: |
|
2037 | if len(args) == 1: | |
2041 | raise UsageError( |
|
2038 | raise UsageError( | |
2042 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2039 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2043 | name,ranges = args[0], args[1:] |
|
2040 | name,ranges = args[0], args[1:] | |
2044 |
|
2041 | |||
2045 | #print 'rng',ranges # dbg |
|
2042 | #print 'rng',ranges # dbg | |
2046 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2043 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
2047 | macro = Macro(lines) |
|
2044 | macro = Macro("\n".join(lines)) | |
2048 | self.shell.define_macro(name, macro) |
|
2045 | self.shell.define_macro(name, macro) | |
2049 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2046 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2050 | print 'Macro contents:' |
|
2047 | print 'Macro contents:' | |
2051 | print macro, |
|
2048 | print macro, | |
2052 |
|
2049 | |||
2053 | def magic_save(self,parameter_s = ''): |
|
2050 | def magic_save(self,parameter_s = ''): | |
2054 | """Save a set of lines to a given filename. |
|
2051 | """Save a set of lines to a given filename. | |
2055 |
|
2052 | |||
2056 | Usage:\\ |
|
2053 | Usage:\\ | |
2057 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2054 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2058 |
|
2055 | |||
2059 | Options: |
|
2056 | Options: | |
2060 |
|
2057 | |||
2061 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2058 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2062 | so that magics are loaded in their transformed version to valid |
|
2059 | so that magics are loaded in their transformed version to valid | |
2063 | Python. If this option is given, the raw input as typed as the |
|
2060 | Python. If this option is given, the raw input as typed as the | |
2064 | command line is used instead. |
|
2061 | command line is used instead. | |
2065 |
|
2062 | |||
2066 | This function uses the same syntax as %macro for line extraction, but |
|
2063 | This function uses the same syntax as %macro for line extraction, but | |
2067 | instead of creating a macro it saves the resulting string to the |
|
2064 | instead of creating a macro it saves the resulting string to the | |
2068 | filename you specify. |
|
2065 | filename you specify. | |
2069 |
|
2066 | |||
2070 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2067 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2071 | it asks for confirmation before overwriting existing files.""" |
|
2068 | it asks for confirmation before overwriting existing files.""" | |
2072 |
|
2069 | |||
2073 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2070 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2074 | fname,ranges = args[0], args[1:] |
|
2071 | fname,ranges = args[0], args[1:] | |
2075 | if not fname.endswith('.py'): |
|
2072 | if not fname.endswith('.py'): | |
2076 | fname += '.py' |
|
2073 | fname += '.py' | |
2077 | if os.path.isfile(fname): |
|
2074 | if os.path.isfile(fname): | |
2078 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2075 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2079 | if ans.lower() not in ['y','yes']: |
|
2076 | if ans.lower() not in ['y','yes']: | |
2080 | print 'Operation cancelled.' |
|
2077 | print 'Operation cancelled.' | |
2081 | return |
|
2078 | return | |
2082 | cmds = '\n'.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2079 | cmds = '\n'.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2083 | with open(fname,'w') as f: |
|
2080 | with open(fname,'w') as f: | |
2084 | f.write(cmds) |
|
2081 | f.write(cmds) | |
2085 | print 'The following commands were written to file `%s`:' % fname |
|
2082 | print 'The following commands were written to file `%s`:' % fname | |
2086 | print cmds |
|
2083 | print cmds | |
2087 |
|
2084 | |||
2088 | def _edit_macro(self,mname,macro): |
|
2085 | def _edit_macro(self,mname,macro): | |
2089 | """open an editor with the macro data in a file""" |
|
2086 | """open an editor with the macro data in a file""" | |
2090 | filename = self.shell.mktempfile(macro.value) |
|
2087 | filename = self.shell.mktempfile(macro.value) | |
2091 | self.shell.hooks.editor(filename) |
|
2088 | self.shell.hooks.editor(filename) | |
2092 |
|
2089 | |||
2093 | # and make a new macro object, to replace the old one |
|
2090 | # and make a new macro object, to replace the old one | |
2094 | mfile = open(filename) |
|
2091 | mfile = open(filename) | |
2095 | mvalue = mfile.read() |
|
2092 | mvalue = mfile.read() | |
2096 | mfile.close() |
|
2093 | mfile.close() | |
2097 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2094 | self.shell.user_ns[mname] = Macro(mvalue) | |
2098 |
|
2095 | |||
2099 | def magic_ed(self,parameter_s=''): |
|
2096 | def magic_ed(self,parameter_s=''): | |
2100 | """Alias to %edit.""" |
|
2097 | """Alias to %edit.""" | |
2101 | return self.magic_edit(parameter_s) |
|
2098 | return self.magic_edit(parameter_s) | |
2102 |
|
2099 | |||
2103 | @testdec.skip_doctest |
|
2100 | @testdec.skip_doctest | |
2104 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2101 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2105 | """Bring up an editor and execute the resulting code. |
|
2102 | """Bring up an editor and execute the resulting code. | |
2106 |
|
2103 | |||
2107 | Usage: |
|
2104 | Usage: | |
2108 | %edit [options] [args] |
|
2105 | %edit [options] [args] | |
2109 |
|
2106 | |||
2110 | %edit runs IPython's editor hook. The default version of this hook is |
|
2107 | %edit runs IPython's editor hook. The default version of this hook is | |
2111 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2108 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2112 | environment variable $EDITOR. If this isn't found, it will default to |
|
2109 | environment variable $EDITOR. If this isn't found, it will default to | |
2113 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2110 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2114 | docstring for how to change the editor hook. |
|
2111 | docstring for how to change the editor hook. | |
2115 |
|
2112 | |||
2116 | You can also set the value of this editor via the command line option |
|
2113 | You can also set the value of this editor via the command line option | |
2117 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2114 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2118 | specifically for IPython an editor different from your typical default |
|
2115 | specifically for IPython an editor different from your typical default | |
2119 | (and for Windows users who typically don't set environment variables). |
|
2116 | (and for Windows users who typically don't set environment variables). | |
2120 |
|
2117 | |||
2121 | This command allows you to conveniently edit multi-line code right in |
|
2118 | This command allows you to conveniently edit multi-line code right in | |
2122 | your IPython session. |
|
2119 | your IPython session. | |
2123 |
|
2120 | |||
2124 | If called without arguments, %edit opens up an empty editor with a |
|
2121 | If called without arguments, %edit opens up an empty editor with a | |
2125 | temporary file and will execute the contents of this file when you |
|
2122 | temporary file and will execute the contents of this file when you | |
2126 | close it (don't forget to save it!). |
|
2123 | close it (don't forget to save it!). | |
2127 |
|
2124 | |||
2128 |
|
2125 | |||
2129 | Options: |
|
2126 | Options: | |
2130 |
|
2127 | |||
2131 | -n <number>: open the editor at a specified line number. By default, |
|
2128 | -n <number>: open the editor at a specified line number. By default, | |
2132 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2129 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2133 | you can configure this by providing your own modified hook if your |
|
2130 | you can configure this by providing your own modified hook if your | |
2134 | favorite editor supports line-number specifications with a different |
|
2131 | favorite editor supports line-number specifications with a different | |
2135 | syntax. |
|
2132 | syntax. | |
2136 |
|
2133 | |||
2137 | -p: this will call the editor with the same data as the previous time |
|
2134 | -p: this will call the editor with the same data as the previous time | |
2138 | it was used, regardless of how long ago (in your current session) it |
|
2135 | it was used, regardless of how long ago (in your current session) it | |
2139 | was. |
|
2136 | was. | |
2140 |
|
2137 | |||
2141 | -r: use 'raw' input. This option only applies to input taken from the |
|
2138 | -r: use 'raw' input. This option only applies to input taken from the | |
2142 | user's history. By default, the 'processed' history is used, so that |
|
2139 | user's history. By default, the 'processed' history is used, so that | |
2143 | magics are loaded in their transformed version to valid Python. If |
|
2140 | magics are loaded in their transformed version to valid Python. If | |
2144 | this option is given, the raw input as typed as the command line is |
|
2141 | this option is given, the raw input as typed as the command line is | |
2145 | used instead. When you exit the editor, it will be executed by |
|
2142 | used instead. When you exit the editor, it will be executed by | |
2146 | IPython's own processor. |
|
2143 | IPython's own processor. | |
2147 |
|
2144 | |||
2148 | -x: do not execute the edited code immediately upon exit. This is |
|
2145 | -x: do not execute the edited code immediately upon exit. This is | |
2149 | mainly useful if you are editing programs which need to be called with |
|
2146 | mainly useful if you are editing programs which need to be called with | |
2150 | command line arguments, which you can then do using %run. |
|
2147 | command line arguments, which you can then do using %run. | |
2151 |
|
2148 | |||
2152 |
|
2149 | |||
2153 | Arguments: |
|
2150 | Arguments: | |
2154 |
|
2151 | |||
2155 | If arguments are given, the following possibilites exist: |
|
2152 | If arguments are given, the following possibilites exist: | |
2156 |
|
2153 | |||
2157 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2154 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2158 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2155 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2159 | loaded into the editor. The syntax is the same of the %macro command. |
|
2156 | loaded into the editor. The syntax is the same of the %macro command. | |
2160 |
|
2157 | |||
2161 | - If the argument doesn't start with a number, it is evaluated as a |
|
2158 | - If the argument doesn't start with a number, it is evaluated as a | |
2162 | variable and its contents loaded into the editor. You can thus edit |
|
2159 | variable and its contents loaded into the editor. You can thus edit | |
2163 | any string which contains python code (including the result of |
|
2160 | any string which contains python code (including the result of | |
2164 | previous edits). |
|
2161 | previous edits). | |
2165 |
|
2162 | |||
2166 | - If the argument is the name of an object (other than a string), |
|
2163 | - If the argument is the name of an object (other than a string), | |
2167 | IPython will try to locate the file where it was defined and open the |
|
2164 | IPython will try to locate the file where it was defined and open the | |
2168 | editor at the point where it is defined. You can use `%edit function` |
|
2165 | editor at the point where it is defined. You can use `%edit function` | |
2169 | to load an editor exactly at the point where 'function' is defined, |
|
2166 | to load an editor exactly at the point where 'function' is defined, | |
2170 | edit it and have the file be executed automatically. |
|
2167 | edit it and have the file be executed automatically. | |
2171 |
|
2168 | |||
2172 | If the object is a macro (see %macro for details), this opens up your |
|
2169 | If the object is a macro (see %macro for details), this opens up your | |
2173 | specified editor with a temporary file containing the macro's data. |
|
2170 | specified editor with a temporary file containing the macro's data. | |
2174 | Upon exit, the macro is reloaded with the contents of the file. |
|
2171 | Upon exit, the macro is reloaded with the contents of the file. | |
2175 |
|
2172 | |||
2176 | Note: opening at an exact line is only supported under Unix, and some |
|
2173 | Note: opening at an exact line is only supported under Unix, and some | |
2177 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2174 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2178 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2175 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2179 | (X)Emacs, vi, jed, pico and joe all do. |
|
2176 | (X)Emacs, vi, jed, pico and joe all do. | |
2180 |
|
2177 | |||
2181 | - If the argument is not found as a variable, IPython will look for a |
|
2178 | - If the argument is not found as a variable, IPython will look for a | |
2182 | file with that name (adding .py if necessary) and load it into the |
|
2179 | file with that name (adding .py if necessary) and load it into the | |
2183 | editor. It will execute its contents with execfile() when you exit, |
|
2180 | editor. It will execute its contents with execfile() when you exit, | |
2184 | loading any code in the file into your interactive namespace. |
|
2181 | loading any code in the file into your interactive namespace. | |
2185 |
|
2182 | |||
2186 | After executing your code, %edit will return as output the code you |
|
2183 | After executing your code, %edit will return as output the code you | |
2187 | typed in the editor (except when it was an existing file). This way |
|
2184 | typed in the editor (except when it was an existing file). This way | |
2188 | you can reload the code in further invocations of %edit as a variable, |
|
2185 | you can reload the code in further invocations of %edit as a variable, | |
2189 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2186 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2190 | the output. |
|
2187 | the output. | |
2191 |
|
2188 | |||
2192 | Note that %edit is also available through the alias %ed. |
|
2189 | Note that %edit is also available through the alias %ed. | |
2193 |
|
2190 | |||
2194 | This is an example of creating a simple function inside the editor and |
|
2191 | This is an example of creating a simple function inside the editor and | |
2195 | then modifying it. First, start up the editor: |
|
2192 | then modifying it. First, start up the editor: | |
2196 |
|
2193 | |||
2197 | In [1]: ed |
|
2194 | In [1]: ed | |
2198 | Editing... done. Executing edited code... |
|
2195 | Editing... done. Executing edited code... | |
2199 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2196 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2200 |
|
2197 | |||
2201 | We can then call the function foo(): |
|
2198 | We can then call the function foo(): | |
2202 |
|
2199 | |||
2203 | In [2]: foo() |
|
2200 | In [2]: foo() | |
2204 | foo() was defined in an editing session |
|
2201 | foo() was defined in an editing session | |
2205 |
|
2202 | |||
2206 | Now we edit foo. IPython automatically loads the editor with the |
|
2203 | Now we edit foo. IPython automatically loads the editor with the | |
2207 | (temporary) file where foo() was previously defined: |
|
2204 | (temporary) file where foo() was previously defined: | |
2208 |
|
2205 | |||
2209 | In [3]: ed foo |
|
2206 | In [3]: ed foo | |
2210 | Editing... done. Executing edited code... |
|
2207 | Editing... done. Executing edited code... | |
2211 |
|
2208 | |||
2212 | And if we call foo() again we get the modified version: |
|
2209 | And if we call foo() again we get the modified version: | |
2213 |
|
2210 | |||
2214 | In [4]: foo() |
|
2211 | In [4]: foo() | |
2215 | foo() has now been changed! |
|
2212 | foo() has now been changed! | |
2216 |
|
2213 | |||
2217 | Here is an example of how to edit a code snippet successive |
|
2214 | Here is an example of how to edit a code snippet successive | |
2218 | times. First we call the editor: |
|
2215 | times. First we call the editor: | |
2219 |
|
2216 | |||
2220 | In [5]: ed |
|
2217 | In [5]: ed | |
2221 | Editing... done. Executing edited code... |
|
2218 | Editing... done. Executing edited code... | |
2222 | hello |
|
2219 | hello | |
2223 | Out[5]: "print 'hello'n" |
|
2220 | Out[5]: "print 'hello'n" | |
2224 |
|
2221 | |||
2225 | Now we call it again with the previous output (stored in _): |
|
2222 | Now we call it again with the previous output (stored in _): | |
2226 |
|
2223 | |||
2227 | In [6]: ed _ |
|
2224 | In [6]: ed _ | |
2228 | Editing... done. Executing edited code... |
|
2225 | Editing... done. Executing edited code... | |
2229 | hello world |
|
2226 | hello world | |
2230 | Out[6]: "print 'hello world'n" |
|
2227 | Out[6]: "print 'hello world'n" | |
2231 |
|
2228 | |||
2232 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2229 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2233 |
|
2230 | |||
2234 | In [7]: ed _8 |
|
2231 | In [7]: ed _8 | |
2235 | Editing... done. Executing edited code... |
|
2232 | Editing... done. Executing edited code... | |
2236 | hello again |
|
2233 | hello again | |
2237 | Out[7]: "print 'hello again'n" |
|
2234 | Out[7]: "print 'hello again'n" | |
2238 |
|
2235 | |||
2239 |
|
2236 | |||
2240 | Changing the default editor hook: |
|
2237 | Changing the default editor hook: | |
2241 |
|
2238 | |||
2242 | If you wish to write your own editor hook, you can put it in a |
|
2239 | If you wish to write your own editor hook, you can put it in a | |
2243 | configuration file which you load at startup time. The default hook |
|
2240 | configuration file which you load at startup time. The default hook | |
2244 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2241 | is defined in the IPython.core.hooks module, and you can use that as a | |
2245 | starting example for further modifications. That file also has |
|
2242 | starting example for further modifications. That file also has | |
2246 | general instructions on how to set a new hook for use once you've |
|
2243 | general instructions on how to set a new hook for use once you've | |
2247 | defined it.""" |
|
2244 | defined it.""" | |
2248 |
|
2245 | |||
2249 | # FIXME: This function has become a convoluted mess. It needs a |
|
2246 | # FIXME: This function has become a convoluted mess. It needs a | |
2250 | # ground-up rewrite with clean, simple logic. |
|
2247 | # ground-up rewrite with clean, simple logic. | |
2251 |
|
2248 | |||
2252 | def make_filename(arg): |
|
2249 | def make_filename(arg): | |
2253 | "Make a filename from the given args" |
|
2250 | "Make a filename from the given args" | |
2254 | try: |
|
2251 | try: | |
2255 | filename = get_py_filename(arg) |
|
2252 | filename = get_py_filename(arg) | |
2256 | except IOError: |
|
2253 | except IOError: | |
2257 | if args.endswith('.py'): |
|
2254 | if args.endswith('.py'): | |
2258 | filename = arg |
|
2255 | filename = arg | |
2259 | else: |
|
2256 | else: | |
2260 | filename = None |
|
2257 | filename = None | |
2261 | return filename |
|
2258 | return filename | |
2262 |
|
2259 | |||
2263 | # custom exceptions |
|
2260 | # custom exceptions | |
2264 | class DataIsObject(Exception): pass |
|
2261 | class DataIsObject(Exception): pass | |
2265 |
|
2262 | |||
2266 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2263 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2267 | # Set a few locals from the options for convenience: |
|
2264 | # Set a few locals from the options for convenience: | |
2268 | opts_p = opts.has_key('p') |
|
2265 | opts_p = opts.has_key('p') | |
2269 | opts_r = opts.has_key('r') |
|
2266 | opts_r = opts.has_key('r') | |
2270 |
|
2267 | |||
2271 | # Default line number value |
|
2268 | # Default line number value | |
2272 | lineno = opts.get('n',None) |
|
2269 | lineno = opts.get('n',None) | |
2273 |
|
2270 | |||
2274 | if opts_p: |
|
2271 | if opts_p: | |
2275 | args = '_%s' % last_call[0] |
|
2272 | args = '_%s' % last_call[0] | |
2276 | if not self.shell.user_ns.has_key(args): |
|
2273 | if not self.shell.user_ns.has_key(args): | |
2277 | args = last_call[1] |
|
2274 | args = last_call[1] | |
2278 |
|
2275 | |||
2279 | # use last_call to remember the state of the previous call, but don't |
|
2276 | # use last_call to remember the state of the previous call, but don't | |
2280 | # let it be clobbered by successive '-p' calls. |
|
2277 | # let it be clobbered by successive '-p' calls. | |
2281 | try: |
|
2278 | try: | |
2282 | last_call[0] = self.shell.displayhook.prompt_count |
|
2279 | last_call[0] = self.shell.displayhook.prompt_count | |
2283 | if not opts_p: |
|
2280 | if not opts_p: | |
2284 | last_call[1] = parameter_s |
|
2281 | last_call[1] = parameter_s | |
2285 | except: |
|
2282 | except: | |
2286 | pass |
|
2283 | pass | |
2287 |
|
2284 | |||
2288 | # by default this is done with temp files, except when the given |
|
2285 | # by default this is done with temp files, except when the given | |
2289 | # arg is a filename |
|
2286 | # arg is a filename | |
2290 | use_temp = 1 |
|
2287 | use_temp = 1 | |
2291 |
|
2288 | |||
2292 | if re.match(r'\d',args): |
|
2289 | if re.match(r'\d',args): | |
2293 | # Mode where user specifies ranges of lines, like in %macro. |
|
2290 | # Mode where user specifies ranges of lines, like in %macro. | |
2294 | # This means that you can't edit files whose names begin with |
|
2291 | # This means that you can't edit files whose names begin with | |
2295 | # numbers this way. Tough. |
|
2292 | # numbers this way. Tough. | |
2296 | ranges = args.split() |
|
2293 | ranges = args.split() | |
2297 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2294 | data = '\n'.join(self.extract_input_slices(ranges,opts_r)) | |
2298 | elif args.endswith('.py'): |
|
2295 | elif args.endswith('.py'): | |
2299 | filename = make_filename(args) |
|
2296 | filename = make_filename(args) | |
2300 | data = '' |
|
2297 | data = '' | |
2301 | use_temp = 0 |
|
2298 | use_temp = 0 | |
2302 | elif args: |
|
2299 | elif args: | |
2303 | try: |
|
2300 | try: | |
2304 | # Load the parameter given as a variable. If not a string, |
|
2301 | # Load the parameter given as a variable. If not a string, | |
2305 | # process it as an object instead (below) |
|
2302 | # process it as an object instead (below) | |
2306 |
|
2303 | |||
2307 | #print '*** args',args,'type',type(args) # dbg |
|
2304 | #print '*** args',args,'type',type(args) # dbg | |
2308 | data = eval(args,self.shell.user_ns) |
|
2305 | data = eval(args,self.shell.user_ns) | |
2309 | if not type(data) in StringTypes: |
|
2306 | if not type(data) in StringTypes: | |
2310 | raise DataIsObject |
|
2307 | raise DataIsObject | |
2311 |
|
2308 | |||
2312 | except (NameError,SyntaxError): |
|
2309 | except (NameError,SyntaxError): | |
2313 | # given argument is not a variable, try as a filename |
|
2310 | # given argument is not a variable, try as a filename | |
2314 | filename = make_filename(args) |
|
2311 | filename = make_filename(args) | |
2315 | if filename is None: |
|
2312 | if filename is None: | |
2316 | warn("Argument given (%s) can't be found as a variable " |
|
2313 | warn("Argument given (%s) can't be found as a variable " | |
2317 | "or as a filename." % args) |
|
2314 | "or as a filename." % args) | |
2318 | return |
|
2315 | return | |
2319 |
|
2316 | |||
2320 | data = '' |
|
2317 | data = '' | |
2321 | use_temp = 0 |
|
2318 | use_temp = 0 | |
2322 | except DataIsObject: |
|
2319 | except DataIsObject: | |
2323 |
|
2320 | |||
2324 | # macros have a special edit function |
|
2321 | # macros have a special edit function | |
2325 | if isinstance(data,Macro): |
|
2322 | if isinstance(data,Macro): | |
2326 | self._edit_macro(args,data) |
|
2323 | self._edit_macro(args,data) | |
2327 | return |
|
2324 | return | |
2328 |
|
2325 | |||
2329 | # For objects, try to edit the file where they are defined |
|
2326 | # For objects, try to edit the file where they are defined | |
2330 | try: |
|
2327 | try: | |
2331 | filename = inspect.getabsfile(data) |
|
2328 | filename = inspect.getabsfile(data) | |
2332 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2329 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2333 | # class created by %edit? Try to find source |
|
2330 | # class created by %edit? Try to find source | |
2334 | # by looking for method definitions instead, the |
|
2331 | # by looking for method definitions instead, the | |
2335 | # __module__ in those classes is FakeModule. |
|
2332 | # __module__ in those classes is FakeModule. | |
2336 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2333 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2337 | for attr in attrs: |
|
2334 | for attr in attrs: | |
2338 | if not inspect.ismethod(attr): |
|
2335 | if not inspect.ismethod(attr): | |
2339 | continue |
|
2336 | continue | |
2340 | filename = inspect.getabsfile(attr) |
|
2337 | filename = inspect.getabsfile(attr) | |
2341 | if filename and 'fakemodule' not in filename.lower(): |
|
2338 | if filename and 'fakemodule' not in filename.lower(): | |
2342 | # change the attribute to be the edit target instead |
|
2339 | # change the attribute to be the edit target instead | |
2343 | data = attr |
|
2340 | data = attr | |
2344 | break |
|
2341 | break | |
2345 |
|
2342 | |||
2346 | datafile = 1 |
|
2343 | datafile = 1 | |
2347 | except TypeError: |
|
2344 | except TypeError: | |
2348 | filename = make_filename(args) |
|
2345 | filename = make_filename(args) | |
2349 | datafile = 1 |
|
2346 | datafile = 1 | |
2350 | warn('Could not find file where `%s` is defined.\n' |
|
2347 | warn('Could not find file where `%s` is defined.\n' | |
2351 | 'Opening a file named `%s`' % (args,filename)) |
|
2348 | 'Opening a file named `%s`' % (args,filename)) | |
2352 | # Now, make sure we can actually read the source (if it was in |
|
2349 | # Now, make sure we can actually read the source (if it was in | |
2353 | # a temp file it's gone by now). |
|
2350 | # a temp file it's gone by now). | |
2354 | if datafile: |
|
2351 | if datafile: | |
2355 | try: |
|
2352 | try: | |
2356 | if lineno is None: |
|
2353 | if lineno is None: | |
2357 | lineno = inspect.getsourcelines(data)[1] |
|
2354 | lineno = inspect.getsourcelines(data)[1] | |
2358 | except IOError: |
|
2355 | except IOError: | |
2359 | filename = make_filename(args) |
|
2356 | filename = make_filename(args) | |
2360 | if filename is None: |
|
2357 | if filename is None: | |
2361 | warn('The file `%s` where `%s` was defined cannot ' |
|
2358 | warn('The file `%s` where `%s` was defined cannot ' | |
2362 | 'be read.' % (filename,data)) |
|
2359 | 'be read.' % (filename,data)) | |
2363 | return |
|
2360 | return | |
2364 | use_temp = 0 |
|
2361 | use_temp = 0 | |
2365 | else: |
|
2362 | else: | |
2366 | data = '' |
|
2363 | data = '' | |
2367 |
|
2364 | |||
2368 | if use_temp: |
|
2365 | if use_temp: | |
2369 | filename = self.shell.mktempfile(data) |
|
2366 | filename = self.shell.mktempfile(data) | |
2370 | print 'IPython will make a temporary file named:',filename |
|
2367 | print 'IPython will make a temporary file named:',filename | |
2371 |
|
2368 | |||
2372 | # do actual editing here |
|
2369 | # do actual editing here | |
2373 | print 'Editing...', |
|
2370 | print 'Editing...', | |
2374 | sys.stdout.flush() |
|
2371 | sys.stdout.flush() | |
2375 | try: |
|
2372 | try: | |
2376 | # Quote filenames that may have spaces in them |
|
2373 | # Quote filenames that may have spaces in them | |
2377 | if ' ' in filename: |
|
2374 | if ' ' in filename: | |
2378 | filename = "%s" % filename |
|
2375 | filename = "%s" % filename | |
2379 | self.shell.hooks.editor(filename,lineno) |
|
2376 | self.shell.hooks.editor(filename,lineno) | |
2380 | except TryNext: |
|
2377 | except TryNext: | |
2381 | warn('Could not open editor') |
|
2378 | warn('Could not open editor') | |
2382 | return |
|
2379 | return | |
2383 |
|
2380 | |||
2384 | # XXX TODO: should this be generalized for all string vars? |
|
2381 | # XXX TODO: should this be generalized for all string vars? | |
2385 | # For now, this is special-cased to blocks created by cpaste |
|
2382 | # For now, this is special-cased to blocks created by cpaste | |
2386 | if args.strip() == 'pasted_block': |
|
2383 | if args.strip() == 'pasted_block': | |
2387 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2384 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2388 |
|
2385 | |||
2389 | if opts.has_key('x'): # -x prevents actual execution |
|
2386 | if opts.has_key('x'): # -x prevents actual execution | |
2390 |
|
2387 | |||
2391 | else: |
|
2388 | else: | |
2392 | print 'done. Executing edited code...' |
|
2389 | print 'done. Executing edited code...' | |
2393 | if opts_r: |
|
2390 | if opts_r: | |
2394 | self.shell.run_cell(file_read(filename)) |
|
2391 | self.shell.run_cell(file_read(filename)) | |
2395 | else: |
|
2392 | else: | |
2396 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2393 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2397 | self.shell.user_ns) |
|
2394 | self.shell.user_ns) | |
2398 |
|
2395 | |||
2399 |
|
2396 | |||
2400 | if use_temp: |
|
2397 | if use_temp: | |
2401 | try: |
|
2398 | try: | |
2402 | return open(filename).read() |
|
2399 | return open(filename).read() | |
2403 | except IOError,msg: |
|
2400 | except IOError,msg: | |
2404 | if msg.filename == filename: |
|
2401 | if msg.filename == filename: | |
2405 | warn('File not found. Did you forget to save?') |
|
2402 | warn('File not found. Did you forget to save?') | |
2406 | return |
|
2403 | return | |
2407 | else: |
|
2404 | else: | |
2408 | self.shell.showtraceback() |
|
2405 | self.shell.showtraceback() | |
2409 |
|
2406 | |||
2410 | def magic_xmode(self,parameter_s = ''): |
|
2407 | def magic_xmode(self,parameter_s = ''): | |
2411 | """Switch modes for the exception handlers. |
|
2408 | """Switch modes for the exception handlers. | |
2412 |
|
2409 | |||
2413 | Valid modes: Plain, Context and Verbose. |
|
2410 | Valid modes: Plain, Context and Verbose. | |
2414 |
|
2411 | |||
2415 | If called without arguments, acts as a toggle.""" |
|
2412 | If called without arguments, acts as a toggle.""" | |
2416 |
|
2413 | |||
2417 | def xmode_switch_err(name): |
|
2414 | def xmode_switch_err(name): | |
2418 | warn('Error changing %s exception modes.\n%s' % |
|
2415 | warn('Error changing %s exception modes.\n%s' % | |
2419 | (name,sys.exc_info()[1])) |
|
2416 | (name,sys.exc_info()[1])) | |
2420 |
|
2417 | |||
2421 | shell = self.shell |
|
2418 | shell = self.shell | |
2422 | new_mode = parameter_s.strip().capitalize() |
|
2419 | new_mode = parameter_s.strip().capitalize() | |
2423 | try: |
|
2420 | try: | |
2424 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2421 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2425 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2422 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2426 | except: |
|
2423 | except: | |
2427 | xmode_switch_err('user') |
|
2424 | xmode_switch_err('user') | |
2428 |
|
2425 | |||
2429 | def magic_colors(self,parameter_s = ''): |
|
2426 | def magic_colors(self,parameter_s = ''): | |
2430 | """Switch color scheme for prompts, info system and exception handlers. |
|
2427 | """Switch color scheme for prompts, info system and exception handlers. | |
2431 |
|
2428 | |||
2432 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2429 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2433 |
|
2430 | |||
2434 | Color scheme names are not case-sensitive. |
|
2431 | Color scheme names are not case-sensitive. | |
2435 |
|
2432 | |||
2436 | Examples |
|
2433 | Examples | |
2437 | -------- |
|
2434 | -------- | |
2438 | To get a plain black and white terminal:: |
|
2435 | To get a plain black and white terminal:: | |
2439 |
|
2436 | |||
2440 | %colors nocolor |
|
2437 | %colors nocolor | |
2441 | """ |
|
2438 | """ | |
2442 |
|
2439 | |||
2443 | def color_switch_err(name): |
|
2440 | def color_switch_err(name): | |
2444 | warn('Error changing %s color schemes.\n%s' % |
|
2441 | warn('Error changing %s color schemes.\n%s' % | |
2445 | (name,sys.exc_info()[1])) |
|
2442 | (name,sys.exc_info()[1])) | |
2446 |
|
2443 | |||
2447 |
|
2444 | |||
2448 | new_scheme = parameter_s.strip() |
|
2445 | new_scheme = parameter_s.strip() | |
2449 | if not new_scheme: |
|
2446 | if not new_scheme: | |
2450 | raise UsageError( |
|
2447 | raise UsageError( | |
2451 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2448 | "%colors: you must specify a color scheme. See '%colors?'") | |
2452 | return |
|
2449 | return | |
2453 | # local shortcut |
|
2450 | # local shortcut | |
2454 | shell = self.shell |
|
2451 | shell = self.shell | |
2455 |
|
2452 | |||
2456 | import IPython.utils.rlineimpl as readline |
|
2453 | import IPython.utils.rlineimpl as readline | |
2457 |
|
2454 | |||
2458 | if not readline.have_readline and sys.platform == "win32": |
|
2455 | if not readline.have_readline and sys.platform == "win32": | |
2459 | msg = """\ |
|
2456 | msg = """\ | |
2460 | Proper color support under MS Windows requires the pyreadline library. |
|
2457 | Proper color support under MS Windows requires the pyreadline library. | |
2461 | You can find it at: |
|
2458 | You can find it at: | |
2462 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2459 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2463 | Gary's readline needs the ctypes module, from: |
|
2460 | Gary's readline needs the ctypes module, from: | |
2464 | http://starship.python.net/crew/theller/ctypes |
|
2461 | http://starship.python.net/crew/theller/ctypes | |
2465 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2462 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2466 |
|
2463 | |||
2467 | Defaulting color scheme to 'NoColor'""" |
|
2464 | Defaulting color scheme to 'NoColor'""" | |
2468 | new_scheme = 'NoColor' |
|
2465 | new_scheme = 'NoColor' | |
2469 | warn(msg) |
|
2466 | warn(msg) | |
2470 |
|
2467 | |||
2471 | # readline option is 0 |
|
2468 | # readline option is 0 | |
2472 | if not shell.has_readline: |
|
2469 | if not shell.has_readline: | |
2473 | new_scheme = 'NoColor' |
|
2470 | new_scheme = 'NoColor' | |
2474 |
|
2471 | |||
2475 | # Set prompt colors |
|
2472 | # Set prompt colors | |
2476 | try: |
|
2473 | try: | |
2477 | shell.displayhook.set_colors(new_scheme) |
|
2474 | shell.displayhook.set_colors(new_scheme) | |
2478 | except: |
|
2475 | except: | |
2479 | color_switch_err('prompt') |
|
2476 | color_switch_err('prompt') | |
2480 | else: |
|
2477 | else: | |
2481 | shell.colors = \ |
|
2478 | shell.colors = \ | |
2482 | shell.displayhook.color_table.active_scheme_name |
|
2479 | shell.displayhook.color_table.active_scheme_name | |
2483 | # Set exception colors |
|
2480 | # Set exception colors | |
2484 | try: |
|
2481 | try: | |
2485 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2482 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2486 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2483 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2487 | except: |
|
2484 | except: | |
2488 | color_switch_err('exception') |
|
2485 | color_switch_err('exception') | |
2489 |
|
2486 | |||
2490 | # Set info (for 'object?') colors |
|
2487 | # Set info (for 'object?') colors | |
2491 | if shell.color_info: |
|
2488 | if shell.color_info: | |
2492 | try: |
|
2489 | try: | |
2493 | shell.inspector.set_active_scheme(new_scheme) |
|
2490 | shell.inspector.set_active_scheme(new_scheme) | |
2494 | except: |
|
2491 | except: | |
2495 | color_switch_err('object inspector') |
|
2492 | color_switch_err('object inspector') | |
2496 | else: |
|
2493 | else: | |
2497 | shell.inspector.set_active_scheme('NoColor') |
|
2494 | shell.inspector.set_active_scheme('NoColor') | |
2498 |
|
2495 | |||
2499 | def magic_pprint(self, parameter_s=''): |
|
2496 | def magic_pprint(self, parameter_s=''): | |
2500 | """Toggle pretty printing on/off.""" |
|
2497 | """Toggle pretty printing on/off.""" | |
2501 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2498 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
2502 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2499 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2503 | print 'Pretty printing has been turned', \ |
|
2500 | print 'Pretty printing has been turned', \ | |
2504 | ['OFF','ON'][ptformatter.pprint] |
|
2501 | ['OFF','ON'][ptformatter.pprint] | |
2505 |
|
2502 | |||
2506 | def magic_Exit(self, parameter_s=''): |
|
2503 | def magic_Exit(self, parameter_s=''): | |
2507 | """Exit IPython.""" |
|
2504 | """Exit IPython.""" | |
2508 |
|
2505 | |||
2509 | self.shell.ask_exit() |
|
2506 | self.shell.ask_exit() | |
2510 |
|
2507 | |||
2511 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2508 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2512 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2509 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2513 |
|
2510 | |||
2514 | #...................................................................... |
|
2511 | #...................................................................... | |
2515 | # Functions to implement unix shell-type things |
|
2512 | # Functions to implement unix shell-type things | |
2516 |
|
2513 | |||
2517 | @testdec.skip_doctest |
|
2514 | @testdec.skip_doctest | |
2518 | def magic_alias(self, parameter_s = ''): |
|
2515 | def magic_alias(self, parameter_s = ''): | |
2519 | """Define an alias for a system command. |
|
2516 | """Define an alias for a system command. | |
2520 |
|
2517 | |||
2521 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2518 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2522 |
|
2519 | |||
2523 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2520 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2524 | params' (from your underlying operating system). |
|
2521 | params' (from your underlying operating system). | |
2525 |
|
2522 | |||
2526 | Aliases have lower precedence than magic functions and Python normal |
|
2523 | Aliases have lower precedence than magic functions and Python normal | |
2527 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2524 | variables, so if 'foo' is both a Python variable and an alias, the | |
2528 | alias can not be executed until 'del foo' removes the Python variable. |
|
2525 | alias can not be executed until 'del foo' removes the Python variable. | |
2529 |
|
2526 | |||
2530 | You can use the %l specifier in an alias definition to represent the |
|
2527 | You can use the %l specifier in an alias definition to represent the | |
2531 | whole line when the alias is called. For example: |
|
2528 | whole line when the alias is called. For example: | |
2532 |
|
2529 | |||
2533 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2530 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2534 | In [3]: bracket hello world |
|
2531 | In [3]: bracket hello world | |
2535 | Input in brackets: <hello world> |
|
2532 | Input in brackets: <hello world> | |
2536 |
|
2533 | |||
2537 | You can also define aliases with parameters using %s specifiers (one |
|
2534 | You can also define aliases with parameters using %s specifiers (one | |
2538 | per parameter): |
|
2535 | per parameter): | |
2539 |
|
2536 | |||
2540 | In [1]: alias parts echo first %s second %s |
|
2537 | In [1]: alias parts echo first %s second %s | |
2541 | In [2]: %parts A B |
|
2538 | In [2]: %parts A B | |
2542 | first A second B |
|
2539 | first A second B | |
2543 | In [3]: %parts A |
|
2540 | In [3]: %parts A | |
2544 | Incorrect number of arguments: 2 expected. |
|
2541 | Incorrect number of arguments: 2 expected. | |
2545 | parts is an alias to: 'echo first %s second %s' |
|
2542 | parts is an alias to: 'echo first %s second %s' | |
2546 |
|
2543 | |||
2547 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2544 | Note that %l and %s are mutually exclusive. You can only use one or | |
2548 | the other in your aliases. |
|
2545 | the other in your aliases. | |
2549 |
|
2546 | |||
2550 | Aliases expand Python variables just like system calls using ! or !! |
|
2547 | Aliases expand Python variables just like system calls using ! or !! | |
2551 | do: all expressions prefixed with '$' get expanded. For details of |
|
2548 | do: all expressions prefixed with '$' get expanded. For details of | |
2552 | the semantic rules, see PEP-215: |
|
2549 | the semantic rules, see PEP-215: | |
2553 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2550 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2554 | IPython for variable expansion. If you want to access a true shell |
|
2551 | IPython for variable expansion. If you want to access a true shell | |
2555 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2552 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2556 |
|
2553 | |||
2557 | In [6]: alias show echo |
|
2554 | In [6]: alias show echo | |
2558 | In [7]: PATH='A Python string' |
|
2555 | In [7]: PATH='A Python string' | |
2559 | In [8]: show $PATH |
|
2556 | In [8]: show $PATH | |
2560 | A Python string |
|
2557 | A Python string | |
2561 | In [9]: show $$PATH |
|
2558 | In [9]: show $$PATH | |
2562 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2559 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2563 |
|
2560 | |||
2564 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2561 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2565 | and %rehashx functions, which automatically create aliases for the |
|
2562 | and %rehashx functions, which automatically create aliases for the | |
2566 | contents of your $PATH. |
|
2563 | contents of your $PATH. | |
2567 |
|
2564 | |||
2568 | If called with no parameters, %alias prints the current alias table.""" |
|
2565 | If called with no parameters, %alias prints the current alias table.""" | |
2569 |
|
2566 | |||
2570 | par = parameter_s.strip() |
|
2567 | par = parameter_s.strip() | |
2571 | if not par: |
|
2568 | if not par: | |
2572 | stored = self.db.get('stored_aliases', {} ) |
|
2569 | stored = self.db.get('stored_aliases', {} ) | |
2573 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2570 | aliases = sorted(self.shell.alias_manager.aliases) | |
2574 | # for k, v in stored: |
|
2571 | # for k, v in stored: | |
2575 | # atab.append(k, v[0]) |
|
2572 | # atab.append(k, v[0]) | |
2576 |
|
2573 | |||
2577 | print "Total number of aliases:", len(aliases) |
|
2574 | print "Total number of aliases:", len(aliases) | |
2578 | sys.stdout.flush() |
|
2575 | sys.stdout.flush() | |
2579 | return aliases |
|
2576 | return aliases | |
2580 |
|
2577 | |||
2581 | # Now try to define a new one |
|
2578 | # Now try to define a new one | |
2582 | try: |
|
2579 | try: | |
2583 | alias,cmd = par.split(None, 1) |
|
2580 | alias,cmd = par.split(None, 1) | |
2584 | except: |
|
2581 | except: | |
2585 | print oinspect.getdoc(self.magic_alias) |
|
2582 | print oinspect.getdoc(self.magic_alias) | |
2586 | else: |
|
2583 | else: | |
2587 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2584 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2588 | # end magic_alias |
|
2585 | # end magic_alias | |
2589 |
|
2586 | |||
2590 | def magic_unalias(self, parameter_s = ''): |
|
2587 | def magic_unalias(self, parameter_s = ''): | |
2591 | """Remove an alias""" |
|
2588 | """Remove an alias""" | |
2592 |
|
2589 | |||
2593 | aname = parameter_s.strip() |
|
2590 | aname = parameter_s.strip() | |
2594 | self.shell.alias_manager.undefine_alias(aname) |
|
2591 | self.shell.alias_manager.undefine_alias(aname) | |
2595 | stored = self.db.get('stored_aliases', {} ) |
|
2592 | stored = self.db.get('stored_aliases', {} ) | |
2596 | if aname in stored: |
|
2593 | if aname in stored: | |
2597 | print "Removing %stored alias",aname |
|
2594 | print "Removing %stored alias",aname | |
2598 | del stored[aname] |
|
2595 | del stored[aname] | |
2599 | self.db['stored_aliases'] = stored |
|
2596 | self.db['stored_aliases'] = stored | |
2600 |
|
2597 | |||
2601 | def magic_rehashx(self, parameter_s = ''): |
|
2598 | def magic_rehashx(self, parameter_s = ''): | |
2602 | """Update the alias table with all executable files in $PATH. |
|
2599 | """Update the alias table with all executable files in $PATH. | |
2603 |
|
2600 | |||
2604 | This version explicitly checks that every entry in $PATH is a file |
|
2601 | This version explicitly checks that every entry in $PATH is a file | |
2605 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2602 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2606 |
|
2603 | |||
2607 | Under Windows, it checks executability as a match agains a |
|
2604 | Under Windows, it checks executability as a match agains a | |
2608 | '|'-separated string of extensions, stored in the IPython config |
|
2605 | '|'-separated string of extensions, stored in the IPython config | |
2609 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2606 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2610 |
|
2607 | |||
2611 | This function also resets the root module cache of module completer, |
|
2608 | This function also resets the root module cache of module completer, | |
2612 | used on slow filesystems. |
|
2609 | used on slow filesystems. | |
2613 | """ |
|
2610 | """ | |
2614 | from IPython.core.alias import InvalidAliasError |
|
2611 | from IPython.core.alias import InvalidAliasError | |
2615 |
|
2612 | |||
2616 | # for the benefit of module completer in ipy_completers.py |
|
2613 | # for the benefit of module completer in ipy_completers.py | |
2617 | del self.db['rootmodules'] |
|
2614 | del self.db['rootmodules'] | |
2618 |
|
2615 | |||
2619 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2616 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2620 | os.environ.get('PATH','').split(os.pathsep)] |
|
2617 | os.environ.get('PATH','').split(os.pathsep)] | |
2621 | path = filter(os.path.isdir,path) |
|
2618 | path = filter(os.path.isdir,path) | |
2622 |
|
2619 | |||
2623 | syscmdlist = [] |
|
2620 | syscmdlist = [] | |
2624 | # Now define isexec in a cross platform manner. |
|
2621 | # Now define isexec in a cross platform manner. | |
2625 | if os.name == 'posix': |
|
2622 | if os.name == 'posix': | |
2626 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2623 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2627 | os.access(fname,os.X_OK) |
|
2624 | os.access(fname,os.X_OK) | |
2628 | else: |
|
2625 | else: | |
2629 | try: |
|
2626 | try: | |
2630 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2627 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2631 | except KeyError: |
|
2628 | except KeyError: | |
2632 | winext = 'exe|com|bat|py' |
|
2629 | winext = 'exe|com|bat|py' | |
2633 | if 'py' not in winext: |
|
2630 | if 'py' not in winext: | |
2634 | winext += '|py' |
|
2631 | winext += '|py' | |
2635 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2632 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2636 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2633 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2637 | savedir = os.getcwd() |
|
2634 | savedir = os.getcwd() | |
2638 |
|
2635 | |||
2639 | # Now walk the paths looking for executables to alias. |
|
2636 | # Now walk the paths looking for executables to alias. | |
2640 | try: |
|
2637 | try: | |
2641 | # write the whole loop for posix/Windows so we don't have an if in |
|
2638 | # write the whole loop for posix/Windows so we don't have an if in | |
2642 | # the innermost part |
|
2639 | # the innermost part | |
2643 | if os.name == 'posix': |
|
2640 | if os.name == 'posix': | |
2644 | for pdir in path: |
|
2641 | for pdir in path: | |
2645 | os.chdir(pdir) |
|
2642 | os.chdir(pdir) | |
2646 | for ff in os.listdir(pdir): |
|
2643 | for ff in os.listdir(pdir): | |
2647 | if isexec(ff): |
|
2644 | if isexec(ff): | |
2648 | try: |
|
2645 | try: | |
2649 | # Removes dots from the name since ipython |
|
2646 | # Removes dots from the name since ipython | |
2650 | # will assume names with dots to be python. |
|
2647 | # will assume names with dots to be python. | |
2651 | self.shell.alias_manager.define_alias( |
|
2648 | self.shell.alias_manager.define_alias( | |
2652 | ff.replace('.',''), ff) |
|
2649 | ff.replace('.',''), ff) | |
2653 | except InvalidAliasError: |
|
2650 | except InvalidAliasError: | |
2654 | pass |
|
2651 | pass | |
2655 | else: |
|
2652 | else: | |
2656 | syscmdlist.append(ff) |
|
2653 | syscmdlist.append(ff) | |
2657 | else: |
|
2654 | else: | |
2658 | no_alias = self.shell.alias_manager.no_alias |
|
2655 | no_alias = self.shell.alias_manager.no_alias | |
2659 | for pdir in path: |
|
2656 | for pdir in path: | |
2660 | os.chdir(pdir) |
|
2657 | os.chdir(pdir) | |
2661 | for ff in os.listdir(pdir): |
|
2658 | for ff in os.listdir(pdir): | |
2662 | base, ext = os.path.splitext(ff) |
|
2659 | base, ext = os.path.splitext(ff) | |
2663 | if isexec(ff) and base.lower() not in no_alias: |
|
2660 | if isexec(ff) and base.lower() not in no_alias: | |
2664 | if ext.lower() == '.exe': |
|
2661 | if ext.lower() == '.exe': | |
2665 | ff = base |
|
2662 | ff = base | |
2666 | try: |
|
2663 | try: | |
2667 | # Removes dots from the name since ipython |
|
2664 | # Removes dots from the name since ipython | |
2668 | # will assume names with dots to be python. |
|
2665 | # will assume names with dots to be python. | |
2669 | self.shell.alias_manager.define_alias( |
|
2666 | self.shell.alias_manager.define_alias( | |
2670 | base.lower().replace('.',''), ff) |
|
2667 | base.lower().replace('.',''), ff) | |
2671 | except InvalidAliasError: |
|
2668 | except InvalidAliasError: | |
2672 | pass |
|
2669 | pass | |
2673 | syscmdlist.append(ff) |
|
2670 | syscmdlist.append(ff) | |
2674 | db = self.db |
|
2671 | db = self.db | |
2675 | db['syscmdlist'] = syscmdlist |
|
2672 | db['syscmdlist'] = syscmdlist | |
2676 | finally: |
|
2673 | finally: | |
2677 | os.chdir(savedir) |
|
2674 | os.chdir(savedir) | |
2678 |
|
2675 | |||
2679 | @testdec.skip_doctest |
|
2676 | @testdec.skip_doctest | |
2680 | def magic_pwd(self, parameter_s = ''): |
|
2677 | def magic_pwd(self, parameter_s = ''): | |
2681 | """Return the current working directory path. |
|
2678 | """Return the current working directory path. | |
2682 |
|
2679 | |||
2683 | Examples |
|
2680 | Examples | |
2684 | -------- |
|
2681 | -------- | |
2685 | :: |
|
2682 | :: | |
2686 |
|
2683 | |||
2687 | In [9]: pwd |
|
2684 | In [9]: pwd | |
2688 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2685 | Out[9]: '/home/tsuser/sprint/ipython' | |
2689 | """ |
|
2686 | """ | |
2690 | return os.getcwd() |
|
2687 | return os.getcwd() | |
2691 |
|
2688 | |||
2692 | @testdec.skip_doctest |
|
2689 | @testdec.skip_doctest | |
2693 | def magic_cd(self, parameter_s=''): |
|
2690 | def magic_cd(self, parameter_s=''): | |
2694 | """Change the current working directory. |
|
2691 | """Change the current working directory. | |
2695 |
|
2692 | |||
2696 | This command automatically maintains an internal list of directories |
|
2693 | This command automatically maintains an internal list of directories | |
2697 | you visit during your IPython session, in the variable _dh. The |
|
2694 | you visit during your IPython session, in the variable _dh. The | |
2698 | command %dhist shows this history nicely formatted. You can also |
|
2695 | command %dhist shows this history nicely formatted. You can also | |
2699 | do 'cd -<tab>' to see directory history conveniently. |
|
2696 | do 'cd -<tab>' to see directory history conveniently. | |
2700 |
|
2697 | |||
2701 | Usage: |
|
2698 | Usage: | |
2702 |
|
2699 | |||
2703 | cd 'dir': changes to directory 'dir'. |
|
2700 | cd 'dir': changes to directory 'dir'. | |
2704 |
|
2701 | |||
2705 | cd -: changes to the last visited directory. |
|
2702 | cd -: changes to the last visited directory. | |
2706 |
|
2703 | |||
2707 | cd -<n>: changes to the n-th directory in the directory history. |
|
2704 | cd -<n>: changes to the n-th directory in the directory history. | |
2708 |
|
2705 | |||
2709 | cd --foo: change to directory that matches 'foo' in history |
|
2706 | cd --foo: change to directory that matches 'foo' in history | |
2710 |
|
2707 | |||
2711 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2708 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2712 | (note: cd <bookmark_name> is enough if there is no |
|
2709 | (note: cd <bookmark_name> is enough if there is no | |
2713 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2710 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2714 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2711 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2715 |
|
2712 | |||
2716 | Options: |
|
2713 | Options: | |
2717 |
|
2714 | |||
2718 | -q: quiet. Do not print the working directory after the cd command is |
|
2715 | -q: quiet. Do not print the working directory after the cd command is | |
2719 | executed. By default IPython's cd command does print this directory, |
|
2716 | executed. By default IPython's cd command does print this directory, | |
2720 | since the default prompts do not display path information. |
|
2717 | since the default prompts do not display path information. | |
2721 |
|
2718 | |||
2722 | Note that !cd doesn't work for this purpose because the shell where |
|
2719 | Note that !cd doesn't work for this purpose because the shell where | |
2723 | !command runs is immediately discarded after executing 'command'. |
|
2720 | !command runs is immediately discarded after executing 'command'. | |
2724 |
|
2721 | |||
2725 | Examples |
|
2722 | Examples | |
2726 | -------- |
|
2723 | -------- | |
2727 | :: |
|
2724 | :: | |
2728 |
|
2725 | |||
2729 | In [10]: cd parent/child |
|
2726 | In [10]: cd parent/child | |
2730 | /home/tsuser/parent/child |
|
2727 | /home/tsuser/parent/child | |
2731 | """ |
|
2728 | """ | |
2732 |
|
2729 | |||
2733 | parameter_s = parameter_s.strip() |
|
2730 | parameter_s = parameter_s.strip() | |
2734 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2731 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2735 |
|
2732 | |||
2736 | oldcwd = os.getcwd() |
|
2733 | oldcwd = os.getcwd() | |
2737 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2734 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2738 | # jump in directory history by number |
|
2735 | # jump in directory history by number | |
2739 | if numcd: |
|
2736 | if numcd: | |
2740 | nn = int(numcd.group(2)) |
|
2737 | nn = int(numcd.group(2)) | |
2741 | try: |
|
2738 | try: | |
2742 | ps = self.shell.user_ns['_dh'][nn] |
|
2739 | ps = self.shell.user_ns['_dh'][nn] | |
2743 | except IndexError: |
|
2740 | except IndexError: | |
2744 | print 'The requested directory does not exist in history.' |
|
2741 | print 'The requested directory does not exist in history.' | |
2745 | return |
|
2742 | return | |
2746 | else: |
|
2743 | else: | |
2747 | opts = {} |
|
2744 | opts = {} | |
2748 | elif parameter_s.startswith('--'): |
|
2745 | elif parameter_s.startswith('--'): | |
2749 | ps = None |
|
2746 | ps = None | |
2750 | fallback = None |
|
2747 | fallback = None | |
2751 | pat = parameter_s[2:] |
|
2748 | pat = parameter_s[2:] | |
2752 | dh = self.shell.user_ns['_dh'] |
|
2749 | dh = self.shell.user_ns['_dh'] | |
2753 | # first search only by basename (last component) |
|
2750 | # first search only by basename (last component) | |
2754 | for ent in reversed(dh): |
|
2751 | for ent in reversed(dh): | |
2755 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2752 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2756 | ps = ent |
|
2753 | ps = ent | |
2757 | break |
|
2754 | break | |
2758 |
|
2755 | |||
2759 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2756 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2760 | fallback = ent |
|
2757 | fallback = ent | |
2761 |
|
2758 | |||
2762 | # if we have no last part match, pick the first full path match |
|
2759 | # if we have no last part match, pick the first full path match | |
2763 | if ps is None: |
|
2760 | if ps is None: | |
2764 | ps = fallback |
|
2761 | ps = fallback | |
2765 |
|
2762 | |||
2766 | if ps is None: |
|
2763 | if ps is None: | |
2767 | print "No matching entry in directory history" |
|
2764 | print "No matching entry in directory history" | |
2768 | return |
|
2765 | return | |
2769 | else: |
|
2766 | else: | |
2770 | opts = {} |
|
2767 | opts = {} | |
2771 |
|
2768 | |||
2772 |
|
2769 | |||
2773 | else: |
|
2770 | else: | |
2774 | #turn all non-space-escaping backslashes to slashes, |
|
2771 | #turn all non-space-escaping backslashes to slashes, | |
2775 | # for c:\windows\directory\names\ |
|
2772 | # for c:\windows\directory\names\ | |
2776 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2773 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2777 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2774 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2778 | # jump to previous |
|
2775 | # jump to previous | |
2779 | if ps == '-': |
|
2776 | if ps == '-': | |
2780 | try: |
|
2777 | try: | |
2781 | ps = self.shell.user_ns['_dh'][-2] |
|
2778 | ps = self.shell.user_ns['_dh'][-2] | |
2782 | except IndexError: |
|
2779 | except IndexError: | |
2783 | raise UsageError('%cd -: No previous directory to change to.') |
|
2780 | raise UsageError('%cd -: No previous directory to change to.') | |
2784 | # jump to bookmark if needed |
|
2781 | # jump to bookmark if needed | |
2785 | else: |
|
2782 | else: | |
2786 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2783 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2787 | bkms = self.db.get('bookmarks', {}) |
|
2784 | bkms = self.db.get('bookmarks', {}) | |
2788 |
|
2785 | |||
2789 | if bkms.has_key(ps): |
|
2786 | if bkms.has_key(ps): | |
2790 | target = bkms[ps] |
|
2787 | target = bkms[ps] | |
2791 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2788 | print '(bookmark:%s) -> %s' % (ps,target) | |
2792 | ps = target |
|
2789 | ps = target | |
2793 | else: |
|
2790 | else: | |
2794 | if opts.has_key('b'): |
|
2791 | if opts.has_key('b'): | |
2795 | raise UsageError("Bookmark '%s' not found. " |
|
2792 | raise UsageError("Bookmark '%s' not found. " | |
2796 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2793 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2797 |
|
2794 | |||
2798 | # at this point ps should point to the target dir |
|
2795 | # at this point ps should point to the target dir | |
2799 | if ps: |
|
2796 | if ps: | |
2800 | try: |
|
2797 | try: | |
2801 | os.chdir(os.path.expanduser(ps)) |
|
2798 | os.chdir(os.path.expanduser(ps)) | |
2802 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2799 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2803 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2800 | set_term_title('IPython: ' + abbrev_cwd()) | |
2804 | except OSError: |
|
2801 | except OSError: | |
2805 | print sys.exc_info()[1] |
|
2802 | print sys.exc_info()[1] | |
2806 | else: |
|
2803 | else: | |
2807 | cwd = os.getcwd() |
|
2804 | cwd = os.getcwd() | |
2808 | dhist = self.shell.user_ns['_dh'] |
|
2805 | dhist = self.shell.user_ns['_dh'] | |
2809 | if oldcwd != cwd: |
|
2806 | if oldcwd != cwd: | |
2810 | dhist.append(cwd) |
|
2807 | dhist.append(cwd) | |
2811 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2808 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2812 |
|
2809 | |||
2813 | else: |
|
2810 | else: | |
2814 | os.chdir(self.shell.home_dir) |
|
2811 | os.chdir(self.shell.home_dir) | |
2815 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2812 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2816 | set_term_title('IPython: ' + '~') |
|
2813 | set_term_title('IPython: ' + '~') | |
2817 | cwd = os.getcwd() |
|
2814 | cwd = os.getcwd() | |
2818 | dhist = self.shell.user_ns['_dh'] |
|
2815 | dhist = self.shell.user_ns['_dh'] | |
2819 |
|
2816 | |||
2820 | if oldcwd != cwd: |
|
2817 | if oldcwd != cwd: | |
2821 | dhist.append(cwd) |
|
2818 | dhist.append(cwd) | |
2822 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2819 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2823 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2820 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2824 | print self.shell.user_ns['_dh'][-1] |
|
2821 | print self.shell.user_ns['_dh'][-1] | |
2825 |
|
2822 | |||
2826 |
|
2823 | |||
2827 | def magic_env(self, parameter_s=''): |
|
2824 | def magic_env(self, parameter_s=''): | |
2828 | """List environment variables.""" |
|
2825 | """List environment variables.""" | |
2829 |
|
2826 | |||
2830 | return os.environ.data |
|
2827 | return os.environ.data | |
2831 |
|
2828 | |||
2832 | def magic_pushd(self, parameter_s=''): |
|
2829 | def magic_pushd(self, parameter_s=''): | |
2833 | """Place the current dir on stack and change directory. |
|
2830 | """Place the current dir on stack and change directory. | |
2834 |
|
2831 | |||
2835 | Usage:\\ |
|
2832 | Usage:\\ | |
2836 | %pushd ['dirname'] |
|
2833 | %pushd ['dirname'] | |
2837 | """ |
|
2834 | """ | |
2838 |
|
2835 | |||
2839 | dir_s = self.shell.dir_stack |
|
2836 | dir_s = self.shell.dir_stack | |
2840 | tgt = os.path.expanduser(parameter_s) |
|
2837 | tgt = os.path.expanduser(parameter_s) | |
2841 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2838 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2842 | if tgt: |
|
2839 | if tgt: | |
2843 | self.magic_cd(parameter_s) |
|
2840 | self.magic_cd(parameter_s) | |
2844 | dir_s.insert(0,cwd) |
|
2841 | dir_s.insert(0,cwd) | |
2845 | return self.magic_dirs() |
|
2842 | return self.magic_dirs() | |
2846 |
|
2843 | |||
2847 | def magic_popd(self, parameter_s=''): |
|
2844 | def magic_popd(self, parameter_s=''): | |
2848 | """Change to directory popped off the top of the stack. |
|
2845 | """Change to directory popped off the top of the stack. | |
2849 | """ |
|
2846 | """ | |
2850 | if not self.shell.dir_stack: |
|
2847 | if not self.shell.dir_stack: | |
2851 | raise UsageError("%popd on empty stack") |
|
2848 | raise UsageError("%popd on empty stack") | |
2852 | top = self.shell.dir_stack.pop(0) |
|
2849 | top = self.shell.dir_stack.pop(0) | |
2853 | self.magic_cd(top) |
|
2850 | self.magic_cd(top) | |
2854 | print "popd ->",top |
|
2851 | print "popd ->",top | |
2855 |
|
2852 | |||
2856 | def magic_dirs(self, parameter_s=''): |
|
2853 | def magic_dirs(self, parameter_s=''): | |
2857 | """Return the current directory stack.""" |
|
2854 | """Return the current directory stack.""" | |
2858 |
|
2855 | |||
2859 | return self.shell.dir_stack |
|
2856 | return self.shell.dir_stack | |
2860 |
|
2857 | |||
2861 | def magic_dhist(self, parameter_s=''): |
|
2858 | def magic_dhist(self, parameter_s=''): | |
2862 | """Print your history of visited directories. |
|
2859 | """Print your history of visited directories. | |
2863 |
|
2860 | |||
2864 | %dhist -> print full history\\ |
|
2861 | %dhist -> print full history\\ | |
2865 | %dhist n -> print last n entries only\\ |
|
2862 | %dhist n -> print last n entries only\\ | |
2866 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2863 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2867 |
|
2864 | |||
2868 | This history is automatically maintained by the %cd command, and |
|
2865 | This history is automatically maintained by the %cd command, and | |
2869 | always available as the global list variable _dh. You can use %cd -<n> |
|
2866 | always available as the global list variable _dh. You can use %cd -<n> | |
2870 | to go to directory number <n>. |
|
2867 | to go to directory number <n>. | |
2871 |
|
2868 | |||
2872 | Note that most of time, you should view directory history by entering |
|
2869 | Note that most of time, you should view directory history by entering | |
2873 | cd -<TAB>. |
|
2870 | cd -<TAB>. | |
2874 |
|
2871 | |||
2875 | """ |
|
2872 | """ | |
2876 |
|
2873 | |||
2877 | dh = self.shell.user_ns['_dh'] |
|
2874 | dh = self.shell.user_ns['_dh'] | |
2878 | if parameter_s: |
|
2875 | if parameter_s: | |
2879 | try: |
|
2876 | try: | |
2880 | args = map(int,parameter_s.split()) |
|
2877 | args = map(int,parameter_s.split()) | |
2881 | except: |
|
2878 | except: | |
2882 | self.arg_err(Magic.magic_dhist) |
|
2879 | self.arg_err(Magic.magic_dhist) | |
2883 | return |
|
2880 | return | |
2884 | if len(args) == 1: |
|
2881 | if len(args) == 1: | |
2885 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2882 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2886 | elif len(args) == 2: |
|
2883 | elif len(args) == 2: | |
2887 | ini,fin = args |
|
2884 | ini,fin = args | |
2888 | else: |
|
2885 | else: | |
2889 | self.arg_err(Magic.magic_dhist) |
|
2886 | self.arg_err(Magic.magic_dhist) | |
2890 | return |
|
2887 | return | |
2891 | else: |
|
2888 | else: | |
2892 | ini,fin = 0,len(dh) |
|
2889 | ini,fin = 0,len(dh) | |
2893 | nlprint(dh, |
|
2890 | nlprint(dh, | |
2894 | header = 'Directory history (kept in _dh)', |
|
2891 | header = 'Directory history (kept in _dh)', | |
2895 | start=ini,stop=fin) |
|
2892 | start=ini,stop=fin) | |
2896 |
|
2893 | |||
2897 | @testdec.skip_doctest |
|
2894 | @testdec.skip_doctest | |
2898 | def magic_sc(self, parameter_s=''): |
|
2895 | def magic_sc(self, parameter_s=''): | |
2899 | """Shell capture - execute a shell command and capture its output. |
|
2896 | """Shell capture - execute a shell command and capture its output. | |
2900 |
|
2897 | |||
2901 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2898 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2902 |
|
2899 | |||
2903 | You should use the form 'var = !command' instead. Example: |
|
2900 | You should use the form 'var = !command' instead. Example: | |
2904 |
|
2901 | |||
2905 | "%sc -l myfiles = ls ~" should now be written as |
|
2902 | "%sc -l myfiles = ls ~" should now be written as | |
2906 |
|
2903 | |||
2907 | "myfiles = !ls ~" |
|
2904 | "myfiles = !ls ~" | |
2908 |
|
2905 | |||
2909 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2906 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2910 | below. |
|
2907 | below. | |
2911 |
|
2908 | |||
2912 | -- |
|
2909 | -- | |
2913 | %sc [options] varname=command |
|
2910 | %sc [options] varname=command | |
2914 |
|
2911 | |||
2915 | IPython will run the given command using commands.getoutput(), and |
|
2912 | IPython will run the given command using commands.getoutput(), and | |
2916 | will then update the user's interactive namespace with a variable |
|
2913 | will then update the user's interactive namespace with a variable | |
2917 | called varname, containing the value of the call. Your command can |
|
2914 | called varname, containing the value of the call. Your command can | |
2918 | contain shell wildcards, pipes, etc. |
|
2915 | contain shell wildcards, pipes, etc. | |
2919 |
|
2916 | |||
2920 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2917 | The '=' sign in the syntax is mandatory, and the variable name you | |
2921 | supply must follow Python's standard conventions for valid names. |
|
2918 | supply must follow Python's standard conventions for valid names. | |
2922 |
|
2919 | |||
2923 | (A special format without variable name exists for internal use) |
|
2920 | (A special format without variable name exists for internal use) | |
2924 |
|
2921 | |||
2925 | Options: |
|
2922 | Options: | |
2926 |
|
2923 | |||
2927 | -l: list output. Split the output on newlines into a list before |
|
2924 | -l: list output. Split the output on newlines into a list before | |
2928 | assigning it to the given variable. By default the output is stored |
|
2925 | assigning it to the given variable. By default the output is stored | |
2929 | as a single string. |
|
2926 | as a single string. | |
2930 |
|
2927 | |||
2931 | -v: verbose. Print the contents of the variable. |
|
2928 | -v: verbose. Print the contents of the variable. | |
2932 |
|
2929 | |||
2933 | In most cases you should not need to split as a list, because the |
|
2930 | In most cases you should not need to split as a list, because the | |
2934 | returned value is a special type of string which can automatically |
|
2931 | returned value is a special type of string which can automatically | |
2935 | provide its contents either as a list (split on newlines) or as a |
|
2932 | provide its contents either as a list (split on newlines) or as a | |
2936 | space-separated string. These are convenient, respectively, either |
|
2933 | space-separated string. These are convenient, respectively, either | |
2937 | for sequential processing or to be passed to a shell command. |
|
2934 | for sequential processing or to be passed to a shell command. | |
2938 |
|
2935 | |||
2939 | For example: |
|
2936 | For example: | |
2940 |
|
2937 | |||
2941 | # all-random |
|
2938 | # all-random | |
2942 |
|
2939 | |||
2943 | # Capture into variable a |
|
2940 | # Capture into variable a | |
2944 | In [1]: sc a=ls *py |
|
2941 | In [1]: sc a=ls *py | |
2945 |
|
2942 | |||
2946 | # a is a string with embedded newlines |
|
2943 | # a is a string with embedded newlines | |
2947 | In [2]: a |
|
2944 | In [2]: a | |
2948 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2945 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2949 |
|
2946 | |||
2950 | # which can be seen as a list: |
|
2947 | # which can be seen as a list: | |
2951 | In [3]: a.l |
|
2948 | In [3]: a.l | |
2952 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2949 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2953 |
|
2950 | |||
2954 | # or as a whitespace-separated string: |
|
2951 | # or as a whitespace-separated string: | |
2955 | In [4]: a.s |
|
2952 | In [4]: a.s | |
2956 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2953 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2957 |
|
2954 | |||
2958 | # a.s is useful to pass as a single command line: |
|
2955 | # a.s is useful to pass as a single command line: | |
2959 | In [5]: !wc -l $a.s |
|
2956 | In [5]: !wc -l $a.s | |
2960 | 146 setup.py |
|
2957 | 146 setup.py | |
2961 | 130 win32_manual_post_install.py |
|
2958 | 130 win32_manual_post_install.py | |
2962 | 276 total |
|
2959 | 276 total | |
2963 |
|
2960 | |||
2964 | # while the list form is useful to loop over: |
|
2961 | # while the list form is useful to loop over: | |
2965 | In [6]: for f in a.l: |
|
2962 | In [6]: for f in a.l: | |
2966 | ...: !wc -l $f |
|
2963 | ...: !wc -l $f | |
2967 | ...: |
|
2964 | ...: | |
2968 | 146 setup.py |
|
2965 | 146 setup.py | |
2969 | 130 win32_manual_post_install.py |
|
2966 | 130 win32_manual_post_install.py | |
2970 |
|
2967 | |||
2971 | Similiarly, the lists returned by the -l option are also special, in |
|
2968 | Similiarly, the lists returned by the -l option are also special, in | |
2972 | the sense that you can equally invoke the .s attribute on them to |
|
2969 | the sense that you can equally invoke the .s attribute on them to | |
2973 | automatically get a whitespace-separated string from their contents: |
|
2970 | automatically get a whitespace-separated string from their contents: | |
2974 |
|
2971 | |||
2975 | In [7]: sc -l b=ls *py |
|
2972 | In [7]: sc -l b=ls *py | |
2976 |
|
2973 | |||
2977 | In [8]: b |
|
2974 | In [8]: b | |
2978 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2975 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2979 |
|
2976 | |||
2980 | In [9]: b.s |
|
2977 | In [9]: b.s | |
2981 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2978 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2982 |
|
2979 | |||
2983 | In summary, both the lists and strings used for ouptut capture have |
|
2980 | In summary, both the lists and strings used for ouptut capture have | |
2984 | the following special attributes: |
|
2981 | the following special attributes: | |
2985 |
|
2982 | |||
2986 | .l (or .list) : value as list. |
|
2983 | .l (or .list) : value as list. | |
2987 | .n (or .nlstr): value as newline-separated string. |
|
2984 | .n (or .nlstr): value as newline-separated string. | |
2988 | .s (or .spstr): value as space-separated string. |
|
2985 | .s (or .spstr): value as space-separated string. | |
2989 | """ |
|
2986 | """ | |
2990 |
|
2987 | |||
2991 | opts,args = self.parse_options(parameter_s,'lv') |
|
2988 | opts,args = self.parse_options(parameter_s,'lv') | |
2992 | # Try to get a variable name and command to run |
|
2989 | # Try to get a variable name and command to run | |
2993 | try: |
|
2990 | try: | |
2994 | # the variable name must be obtained from the parse_options |
|
2991 | # the variable name must be obtained from the parse_options | |
2995 | # output, which uses shlex.split to strip options out. |
|
2992 | # output, which uses shlex.split to strip options out. | |
2996 | var,_ = args.split('=',1) |
|
2993 | var,_ = args.split('=',1) | |
2997 | var = var.strip() |
|
2994 | var = var.strip() | |
2998 | # But the the command has to be extracted from the original input |
|
2995 | # But the the command has to be extracted from the original input | |
2999 | # parameter_s, not on what parse_options returns, to avoid the |
|
2996 | # parameter_s, not on what parse_options returns, to avoid the | |
3000 | # quote stripping which shlex.split performs on it. |
|
2997 | # quote stripping which shlex.split performs on it. | |
3001 | _,cmd = parameter_s.split('=',1) |
|
2998 | _,cmd = parameter_s.split('=',1) | |
3002 | except ValueError: |
|
2999 | except ValueError: | |
3003 | var,cmd = '','' |
|
3000 | var,cmd = '','' | |
3004 | # If all looks ok, proceed |
|
3001 | # If all looks ok, proceed | |
3005 | split = 'l' in opts |
|
3002 | split = 'l' in opts | |
3006 | out = self.shell.getoutput(cmd, split=split) |
|
3003 | out = self.shell.getoutput(cmd, split=split) | |
3007 | if opts.has_key('v'): |
|
3004 | if opts.has_key('v'): | |
3008 | print '%s ==\n%s' % (var,pformat(out)) |
|
3005 | print '%s ==\n%s' % (var,pformat(out)) | |
3009 | if var: |
|
3006 | if var: | |
3010 | self.shell.user_ns.update({var:out}) |
|
3007 | self.shell.user_ns.update({var:out}) | |
3011 | else: |
|
3008 | else: | |
3012 | return out |
|
3009 | return out | |
3013 |
|
3010 | |||
3014 | def magic_sx(self, parameter_s=''): |
|
3011 | def magic_sx(self, parameter_s=''): | |
3015 | """Shell execute - run a shell command and capture its output. |
|
3012 | """Shell execute - run a shell command and capture its output. | |
3016 |
|
3013 | |||
3017 | %sx command |
|
3014 | %sx command | |
3018 |
|
3015 | |||
3019 | IPython will run the given command using commands.getoutput(), and |
|
3016 | IPython will run the given command using commands.getoutput(), and | |
3020 | return the result formatted as a list (split on '\\n'). Since the |
|
3017 | return the result formatted as a list (split on '\\n'). Since the | |
3021 | output is _returned_, it will be stored in ipython's regular output |
|
3018 | output is _returned_, it will be stored in ipython's regular output | |
3022 | cache Out[N] and in the '_N' automatic variables. |
|
3019 | cache Out[N] and in the '_N' automatic variables. | |
3023 |
|
3020 | |||
3024 | Notes: |
|
3021 | Notes: | |
3025 |
|
3022 | |||
3026 | 1) If an input line begins with '!!', then %sx is automatically |
|
3023 | 1) If an input line begins with '!!', then %sx is automatically | |
3027 | invoked. That is, while: |
|
3024 | invoked. That is, while: | |
3028 | !ls |
|
3025 | !ls | |
3029 | causes ipython to simply issue system('ls'), typing |
|
3026 | causes ipython to simply issue system('ls'), typing | |
3030 | !!ls |
|
3027 | !!ls | |
3031 | is a shorthand equivalent to: |
|
3028 | is a shorthand equivalent to: | |
3032 | %sx ls |
|
3029 | %sx ls | |
3033 |
|
3030 | |||
3034 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3031 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3035 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3032 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3036 | to process line-oriented shell output via further python commands. |
|
3033 | to process line-oriented shell output via further python commands. | |
3037 | %sc is meant to provide much finer control, but requires more |
|
3034 | %sc is meant to provide much finer control, but requires more | |
3038 | typing. |
|
3035 | typing. | |
3039 |
|
3036 | |||
3040 | 3) Just like %sc -l, this is a list with special attributes: |
|
3037 | 3) Just like %sc -l, this is a list with special attributes: | |
3041 |
|
3038 | |||
3042 | .l (or .list) : value as list. |
|
3039 | .l (or .list) : value as list. | |
3043 | .n (or .nlstr): value as newline-separated string. |
|
3040 | .n (or .nlstr): value as newline-separated string. | |
3044 | .s (or .spstr): value as whitespace-separated string. |
|
3041 | .s (or .spstr): value as whitespace-separated string. | |
3045 |
|
3042 | |||
3046 | This is very useful when trying to use such lists as arguments to |
|
3043 | This is very useful when trying to use such lists as arguments to | |
3047 | system commands.""" |
|
3044 | system commands.""" | |
3048 |
|
3045 | |||
3049 | if parameter_s: |
|
3046 | if parameter_s: | |
3050 | return self.shell.getoutput(parameter_s) |
|
3047 | return self.shell.getoutput(parameter_s) | |
3051 |
|
3048 | |||
3052 | def magic_r(self, parameter_s=''): |
|
3049 | def magic_r(self, parameter_s=''): | |
3053 | """Repeat previous input. |
|
3050 | """Repeat previous input. | |
3054 |
|
3051 | |||
3055 | Note: Consider using the more powerfull %rep instead! |
|
3052 | Note: Consider using the more powerfull %rep instead! | |
3056 |
|
3053 | |||
3057 | If given an argument, repeats the previous command which starts with |
|
3054 | If given an argument, repeats the previous command which starts with | |
3058 | the same string, otherwise it just repeats the previous input. |
|
3055 | the same string, otherwise it just repeats the previous input. | |
3059 |
|
3056 | |||
3060 | Shell escaped commands (with ! as first character) are not recognized |
|
3057 | Shell escaped commands (with ! as first character) are not recognized | |
3061 | by this system, only pure python code and magic commands. |
|
3058 | by this system, only pure python code and magic commands. | |
3062 | """ |
|
3059 | """ | |
3063 |
|
3060 | |||
3064 | start = parameter_s.strip() |
|
3061 | start = parameter_s.strip() | |
3065 | esc_magic = ESC_MAGIC |
|
3062 | esc_magic = ESC_MAGIC | |
3066 | # Identify magic commands even if automagic is on (which means |
|
3063 | # Identify magic commands even if automagic is on (which means | |
3067 | # the in-memory version is different from that typed by the user). |
|
3064 | # the in-memory version is different from that typed by the user). | |
3068 | if self.shell.automagic: |
|
3065 | if self.shell.automagic: | |
3069 | start_magic = esc_magic+start |
|
3066 | start_magic = esc_magic+start | |
3070 | else: |
|
3067 | else: | |
3071 | start_magic = start |
|
3068 | start_magic = start | |
3072 | # Look through the input history in reverse |
|
3069 | # Look through the input history in reverse | |
3073 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): |
|
3070 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): | |
3074 | input = self.shell.history_manager.input_hist_parsed[n] |
|
3071 | input = self.shell.history_manager.input_hist_parsed[n] | |
3075 | # skip plain 'r' lines so we don't recurse to infinity |
|
3072 | # skip plain 'r' lines so we don't recurse to infinity | |
3076 | if input != '_ip.magic("r")\n' and \ |
|
3073 | if input != '_ip.magic("r")\n' and \ | |
3077 | (input.startswith(start) or input.startswith(start_magic)): |
|
3074 | (input.startswith(start) or input.startswith(start_magic)): | |
3078 | #print 'match',`input` # dbg |
|
3075 | #print 'match',`input` # dbg | |
3079 | print 'Executing:',input, |
|
3076 | print 'Executing:',input, | |
3080 | self.shell.run_cell(input) |
|
3077 | self.shell.run_cell(input) | |
3081 | return |
|
3078 | return | |
3082 | print 'No previous input matching `%s` found.' % start |
|
3079 | print 'No previous input matching `%s` found.' % start | |
3083 |
|
3080 | |||
3084 |
|
3081 | |||
3085 | def magic_bookmark(self, parameter_s=''): |
|
3082 | def magic_bookmark(self, parameter_s=''): | |
3086 | """Manage IPython's bookmark system. |
|
3083 | """Manage IPython's bookmark system. | |
3087 |
|
3084 | |||
3088 | %bookmark <name> - set bookmark to current dir |
|
3085 | %bookmark <name> - set bookmark to current dir | |
3089 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3086 | %bookmark <name> <dir> - set bookmark to <dir> | |
3090 | %bookmark -l - list all bookmarks |
|
3087 | %bookmark -l - list all bookmarks | |
3091 | %bookmark -d <name> - remove bookmark |
|
3088 | %bookmark -d <name> - remove bookmark | |
3092 | %bookmark -r - remove all bookmarks |
|
3089 | %bookmark -r - remove all bookmarks | |
3093 |
|
3090 | |||
3094 | You can later on access a bookmarked folder with: |
|
3091 | You can later on access a bookmarked folder with: | |
3095 | %cd -b <name> |
|
3092 | %cd -b <name> | |
3096 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3093 | or simply '%cd <name>' if there is no directory called <name> AND | |
3097 | there is such a bookmark defined. |
|
3094 | there is such a bookmark defined. | |
3098 |
|
3095 | |||
3099 | Your bookmarks persist through IPython sessions, but they are |
|
3096 | Your bookmarks persist through IPython sessions, but they are | |
3100 | associated with each profile.""" |
|
3097 | associated with each profile.""" | |
3101 |
|
3098 | |||
3102 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3099 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3103 | if len(args) > 2: |
|
3100 | if len(args) > 2: | |
3104 | raise UsageError("%bookmark: too many arguments") |
|
3101 | raise UsageError("%bookmark: too many arguments") | |
3105 |
|
3102 | |||
3106 | bkms = self.db.get('bookmarks',{}) |
|
3103 | bkms = self.db.get('bookmarks',{}) | |
3107 |
|
3104 | |||
3108 | if opts.has_key('d'): |
|
3105 | if opts.has_key('d'): | |
3109 | try: |
|
3106 | try: | |
3110 | todel = args[0] |
|
3107 | todel = args[0] | |
3111 | except IndexError: |
|
3108 | except IndexError: | |
3112 | raise UsageError( |
|
3109 | raise UsageError( | |
3113 | "%bookmark -d: must provide a bookmark to delete") |
|
3110 | "%bookmark -d: must provide a bookmark to delete") | |
3114 | else: |
|
3111 | else: | |
3115 | try: |
|
3112 | try: | |
3116 | del bkms[todel] |
|
3113 | del bkms[todel] | |
3117 | except KeyError: |
|
3114 | except KeyError: | |
3118 | raise UsageError( |
|
3115 | raise UsageError( | |
3119 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3116 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3120 |
|
3117 | |||
3121 | elif opts.has_key('r'): |
|
3118 | elif opts.has_key('r'): | |
3122 | bkms = {} |
|
3119 | bkms = {} | |
3123 | elif opts.has_key('l'): |
|
3120 | elif opts.has_key('l'): | |
3124 | bks = bkms.keys() |
|
3121 | bks = bkms.keys() | |
3125 | bks.sort() |
|
3122 | bks.sort() | |
3126 | if bks: |
|
3123 | if bks: | |
3127 | size = max(map(len,bks)) |
|
3124 | size = max(map(len,bks)) | |
3128 | else: |
|
3125 | else: | |
3129 | size = 0 |
|
3126 | size = 0 | |
3130 | fmt = '%-'+str(size)+'s -> %s' |
|
3127 | fmt = '%-'+str(size)+'s -> %s' | |
3131 | print 'Current bookmarks:' |
|
3128 | print 'Current bookmarks:' | |
3132 | for bk in bks: |
|
3129 | for bk in bks: | |
3133 | print fmt % (bk,bkms[bk]) |
|
3130 | print fmt % (bk,bkms[bk]) | |
3134 | else: |
|
3131 | else: | |
3135 | if not args: |
|
3132 | if not args: | |
3136 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3133 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3137 | elif len(args)==1: |
|
3134 | elif len(args)==1: | |
3138 | bkms[args[0]] = os.getcwd() |
|
3135 | bkms[args[0]] = os.getcwd() | |
3139 | elif len(args)==2: |
|
3136 | elif len(args)==2: | |
3140 | bkms[args[0]] = args[1] |
|
3137 | bkms[args[0]] = args[1] | |
3141 | self.db['bookmarks'] = bkms |
|
3138 | self.db['bookmarks'] = bkms | |
3142 |
|
3139 | |||
3143 | def magic_pycat(self, parameter_s=''): |
|
3140 | def magic_pycat(self, parameter_s=''): | |
3144 | """Show a syntax-highlighted file through a pager. |
|
3141 | """Show a syntax-highlighted file through a pager. | |
3145 |
|
3142 | |||
3146 | This magic is similar to the cat utility, but it will assume the file |
|
3143 | This magic is similar to the cat utility, but it will assume the file | |
3147 | to be Python source and will show it with syntax highlighting. """ |
|
3144 | to be Python source and will show it with syntax highlighting. """ | |
3148 |
|
3145 | |||
3149 | try: |
|
3146 | try: | |
3150 | filename = get_py_filename(parameter_s) |
|
3147 | filename = get_py_filename(parameter_s) | |
3151 | cont = file_read(filename) |
|
3148 | cont = file_read(filename) | |
3152 | except IOError: |
|
3149 | except IOError: | |
3153 | try: |
|
3150 | try: | |
3154 | cont = eval(parameter_s,self.user_ns) |
|
3151 | cont = eval(parameter_s,self.user_ns) | |
3155 | except NameError: |
|
3152 | except NameError: | |
3156 | cont = None |
|
3153 | cont = None | |
3157 | if cont is None: |
|
3154 | if cont is None: | |
3158 | print "Error: no such file or variable" |
|
3155 | print "Error: no such file or variable" | |
3159 | return |
|
3156 | return | |
3160 |
|
3157 | |||
3161 | page.page(self.shell.pycolorize(cont)) |
|
3158 | page.page(self.shell.pycolorize(cont)) | |
3162 |
|
3159 | |||
3163 | def _rerun_pasted(self): |
|
3160 | def _rerun_pasted(self): | |
3164 | """ Rerun a previously pasted command. |
|
3161 | """ Rerun a previously pasted command. | |
3165 | """ |
|
3162 | """ | |
3166 | b = self.user_ns.get('pasted_block', None) |
|
3163 | b = self.user_ns.get('pasted_block', None) | |
3167 | if b is None: |
|
3164 | if b is None: | |
3168 | raise UsageError('No previous pasted block available') |
|
3165 | raise UsageError('No previous pasted block available') | |
3169 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3166 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3170 | exec b in self.user_ns |
|
3167 | exec b in self.user_ns | |
3171 |
|
3168 | |||
3172 | def _get_pasted_lines(self, sentinel): |
|
3169 | def _get_pasted_lines(self, sentinel): | |
3173 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3170 | """ Yield pasted lines until the user enters the given sentinel value. | |
3174 | """ |
|
3171 | """ | |
3175 | from IPython.core import interactiveshell |
|
3172 | from IPython.core import interactiveshell | |
3176 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3173 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3177 | while True: |
|
3174 | while True: | |
3178 | l = interactiveshell.raw_input_original(':') |
|
3175 | l = interactiveshell.raw_input_original(':') | |
3179 | if l == sentinel: |
|
3176 | if l == sentinel: | |
3180 | return |
|
3177 | return | |
3181 | else: |
|
3178 | else: | |
3182 | yield l |
|
3179 | yield l | |
3183 |
|
3180 | |||
3184 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3181 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3185 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3182 | """ Strip non-code parts of a sequence of lines to return a block of | |
3186 | code. |
|
3183 | code. | |
3187 | """ |
|
3184 | """ | |
3188 | # Regular expressions that declare text we strip from the input: |
|
3185 | # Regular expressions that declare text we strip from the input: | |
3189 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3186 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3190 | r'^\s*(\s?>)+', # Python input prompt |
|
3187 | r'^\s*(\s?>)+', # Python input prompt | |
3191 | r'^\s*\.{3,}', # Continuation prompts |
|
3188 | r'^\s*\.{3,}', # Continuation prompts | |
3192 | r'^\++', |
|
3189 | r'^\++', | |
3193 | ] |
|
3190 | ] | |
3194 |
|
3191 | |||
3195 | strip_from_start = map(re.compile,strip_re) |
|
3192 | strip_from_start = map(re.compile,strip_re) | |
3196 |
|
3193 | |||
3197 | lines = [] |
|
3194 | lines = [] | |
3198 | for l in raw_lines: |
|
3195 | for l in raw_lines: | |
3199 | for pat in strip_from_start: |
|
3196 | for pat in strip_from_start: | |
3200 | l = pat.sub('',l) |
|
3197 | l = pat.sub('',l) | |
3201 | lines.append(l) |
|
3198 | lines.append(l) | |
3202 |
|
3199 | |||
3203 | block = "\n".join(lines) + '\n' |
|
3200 | block = "\n".join(lines) + '\n' | |
3204 | #print "block:\n",block |
|
3201 | #print "block:\n",block | |
3205 | return block |
|
3202 | return block | |
3206 |
|
3203 | |||
3207 | def _execute_block(self, block, par): |
|
3204 | def _execute_block(self, block, par): | |
3208 | """ Execute a block, or store it in a variable, per the user's request. |
|
3205 | """ Execute a block, or store it in a variable, per the user's request. | |
3209 | """ |
|
3206 | """ | |
3210 | if not par: |
|
3207 | if not par: | |
3211 | b = textwrap.dedent(block) |
|
3208 | b = textwrap.dedent(block) | |
3212 | self.user_ns['pasted_block'] = b |
|
3209 | self.user_ns['pasted_block'] = b | |
3213 | exec b in self.user_ns |
|
3210 | exec b in self.user_ns | |
3214 | else: |
|
3211 | else: | |
3215 | self.user_ns[par] = SList(block.splitlines()) |
|
3212 | self.user_ns[par] = SList(block.splitlines()) | |
3216 | print "Block assigned to '%s'" % par |
|
3213 | print "Block assigned to '%s'" % par | |
3217 |
|
3214 | |||
3218 | def magic_quickref(self,arg): |
|
3215 | def magic_quickref(self,arg): | |
3219 | """ Show a quick reference sheet """ |
|
3216 | """ Show a quick reference sheet """ | |
3220 | import IPython.core.usage |
|
3217 | import IPython.core.usage | |
3221 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3218 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3222 |
|
3219 | |||
3223 | page.page(qr) |
|
3220 | page.page(qr) | |
3224 |
|
3221 | |||
3225 | def magic_doctest_mode(self,parameter_s=''): |
|
3222 | def magic_doctest_mode(self,parameter_s=''): | |
3226 | """Toggle doctest mode on and off. |
|
3223 | """Toggle doctest mode on and off. | |
3227 |
|
3224 | |||
3228 | This mode is intended to make IPython behave as much as possible like a |
|
3225 | This mode is intended to make IPython behave as much as possible like a | |
3229 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3226 | plain Python shell, from the perspective of how its prompts, exceptions | |
3230 | and output look. This makes it easy to copy and paste parts of a |
|
3227 | and output look. This makes it easy to copy and paste parts of a | |
3231 | session into doctests. It does so by: |
|
3228 | session into doctests. It does so by: | |
3232 |
|
3229 | |||
3233 | - Changing the prompts to the classic ``>>>`` ones. |
|
3230 | - Changing the prompts to the classic ``>>>`` ones. | |
3234 | - Changing the exception reporting mode to 'Plain'. |
|
3231 | - Changing the exception reporting mode to 'Plain'. | |
3235 | - Disabling pretty-printing of output. |
|
3232 | - Disabling pretty-printing of output. | |
3236 |
|
3233 | |||
3237 | Note that IPython also supports the pasting of code snippets that have |
|
3234 | Note that IPython also supports the pasting of code snippets that have | |
3238 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3235 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3239 | doctests from files or docstrings (even if they have leading |
|
3236 | doctests from files or docstrings (even if they have leading | |
3240 | whitespace), and the code will execute correctly. You can then use |
|
3237 | whitespace), and the code will execute correctly. You can then use | |
3241 | '%history -t' to see the translated history; this will give you the |
|
3238 | '%history -t' to see the translated history; this will give you the | |
3242 | input after removal of all the leading prompts and whitespace, which |
|
3239 | input after removal of all the leading prompts and whitespace, which | |
3243 | can be pasted back into an editor. |
|
3240 | can be pasted back into an editor. | |
3244 |
|
3241 | |||
3245 | With these features, you can switch into this mode easily whenever you |
|
3242 | With these features, you can switch into this mode easily whenever you | |
3246 | need to do testing and changes to doctests, without having to leave |
|
3243 | need to do testing and changes to doctests, without having to leave | |
3247 | your existing IPython session. |
|
3244 | your existing IPython session. | |
3248 | """ |
|
3245 | """ | |
3249 |
|
3246 | |||
3250 | from IPython.utils.ipstruct import Struct |
|
3247 | from IPython.utils.ipstruct import Struct | |
3251 |
|
3248 | |||
3252 | # Shorthands |
|
3249 | # Shorthands | |
3253 | shell = self.shell |
|
3250 | shell = self.shell | |
3254 | oc = shell.displayhook |
|
3251 | oc = shell.displayhook | |
3255 | meta = shell.meta |
|
3252 | meta = shell.meta | |
3256 | disp_formatter = self.shell.display_formatter |
|
3253 | disp_formatter = self.shell.display_formatter | |
3257 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3254 | ptformatter = disp_formatter.formatters['text/plain'] | |
3258 | # dstore is a data store kept in the instance metadata bag to track any |
|
3255 | # dstore is a data store kept in the instance metadata bag to track any | |
3259 | # changes we make, so we can undo them later. |
|
3256 | # changes we make, so we can undo them later. | |
3260 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3257 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3261 | save_dstore = dstore.setdefault |
|
3258 | save_dstore = dstore.setdefault | |
3262 |
|
3259 | |||
3263 | # save a few values we'll need to recover later |
|
3260 | # save a few values we'll need to recover later | |
3264 | mode = save_dstore('mode',False) |
|
3261 | mode = save_dstore('mode',False) | |
3265 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3262 | save_dstore('rc_pprint',ptformatter.pprint) | |
3266 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3263 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3267 | save_dstore('rc_separate_out',shell.separate_out) |
|
3264 | save_dstore('rc_separate_out',shell.separate_out) | |
3268 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3265 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3269 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3266 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3270 | save_dstore('rc_separate_in',shell.separate_in) |
|
3267 | save_dstore('rc_separate_in',shell.separate_in) | |
3271 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3268 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
3272 |
|
3269 | |||
3273 | if mode == False: |
|
3270 | if mode == False: | |
3274 | # turn on |
|
3271 | # turn on | |
3275 | oc.prompt1.p_template = '>>> ' |
|
3272 | oc.prompt1.p_template = '>>> ' | |
3276 | oc.prompt2.p_template = '... ' |
|
3273 | oc.prompt2.p_template = '... ' | |
3277 | oc.prompt_out.p_template = '' |
|
3274 | oc.prompt_out.p_template = '' | |
3278 |
|
3275 | |||
3279 | # Prompt separators like plain python |
|
3276 | # Prompt separators like plain python | |
3280 | oc.input_sep = oc.prompt1.sep = '' |
|
3277 | oc.input_sep = oc.prompt1.sep = '' | |
3281 | oc.output_sep = '' |
|
3278 | oc.output_sep = '' | |
3282 | oc.output_sep2 = '' |
|
3279 | oc.output_sep2 = '' | |
3283 |
|
3280 | |||
3284 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3281 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3285 | oc.prompt_out.pad_left = False |
|
3282 | oc.prompt_out.pad_left = False | |
3286 |
|
3283 | |||
3287 | ptformatter.pprint = False |
|
3284 | ptformatter.pprint = False | |
3288 | disp_formatter.plain_text_only = True |
|
3285 | disp_formatter.plain_text_only = True | |
3289 |
|
3286 | |||
3290 | shell.magic_xmode('Plain') |
|
3287 | shell.magic_xmode('Plain') | |
3291 | else: |
|
3288 | else: | |
3292 | # turn off |
|
3289 | # turn off | |
3293 | oc.prompt1.p_template = shell.prompt_in1 |
|
3290 | oc.prompt1.p_template = shell.prompt_in1 | |
3294 | oc.prompt2.p_template = shell.prompt_in2 |
|
3291 | oc.prompt2.p_template = shell.prompt_in2 | |
3295 | oc.prompt_out.p_template = shell.prompt_out |
|
3292 | oc.prompt_out.p_template = shell.prompt_out | |
3296 |
|
3293 | |||
3297 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3294 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3298 |
|
3295 | |||
3299 | oc.output_sep = dstore.rc_separate_out |
|
3296 | oc.output_sep = dstore.rc_separate_out | |
3300 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3297 | oc.output_sep2 = dstore.rc_separate_out2 | |
3301 |
|
3298 | |||
3302 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3299 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3303 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3300 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3304 |
|
3301 | |||
3305 | ptformatter.pprint = dstore.rc_pprint |
|
3302 | ptformatter.pprint = dstore.rc_pprint | |
3306 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3303 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
3307 |
|
3304 | |||
3308 | shell.magic_xmode(dstore.xmode) |
|
3305 | shell.magic_xmode(dstore.xmode) | |
3309 |
|
3306 | |||
3310 | # Store new mode and inform |
|
3307 | # Store new mode and inform | |
3311 | dstore.mode = bool(1-int(mode)) |
|
3308 | dstore.mode = bool(1-int(mode)) | |
3312 | mode_label = ['OFF','ON'][dstore.mode] |
|
3309 | mode_label = ['OFF','ON'][dstore.mode] | |
3313 | print 'Doctest mode is:', mode_label |
|
3310 | print 'Doctest mode is:', mode_label | |
3314 |
|
3311 | |||
3315 | def magic_gui(self, parameter_s=''): |
|
3312 | def magic_gui(self, parameter_s=''): | |
3316 | """Enable or disable IPython GUI event loop integration. |
|
3313 | """Enable or disable IPython GUI event loop integration. | |
3317 |
|
3314 | |||
3318 | %gui [GUINAME] |
|
3315 | %gui [GUINAME] | |
3319 |
|
3316 | |||
3320 | This magic replaces IPython's threaded shells that were activated |
|
3317 | This magic replaces IPython's threaded shells that were activated | |
3321 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3318 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3322 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3319 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3323 | interrupts should work without any problems. The following toolkits |
|
3320 | interrupts should work without any problems. The following toolkits | |
3324 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3321 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3325 |
|
3322 | |||
3326 | %gui wx # enable wxPython event loop integration |
|
3323 | %gui wx # enable wxPython event loop integration | |
3327 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3324 | %gui qt4|qt # enable PyQt4 event loop integration | |
3328 | %gui gtk # enable PyGTK event loop integration |
|
3325 | %gui gtk # enable PyGTK event loop integration | |
3329 | %gui tk # enable Tk event loop integration |
|
3326 | %gui tk # enable Tk event loop integration | |
3330 | %gui # disable all event loop integration |
|
3327 | %gui # disable all event loop integration | |
3331 |
|
3328 | |||
3332 | WARNING: after any of these has been called you can simply create |
|
3329 | WARNING: after any of these has been called you can simply create | |
3333 | an application object, but DO NOT start the event loop yourself, as |
|
3330 | an application object, but DO NOT start the event loop yourself, as | |
3334 | we have already handled that. |
|
3331 | we have already handled that. | |
3335 | """ |
|
3332 | """ | |
3336 | from IPython.lib.inputhook import enable_gui |
|
3333 | from IPython.lib.inputhook import enable_gui | |
3337 | opts, arg = self.parse_options(parameter_s, '') |
|
3334 | opts, arg = self.parse_options(parameter_s, '') | |
3338 | if arg=='': arg = None |
|
3335 | if arg=='': arg = None | |
3339 | return enable_gui(arg) |
|
3336 | return enable_gui(arg) | |
3340 |
|
3337 | |||
3341 | def magic_load_ext(self, module_str): |
|
3338 | def magic_load_ext(self, module_str): | |
3342 | """Load an IPython extension by its module name.""" |
|
3339 | """Load an IPython extension by its module name.""" | |
3343 | return self.extension_manager.load_extension(module_str) |
|
3340 | return self.extension_manager.load_extension(module_str) | |
3344 |
|
3341 | |||
3345 | def magic_unload_ext(self, module_str): |
|
3342 | def magic_unload_ext(self, module_str): | |
3346 | """Unload an IPython extension by its module name.""" |
|
3343 | """Unload an IPython extension by its module name.""" | |
3347 | self.extension_manager.unload_extension(module_str) |
|
3344 | self.extension_manager.unload_extension(module_str) | |
3348 |
|
3345 | |||
3349 | def magic_reload_ext(self, module_str): |
|
3346 | def magic_reload_ext(self, module_str): | |
3350 | """Reload an IPython extension by its module name.""" |
|
3347 | """Reload an IPython extension by its module name.""" | |
3351 | self.extension_manager.reload_extension(module_str) |
|
3348 | self.extension_manager.reload_extension(module_str) | |
3352 |
|
3349 | |||
3353 | @testdec.skip_doctest |
|
3350 | @testdec.skip_doctest | |
3354 | def magic_install_profiles(self, s): |
|
3351 | def magic_install_profiles(self, s): | |
3355 | """Install the default IPython profiles into the .ipython dir. |
|
3352 | """Install the default IPython profiles into the .ipython dir. | |
3356 |
|
3353 | |||
3357 | If the default profiles have already been installed, they will not |
|
3354 | If the default profiles have already been installed, they will not | |
3358 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3355 | be overwritten. You can force overwriting them by using the ``-o`` | |
3359 | option:: |
|
3356 | option:: | |
3360 |
|
3357 | |||
3361 | In [1]: %install_profiles -o |
|
3358 | In [1]: %install_profiles -o | |
3362 | """ |
|
3359 | """ | |
3363 | if '-o' in s: |
|
3360 | if '-o' in s: | |
3364 | overwrite = True |
|
3361 | overwrite = True | |
3365 | else: |
|
3362 | else: | |
3366 | overwrite = False |
|
3363 | overwrite = False | |
3367 | from IPython.config import profile |
|
3364 | from IPython.config import profile | |
3368 | profile_dir = os.path.split(profile.__file__)[0] |
|
3365 | profile_dir = os.path.split(profile.__file__)[0] | |
3369 | ipython_dir = self.ipython_dir |
|
3366 | ipython_dir = self.ipython_dir | |
3370 | files = os.listdir(profile_dir) |
|
3367 | files = os.listdir(profile_dir) | |
3371 |
|
3368 | |||
3372 | to_install = [] |
|
3369 | to_install = [] | |
3373 | for f in files: |
|
3370 | for f in files: | |
3374 | if f.startswith('ipython_config'): |
|
3371 | if f.startswith('ipython_config'): | |
3375 | src = os.path.join(profile_dir, f) |
|
3372 | src = os.path.join(profile_dir, f) | |
3376 | dst = os.path.join(ipython_dir, f) |
|
3373 | dst = os.path.join(ipython_dir, f) | |
3377 | if (not os.path.isfile(dst)) or overwrite: |
|
3374 | if (not os.path.isfile(dst)) or overwrite: | |
3378 | to_install.append((f, src, dst)) |
|
3375 | to_install.append((f, src, dst)) | |
3379 | if len(to_install)>0: |
|
3376 | if len(to_install)>0: | |
3380 | print "Installing profiles to: ", ipython_dir |
|
3377 | print "Installing profiles to: ", ipython_dir | |
3381 | for (f, src, dst) in to_install: |
|
3378 | for (f, src, dst) in to_install: | |
3382 | shutil.copy(src, dst) |
|
3379 | shutil.copy(src, dst) | |
3383 | print " %s" % f |
|
3380 | print " %s" % f | |
3384 |
|
3381 | |||
3385 | def magic_install_default_config(self, s): |
|
3382 | def magic_install_default_config(self, s): | |
3386 | """Install IPython's default config file into the .ipython dir. |
|
3383 | """Install IPython's default config file into the .ipython dir. | |
3387 |
|
3384 | |||
3388 | If the default config file (:file:`ipython_config.py`) is already |
|
3385 | If the default config file (:file:`ipython_config.py`) is already | |
3389 | installed, it will not be overwritten. You can force overwriting |
|
3386 | installed, it will not be overwritten. You can force overwriting | |
3390 | by using the ``-o`` option:: |
|
3387 | by using the ``-o`` option:: | |
3391 |
|
3388 | |||
3392 | In [1]: %install_default_config |
|
3389 | In [1]: %install_default_config | |
3393 | """ |
|
3390 | """ | |
3394 | if '-o' in s: |
|
3391 | if '-o' in s: | |
3395 | overwrite = True |
|
3392 | overwrite = True | |
3396 | else: |
|
3393 | else: | |
3397 | overwrite = False |
|
3394 | overwrite = False | |
3398 | from IPython.config import default |
|
3395 | from IPython.config import default | |
3399 | config_dir = os.path.split(default.__file__)[0] |
|
3396 | config_dir = os.path.split(default.__file__)[0] | |
3400 | ipython_dir = self.ipython_dir |
|
3397 | ipython_dir = self.ipython_dir | |
3401 | default_config_file_name = 'ipython_config.py' |
|
3398 | default_config_file_name = 'ipython_config.py' | |
3402 | src = os.path.join(config_dir, default_config_file_name) |
|
3399 | src = os.path.join(config_dir, default_config_file_name) | |
3403 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3400 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3404 | if (not os.path.isfile(dst)) or overwrite: |
|
3401 | if (not os.path.isfile(dst)) or overwrite: | |
3405 | shutil.copy(src, dst) |
|
3402 | shutil.copy(src, dst) | |
3406 | print "Installing default config file: %s" % dst |
|
3403 | print "Installing default config file: %s" % dst | |
3407 |
|
3404 | |||
3408 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3405 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3409 | # handling and modify slightly %run |
|
3406 | # handling and modify slightly %run | |
3410 |
|
3407 | |||
3411 | @testdec.skip_doctest |
|
3408 | @testdec.skip_doctest | |
3412 | def _pylab_magic_run(self, parameter_s=''): |
|
3409 | def _pylab_magic_run(self, parameter_s=''): | |
3413 | Magic.magic_run(self, parameter_s, |
|
3410 | Magic.magic_run(self, parameter_s, | |
3414 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3411 | runner=mpl_runner(self.shell.safe_execfile)) | |
3415 |
|
3412 | |||
3416 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3413 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3417 |
|
3414 | |||
3418 | @testdec.skip_doctest |
|
3415 | @testdec.skip_doctest | |
3419 | def magic_pylab(self, s): |
|
3416 | def magic_pylab(self, s): | |
3420 | """Load numpy and matplotlib to work interactively. |
|
3417 | """Load numpy and matplotlib to work interactively. | |
3421 |
|
3418 | |||
3422 | %pylab [GUINAME] |
|
3419 | %pylab [GUINAME] | |
3423 |
|
3420 | |||
3424 | This function lets you activate pylab (matplotlib, numpy and |
|
3421 | This function lets you activate pylab (matplotlib, numpy and | |
3425 | interactive support) at any point during an IPython session. |
|
3422 | interactive support) at any point during an IPython session. | |
3426 |
|
3423 | |||
3427 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3424 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3428 | pylab and mlab, as well as all names from numpy and pylab. |
|
3425 | pylab and mlab, as well as all names from numpy and pylab. | |
3429 |
|
3426 | |||
3430 | Parameters |
|
3427 | Parameters | |
3431 | ---------- |
|
3428 | ---------- | |
3432 | guiname : optional |
|
3429 | guiname : optional | |
3433 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3430 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3434 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3431 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3435 | otherwise matplotlib's default (which you can override in your |
|
3432 | otherwise matplotlib's default (which you can override in your | |
3436 | matplotlib config file) is used. |
|
3433 | matplotlib config file) is used. | |
3437 |
|
3434 | |||
3438 | Examples |
|
3435 | Examples | |
3439 | -------- |
|
3436 | -------- | |
3440 | In this case, where the MPL default is TkAgg: |
|
3437 | In this case, where the MPL default is TkAgg: | |
3441 | In [2]: %pylab |
|
3438 | In [2]: %pylab | |
3442 |
|
3439 | |||
3443 | Welcome to pylab, a matplotlib-based Python environment. |
|
3440 | Welcome to pylab, a matplotlib-based Python environment. | |
3444 | Backend in use: TkAgg |
|
3441 | Backend in use: TkAgg | |
3445 | For more information, type 'help(pylab)'. |
|
3442 | For more information, type 'help(pylab)'. | |
3446 |
|
3443 | |||
3447 | But you can explicitly request a different backend: |
|
3444 | But you can explicitly request a different backend: | |
3448 | In [3]: %pylab qt |
|
3445 | In [3]: %pylab qt | |
3449 |
|
3446 | |||
3450 | Welcome to pylab, a matplotlib-based Python environment. |
|
3447 | Welcome to pylab, a matplotlib-based Python environment. | |
3451 | Backend in use: Qt4Agg |
|
3448 | Backend in use: Qt4Agg | |
3452 | For more information, type 'help(pylab)'. |
|
3449 | For more information, type 'help(pylab)'. | |
3453 | """ |
|
3450 | """ | |
3454 | self.shell.enable_pylab(s) |
|
3451 | self.shell.enable_pylab(s) | |
3455 |
|
3452 | |||
3456 | def magic_tb(self, s): |
|
3453 | def magic_tb(self, s): | |
3457 | """Print the last traceback with the currently active exception mode. |
|
3454 | """Print the last traceback with the currently active exception mode. | |
3458 |
|
3455 | |||
3459 | See %xmode for changing exception reporting modes.""" |
|
3456 | See %xmode for changing exception reporting modes.""" | |
3460 | self.shell.showtraceback() |
|
3457 | self.shell.showtraceback() | |
3461 |
|
3458 | |||
3462 | @testdec.skip_doctest |
|
3459 | @testdec.skip_doctest | |
3463 | def magic_precision(self, s=''): |
|
3460 | def magic_precision(self, s=''): | |
3464 | """Set floating point precision for pretty printing. |
|
3461 | """Set floating point precision for pretty printing. | |
3465 |
|
3462 | |||
3466 | Can set either integer precision or a format string. |
|
3463 | Can set either integer precision or a format string. | |
3467 |
|
3464 | |||
3468 | If numpy has been imported and precision is an int, |
|
3465 | If numpy has been imported and precision is an int, | |
3469 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3466 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
3470 |
|
3467 | |||
3471 | If no argument is given, defaults will be restored. |
|
3468 | If no argument is given, defaults will be restored. | |
3472 |
|
3469 | |||
3473 | Examples |
|
3470 | Examples | |
3474 | -------- |
|
3471 | -------- | |
3475 | :: |
|
3472 | :: | |
3476 |
|
3473 | |||
3477 | In [1]: from math import pi |
|
3474 | In [1]: from math import pi | |
3478 |
|
3475 | |||
3479 | In [2]: %precision 3 |
|
3476 | In [2]: %precision 3 | |
3480 | Out[2]: '%.3f' |
|
3477 | Out[2]: '%.3f' | |
3481 |
|
3478 | |||
3482 | In [3]: pi |
|
3479 | In [3]: pi | |
3483 | Out[3]: 3.142 |
|
3480 | Out[3]: 3.142 | |
3484 |
|
3481 | |||
3485 | In [4]: %precision %i |
|
3482 | In [4]: %precision %i | |
3486 | Out[4]: '%i' |
|
3483 | Out[4]: '%i' | |
3487 |
|
3484 | |||
3488 | In [5]: pi |
|
3485 | In [5]: pi | |
3489 | Out[5]: 3 |
|
3486 | Out[5]: 3 | |
3490 |
|
3487 | |||
3491 | In [6]: %precision %e |
|
3488 | In [6]: %precision %e | |
3492 | Out[6]: '%e' |
|
3489 | Out[6]: '%e' | |
3493 |
|
3490 | |||
3494 | In [7]: pi**10 |
|
3491 | In [7]: pi**10 | |
3495 | Out[7]: 9.364805e+04 |
|
3492 | Out[7]: 9.364805e+04 | |
3496 |
|
3493 | |||
3497 | In [8]: %precision |
|
3494 | In [8]: %precision | |
3498 | Out[8]: '%r' |
|
3495 | Out[8]: '%r' | |
3499 |
|
3496 | |||
3500 | In [9]: pi**10 |
|
3497 | In [9]: pi**10 | |
3501 | Out[9]: 93648.047476082982 |
|
3498 | Out[9]: 93648.047476082982 | |
3502 |
|
3499 | |||
3503 | """ |
|
3500 | """ | |
3504 |
|
3501 | |||
3505 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3502 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
3506 | ptformatter.float_precision = s |
|
3503 | ptformatter.float_precision = s | |
3507 | return ptformatter.float_format |
|
3504 | return ptformatter.float_format | |
3508 |
|
3505 | |||
3509 | # end Magic |
|
3506 | # end Magic |
General Comments 0
You need to be logged in to leave comments.
Login now