##// END OF EJS Templates
Merge branch 'magic-examples'
Thomas Kluyver -
r3342:9cf75bcb merge
parent child Browse files
Show More
@@ -1,578 +1,589 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.utils.pickleshare import PickleShareDB
28 from IPython.utils.pickleshare import PickleShareDB
28 from IPython.utils.io import ask_yes_no
29 from IPython.utils.io import ask_yes_no
29 from IPython.utils.warn import warn
30 from IPython.utils.warn import warn
30
31
31 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
32 # Classes and functions
33 # Classes and functions
33 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
34
35
35 class HistoryManager(object):
36 class HistoryManager(object):
36 """A class to organize all history-related functionality in one place.
37 """A class to organize all history-related functionality in one place.
37 """
38 """
38 # Public interface
39 # Public interface
39
40
40 # An instance of the IPython shell we are attached to
41 # An instance of the IPython shell we are attached to
41 shell = None
42 shell = None
42 # A list to hold processed history
43 # A list to hold processed history
43 input_hist_parsed = None
44 input_hist_parsed = None
44 # A list to hold raw history (as typed by user)
45 # A list to hold raw history (as typed by user)
45 input_hist_raw = None
46 input_hist_raw = None
46 # A list of directories visited during session
47 # A list of directories visited during session
47 dir_hist = None
48 dir_hist = None
48 # 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
49 output_hist = None
50 output_hist = None
50 # String with path to the history file
51 # String with path to the history file
51 hist_file = None
52 hist_file = None
52 # PickleShareDB instance holding the raw data for the shadow history
53 # PickleShareDB instance holding the raw data for the shadow history
53 shadow_db = None
54 shadow_db = None
54 # ShadowHist instance with the actual shadow history
55 # ShadowHist instance with the actual shadow history
55 shadow_hist = None
56 shadow_hist = None
56
57
57 # Private interface
58 # Private interface
58 # 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
59 # 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
60 # necessary.
61 # necessary.
61 _i00, _i, _ii, _iii = '','','',''
62 _i00, _i, _ii, _iii = '','','',''
62
63
63 # 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
64 # 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
65 # call).
66 # call).
66 _exit_commands = None
67 _exit_commands = None
67
68
68 def __init__(self, shell):
69 def __init__(self, shell):
69 """Create a new history manager associated with a shell instance.
70 """Create a new history manager associated with a shell instance.
70 """
71 """
71 # We need a pointer back to the shell for various tasks.
72 # We need a pointer back to the shell for various tasks.
72 self.shell = shell
73 self.shell = shell
73
74
74 # List of input with multi-line handling.
75 # List of input with multi-line handling.
75 self.input_hist_parsed = []
76 self.input_hist_parsed = []
76 # This one will hold the 'raw' input history, without any
77 # This one will hold the 'raw' input history, without any
77 # pre-processing. This will allow users to retrieve the input just as
78 # pre-processing. This will allow users to retrieve the input just as
78 # it was exactly typed in by the user, with %hist -r.
79 # it was exactly typed in by the user, with %hist -r.
79 self.input_hist_raw = []
80 self.input_hist_raw = []
80
81
81 # list of visited directories
82 # list of visited directories
82 try:
83 try:
83 self.dir_hist = [os.getcwd()]
84 self.dir_hist = [os.getcwd()]
84 except OSError:
85 except OSError:
85 self.dir_hist = []
86 self.dir_hist = []
86
87
87 # dict of output history
88 # dict of output history
88 self.output_hist = {}
89 self.output_hist = {}
89
90
90 # Now the history file
91 # Now the history file
91 if shell.profile:
92 if shell.profile:
92 histfname = 'history-%s' % shell.profile
93 histfname = 'history-%s' % shell.profile
93 else:
94 else:
94 histfname = 'history'
95 histfname = 'history'
95 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json')
96 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json')
96
97
97 # Objects related to shadow history management
98 # Objects related to shadow history management
98 self._init_shadow_hist()
99 self._init_shadow_hist()
99
100
100 self._i00, self._i, self._ii, self._iii = '','','',''
101 self._i00, self._i, self._ii, self._iii = '','','',''
101
102
102 self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit',
103 self._exit_commands = set(['Quit', 'quit', 'Exit', 'exit', '%Quit',
103 '%quit', '%Exit', '%exit'])
104 '%quit', '%Exit', '%exit'])
104
105
105 # Object is fully initialized, we can now call methods on it.
106 # Object is fully initialized, we can now call methods on it.
106
107
107 # Fill the history zero entry, user counter starts at 1
108 # Fill the history zero entry, user counter starts at 1
108 self.store_inputs('\n', '\n')
109 self.store_inputs('\n', '\n')
109
110
110 # Create and start the autosaver.
111 # Create and start the autosaver.
111 self.autosave_flag = threading.Event()
112 self.autosave_flag = threading.Event()
112 self.autosave_timer = HistorySaveThread(self.autosave_flag, 60)
113 self.autosave_timer = HistorySaveThread(self.autosave_flag, 60)
113 self.autosave_timer.start()
114 self.autosave_timer.start()
114 # Register the autosave handler to be triggered as a post execute
115 # Register the autosave handler to be triggered as a post execute
115 # callback.
116 # callback.
116 self.shell.register_post_execute(self.autosave_if_due)
117 self.shell.register_post_execute(self.autosave_if_due)
117
118
118 def _init_shadow_hist(self):
119 def _init_shadow_hist(self):
119 try:
120 try:
120 self.shadow_db = PickleShareDB(os.path.join(
121 self.shadow_db = PickleShareDB(os.path.join(
121 self.shell.ipython_dir, 'db'))
122 self.shell.ipython_dir, 'db'))
122 except UnicodeDecodeError:
123 except UnicodeDecodeError:
123 print("Your ipython_dir can't be decoded to unicode!")
124 print("Your ipython_dir can't be decoded to unicode!")
124 print("Please set HOME environment variable to something that")
125 print("Please set HOME environment variable to something that")
125 print(r"only has ASCII characters, e.g. c:\home")
126 print(r"only has ASCII characters, e.g. c:\home")
126 print("Now it is", self.ipython_dir)
127 print("Now it is", self.ipython_dir)
127 sys.exit()
128 sys.exit()
128 self.shadow_hist = ShadowHist(self.shadow_db, self.shell)
129 self.shadow_hist = ShadowHist(self.shadow_db, self.shell)
129
130
130 def populate_readline_history(self):
131 def populate_readline_history(self):
131 """Populate the readline history from the raw history.
132 """Populate the readline history from the raw history.
132
133
133 We only store one copy of the raw history, which is persisted to a json
134 We only store one copy of the raw history, which is persisted to a json
134 file on disk. The readline history is repopulated from the contents of
135 file on disk. The readline history is repopulated from the contents of
135 this file."""
136 this file."""
136
137
137 try:
138 try:
138 self.shell.readline.clear_history()
139 self.shell.readline.clear_history()
139 except AttributeError:
140 except AttributeError:
140 pass
141 pass
141 else:
142 else:
142 for h in self.input_hist_raw:
143 for h in self.input_hist_raw:
143 if not h.isspace():
144 if not h.isspace():
144 for line in h.splitlines():
145 for line in h.splitlines():
145 self.shell.readline.add_history(line)
146 self.shell.readline.add_history(line)
146
147
147 def save_history(self):
148 def save_history(self):
148 """Save input history to a file (via readline library)."""
149 """Save input history to a file (via readline library)."""
149 hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:],
150 hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:],
150 parsed=self.input_hist_parsed) #[-self.shell.history_length:])
151 parsed=self.input_hist_parsed) #[-self.shell.history_length:])
151 with open(self.hist_file,'wt') as hfile:
152 with open(self.hist_file,'wt') as hfile:
152 json.dump(hist, hfile,
153 json.dump(hist, hfile,
153 sort_keys=True, indent=4)
154 sort_keys=True, indent=4)
154
155
155 def autosave_if_due(self):
156 def autosave_if_due(self):
156 """Check if the autosave event is set; if so, save history. We do it
157 """Check if the autosave event is set; if so, save history. We do it
157 this way so that the save takes place in the main thread."""
158 this way so that the save takes place in the main thread."""
158 if self.autosave_flag.is_set():
159 if self.autosave_flag.is_set():
159 self.save_history()
160 self.save_history()
160 self.autosave_flag.clear()
161 self.autosave_flag.clear()
161
162
162 def reload_history(self):
163 def reload_history(self):
163 """Reload the input history from disk file."""
164 """Reload the input history from disk file."""
164
165
165 with open(self.hist_file,'rt') as hfile:
166 with open(self.hist_file,'rt') as hfile:
166 try:
167 try:
167 hist = json.load(hfile)
168 hist = json.load(hfile)
168 except ValueError: # Ignore it if JSON is corrupt.
169 except ValueError: # Ignore it if JSON is corrupt.
169 return
170 return
170 self.input_hist_parsed = hist['parsed']
171 self.input_hist_parsed = hist['parsed']
171 self.input_hist_raw = hist['raw']
172 self.input_hist_raw = hist['raw']
172 if self.shell.has_readline:
173 if self.shell.has_readline:
173 self.populate_readline_history()
174 self.populate_readline_history()
174
175
175 def get_history(self, index=None, raw=False, output=True):
176 def get_history(self, index=None, raw=False, output=True):
176 """Get the history list.
177 """Get the history list.
177
178
178 Get the input and output history.
179 Get the input and output history.
179
180
180 Parameters
181 Parameters
181 ----------
182 ----------
182 index : n or (n1, n2) or None
183 index : n or (n1, n2) or None
183 If n, then the last entries. If a tuple, then all in
184 If n, then the last entries. If a tuple, then all in
184 range(n1, n2). If None, then all entries. Raises IndexError if
185 range(n1, n2). If None, then all entries. Raises IndexError if
185 the format of index is incorrect.
186 the format of index is incorrect.
186 raw : bool
187 raw : bool
187 If True, return the raw input.
188 If True, return the raw input.
188 output : bool
189 output : bool
189 If True, then return the output as well.
190 If True, then return the output as well.
190
191
191 Returns
192 Returns
192 -------
193 -------
193 If output is True, then return a dict of tuples, keyed by the prompt
194 If output is True, then return a dict of tuples, keyed by the prompt
194 numbers and with values of (input, output). If output is False, then
195 numbers and with values of (input, output). If output is False, then
195 a dict, keyed by the prompt number with the values of input. Raises
196 a dict, keyed by the prompt number with the values of input. Raises
196 IndexError if no history is found.
197 IndexError if no history is found.
197 """
198 """
198 if raw:
199 if raw:
199 input_hist = self.input_hist_raw
200 input_hist = self.input_hist_raw
200 else:
201 else:
201 input_hist = self.input_hist_parsed
202 input_hist = self.input_hist_parsed
202 if output:
203 if output:
203 output_hist = self.output_hist
204 output_hist = self.output_hist
204 n = len(input_hist)
205 n = len(input_hist)
205 if index is None:
206 if index is None:
206 start=0; stop=n
207 start=0; stop=n
207 elif isinstance(index, int):
208 elif isinstance(index, int):
208 start=n-index; stop=n
209 start=n-index; stop=n
209 elif isinstance(index, tuple) and len(index) == 2:
210 elif isinstance(index, tuple) and len(index) == 2:
210 start=index[0]; stop=index[1]
211 start=index[0]; stop=index[1]
211 else:
212 else:
212 raise IndexError('Not a valid index for the input history: %r'
213 raise IndexError('Not a valid index for the input history: %r'
213 % index)
214 % index)
214 hist = {}
215 hist = {}
215 for i in range(start, stop):
216 for i in range(start, stop):
216 if output:
217 if output:
217 hist[i] = (input_hist[i], output_hist.get(i))
218 hist[i] = (input_hist[i], output_hist.get(i))
218 else:
219 else:
219 hist[i] = input_hist[i]
220 hist[i] = input_hist[i]
220 if not hist:
221 if not hist:
221 raise IndexError('No history for range of indices: %r' % index)
222 raise IndexError('No history for range of indices: %r' % index)
222 return hist
223 return hist
223
224
224 def store_inputs(self, source, source_raw=None):
225 def store_inputs(self, source, source_raw=None):
225 """Store source and raw input in history and create input cache
226 """Store source and raw input in history and create input cache
226 variables _i*.
227 variables _i*.
227
228
228 Parameters
229 Parameters
229 ----------
230 ----------
230 source : str
231 source : str
231 Python input.
232 Python input.
232
233
233 source_raw : str, optional
234 source_raw : str, optional
234 If given, this is the raw input without any IPython transformations
235 If given, this is the raw input without any IPython transformations
235 applied to it. If not given, ``source`` is used.
236 applied to it. If not given, ``source`` is used.
236 """
237 """
237 if source_raw is None:
238 if source_raw is None:
238 source_raw = source
239 source_raw = source
239
240
240 # do not store exit/quit commands
241 # do not store exit/quit commands
241 if source_raw.strip() in self._exit_commands:
242 if source_raw.strip() in self._exit_commands:
242 return
243 return
243
244
244 self.input_hist_parsed.append(source.rstrip())
245 self.input_hist_parsed.append(source.rstrip())
245 self.input_hist_raw.append(source_raw.rstrip())
246 self.input_hist_raw.append(source_raw.rstrip())
246 self.shadow_hist.add(source)
247 self.shadow_hist.add(source)
247
248
248 # update the auto _i variables
249 # update the auto _i variables
249 self._iii = self._ii
250 self._iii = self._ii
250 self._ii = self._i
251 self._ii = self._i
251 self._i = self._i00
252 self._i = self._i00
252 self._i00 = source_raw
253 self._i00 = source_raw
253
254
254 # hackish access to user namespace to create _i1,_i2... dynamically
255 # hackish access to user namespace to create _i1,_i2... dynamically
255 new_i = '_i%s' % self.shell.execution_count
256 new_i = '_i%s' % self.shell.execution_count
256 to_main = {'_i': self._i,
257 to_main = {'_i': self._i,
257 '_ii': self._ii,
258 '_ii': self._ii,
258 '_iii': self._iii,
259 '_iii': self._iii,
259 new_i : self._i00 }
260 new_i : self._i00 }
260 self.shell.user_ns.update(to_main)
261 self.shell.user_ns.update(to_main)
261
262
262 def sync_inputs(self):
263 def sync_inputs(self):
263 """Ensure raw and translated histories have same length."""
264 """Ensure raw and translated histories have same length."""
264 if len(self.input_hist_parsed) != len (self.input_hist_raw):
265 if len(self.input_hist_parsed) != len (self.input_hist_raw):
265 self.input_hist_raw[:] = self.input_hist_parsed
266 self.input_hist_raw[:] = self.input_hist_parsed
266
267
267 def reset(self):
268 def reset(self):
268 """Clear all histories managed by this object."""
269 """Clear all histories managed by this object."""
269 self.input_hist_parsed[:] = []
270 self.input_hist_parsed[:] = []
270 self.input_hist_raw[:] = []
271 self.input_hist_raw[:] = []
271 self.output_hist.clear()
272 self.output_hist.clear()
272 # The directory history can't be completely empty
273 # The directory history can't be completely empty
273 self.dir_hist[:] = [os.getcwd()]
274 self.dir_hist[:] = [os.getcwd()]
274
275
275 class HistorySaveThread(threading.Thread):
276 class HistorySaveThread(threading.Thread):
276 """This thread makes IPython save history periodically.
277 """This thread makes IPython save history periodically.
277
278
278 Without this class, IPython would only save the history on a clean exit.
279 Without this class, IPython would only save the history on a clean exit.
279 This saves the history periodically (the current default is once per
280 This saves the history periodically (the current default is once per
280 minute), so that it is not lost in the event of a crash.
281 minute), so that it is not lost in the event of a crash.
281
282
282 The implementation sets an event to indicate that history should be saved.
283 The implementation sets an event to indicate that history should be saved.
283 The actual save is carried out after executing a user command, to avoid
284 The actual save is carried out after executing a user command, to avoid
284 thread issues.
285 thread issues.
285 """
286 """
286 daemon = True
287 daemon = True
287
288
288 def __init__(self, autosave_flag, time_interval=60):
289 def __init__(self, autosave_flag, time_interval=60):
289 threading.Thread.__init__(self)
290 threading.Thread.__init__(self)
290 self.time_interval = time_interval
291 self.time_interval = time_interval
291 self.autosave_flag = autosave_flag
292 self.autosave_flag = autosave_flag
292 self.exit_now = threading.Event()
293 self.exit_now = threading.Event()
293 # Ensure the thread is stopped tidily when exiting normally
294 # Ensure the thread is stopped tidily when exiting normally
294 atexit.register(self.stop)
295 atexit.register(self.stop)
295
296
296 def run(self):
297 def run(self):
297 while True:
298 while True:
298 self.exit_now.wait(self.time_interval)
299 self.exit_now.wait(self.time_interval)
299 if self.exit_now.is_set():
300 if self.exit_now.is_set():
300 break
301 break
301 self.autosave_flag.set()
302 self.autosave_flag.set()
302
303
303 def stop(self):
304 def stop(self):
304 """Safely and quickly stop the autosave timer thread."""
305 """Safely and quickly stop the autosave timer thread."""
305 self.exit_now.set()
306 self.exit_now.set()
306 self.join()
307 self.join()
307
308
309 @testdec.skip_doctest
308 def magic_history(self, parameter_s = ''):
310 def magic_history(self, parameter_s = ''):
309 """Print input history (_i<n> variables), with most recent last.
311 """Print input history (_i<n> variables), with most recent last.
310
312
311 %history -> print at most 40 inputs (some may be multi-line)\\
313 %history -> print at most 40 inputs (some may be multi-line)\\
312 %history n -> print at most n inputs\\
314 %history n -> print at most n inputs\\
313 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
315 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
314
316
315 By default, input history is printed without line numbers so it can be
317 By default, input history is printed without line numbers so it can be
316 directly pasted into an editor.
318 directly pasted into an editor.
317
319
318 With -n, each input's number <n> is shown, and is accessible as the
320 With -n, each input's number <n> is shown, and is accessible as the
319 automatically generated variable _i<n> as well as In[<n>]. Multi-line
321 automatically generated variable _i<n> as well as In[<n>]. Multi-line
320 statements are printed starting at a new line for easy copy/paste.
322 statements are printed starting at a new line for easy copy/paste.
321
323
322 Options:
324 Options:
323
325
324 -n: print line numbers for each input.
326 -n: print line numbers for each input.
325 This feature is only available if numbered prompts are in use.
327 This feature is only available if numbered prompts are in use.
326
328
327 -o: also print outputs for each input.
329 -o: also print outputs for each input.
328
330
329 -p: print classic '>>>' python prompts before each input. This is useful
331 -p: print classic '>>>' python prompts before each input. This is useful
330 for making documentation, and in conjunction with -o, for producing
332 for making documentation, and in conjunction with -o, for producing
331 doctest-ready output.
333 doctest-ready output.
332
334
333 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
335 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
334
336
335 -t: print the 'translated' history, as IPython understands it. IPython
337 -t: print the 'translated' history, as IPython understands it. IPython
336 filters your input and converts it all into valid Python source before
338 filters your input and converts it all into valid Python source before
337 executing it (things like magics or aliases are turned into function
339 executing it (things like magics or aliases are turned into function
338 calls, for example). With this option, you'll see the native history
340 calls, for example). With this option, you'll see the native history
339 instead of the user-entered version: '%cd /' will be seen as
341 instead of the user-entered version: '%cd /' will be seen as
340 'get_ipython().magic("%cd /")' instead of '%cd /'.
342 'get_ipython().magic("%cd /")' instead of '%cd /'.
341
343
342 -g: treat the arg as a pattern to grep for in (full) history.
344 -g: treat the arg as a pattern to grep for in (full) history.
343 This includes the "shadow history" (almost all commands ever written).
345 This includes the "shadow history" (almost all commands ever written).
344 Use '%hist -g' to show full shadow history (may be very long).
346 Use '%hist -g' to show full shadow history (may be very long).
345 In shadow history, every index nuwber starts with 0.
347 In shadow history, every index nuwber starts with 0.
346
348
347 -f FILENAME: instead of printing the output to the screen, redirect it to
349 -f FILENAME: instead of printing the output to the screen, redirect it to
348 the given file. The file is always overwritten, though IPython asks for
350 the given file. The file is always overwritten, though IPython asks for
349 confirmation first if it already exists.
351 confirmation first if it already exists.
352
353 Examples
354 --------
355 ::
356
357 In [6]: %hist -n 4 6
358 4:a = 12
359 5:print a**2
360
350 """
361 """
351
362
352 if not self.shell.displayhook.do_full_cache:
363 if not self.shell.displayhook.do_full_cache:
353 print('This feature is only available if numbered prompts are in use.')
364 print('This feature is only available if numbered prompts are in use.')
354 return
365 return
355 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
366 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
356
367
357 # Check if output to specific file was requested.
368 # Check if output to specific file was requested.
358 try:
369 try:
359 outfname = opts['f']
370 outfname = opts['f']
360 except KeyError:
371 except KeyError:
361 outfile = IPython.utils.io.Term.cout # default
372 outfile = IPython.utils.io.Term.cout # default
362 # We don't want to close stdout at the end!
373 # We don't want to close stdout at the end!
363 close_at_end = False
374 close_at_end = False
364 else:
375 else:
365 if os.path.exists(outfname):
376 if os.path.exists(outfname):
366 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
377 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
367 print('Aborting.')
378 print('Aborting.')
368 return
379 return
369
380
370 outfile = open(outfname,'w')
381 outfile = open(outfname,'w')
371 close_at_end = True
382 close_at_end = True
372
383
373 if 't' in opts:
384 if 't' in opts:
374 input_hist = self.shell.history_manager.input_hist_parsed
385 input_hist = self.shell.history_manager.input_hist_parsed
375 elif 'r' in opts:
386 elif 'r' in opts:
376 input_hist = self.shell.history_manager.input_hist_raw
387 input_hist = self.shell.history_manager.input_hist_raw
377 else:
388 else:
378 # Raw history is the default
389 # Raw history is the default
379 input_hist = self.shell.history_manager.input_hist_raw
390 input_hist = self.shell.history_manager.input_hist_raw
380
391
381 default_length = 40
392 default_length = 40
382 pattern = None
393 pattern = None
383 if 'g' in opts:
394 if 'g' in opts:
384 init = 1
395 init = 1
385 final = len(input_hist)
396 final = len(input_hist)
386 parts = parameter_s.split(None, 1)
397 parts = parameter_s.split(None, 1)
387 if len(parts) == 1:
398 if len(parts) == 1:
388 parts += '*'
399 parts += '*'
389 head, pattern = parts
400 head, pattern = parts
390 pattern = "*" + pattern + "*"
401 pattern = "*" + pattern + "*"
391 elif len(args) == 0:
402 elif len(args) == 0:
392 final = len(input_hist)-1
403 final = len(input_hist)-1
393 init = max(1,final-default_length)
404 init = max(1,final-default_length)
394 elif len(args) == 1:
405 elif len(args) == 1:
395 final = len(input_hist)
406 final = len(input_hist)
396 init = max(1, final-int(args[0]))
407 init = max(1, final-int(args[0]))
397 elif len(args) == 2:
408 elif len(args) == 2:
398 init, final = map(int, args)
409 init, final = map(int, args)
399 else:
410 else:
400 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
411 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
401 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
412 print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout)
402 return
413 return
403
414
404 width = len(str(final))
415 width = len(str(final))
405 line_sep = ['','\n']
416 line_sep = ['','\n']
406 print_nums = 'n' in opts
417 print_nums = 'n' in opts
407 print_outputs = 'o' in opts
418 print_outputs = 'o' in opts
408 pyprompts = 'p' in opts
419 pyprompts = 'p' in opts
409
420
410 found = False
421 found = False
411 if pattern is not None:
422 if pattern is not None:
412 sh = self.shell.history_manager.shadowhist.all()
423 sh = self.shell.history_manager.shadowhist.all()
413 for idx, s in sh:
424 for idx, s in sh:
414 if fnmatch.fnmatch(s, pattern):
425 if fnmatch.fnmatch(s, pattern):
415 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
426 print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile)
416 found = True
427 found = True
417
428
418 if found:
429 if found:
419 print("===", file=outfile)
430 print("===", file=outfile)
420 print("shadow history ends, fetch by %rep <number> (must start with 0)",
431 print("shadow history ends, fetch by %rep <number> (must start with 0)",
421 file=outfile)
432 file=outfile)
422 print("=== start of normal history ===", file=outfile)
433 print("=== start of normal history ===", file=outfile)
423
434
424 for in_num in range(init, final):
435 for in_num in range(init, final):
425 # Print user history with tabs expanded to 4 spaces. The GUI clients
436 # Print user history with tabs expanded to 4 spaces. The GUI clients
426 # use hard tabs for easier usability in auto-indented code, but we want
437 # use hard tabs for easier usability in auto-indented code, but we want
427 # to produce PEP-8 compliant history for safe pasting into an editor.
438 # to produce PEP-8 compliant history for safe pasting into an editor.
428 inline = input_hist[in_num].expandtabs(4).rstrip()+'\n'
439 inline = input_hist[in_num].expandtabs(4).rstrip()+'\n'
429
440
430 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
441 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
431 continue
442 continue
432
443
433 multiline = int(inline.count('\n') > 1)
444 multiline = int(inline.count('\n') > 1)
434 if print_nums:
445 if print_nums:
435 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
446 print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
436 file=outfile)
447 file=outfile)
437 if pyprompts:
448 if pyprompts:
438 print('>>>', file=outfile)
449 print('>>>', file=outfile)
439 if multiline:
450 if multiline:
440 lines = inline.splitlines()
451 lines = inline.splitlines()
441 print('\n... '.join(lines), file=outfile)
452 print('\n... '.join(lines), file=outfile)
442 print('... ', file=outfile)
453 print('... ', file=outfile)
443 else:
454 else:
444 print(inline, end='', file=outfile)
455 print(inline, end='', file=outfile)
445 else:
456 else:
446 print(inline, end='', file=outfile)
457 print(inline, end='', file=outfile)
447 if print_outputs:
458 if print_outputs:
448 output = self.shell.history_manager.output_hist.get(in_num)
459 output = self.shell.history_manager.output_hist.get(in_num)
449 if output is not None:
460 if output is not None:
450 print(repr(output), file=outfile)
461 print(repr(output), file=outfile)
451
462
452 if close_at_end:
463 if close_at_end:
453 outfile.close()
464 outfile.close()
454
465
455
466
456 def magic_hist(self, parameter_s=''):
467 def magic_hist(self, parameter_s=''):
457 """Alternate name for %history."""
468 """Alternate name for %history."""
458 return self.magic_history(parameter_s)
469 return self.magic_history(parameter_s)
459
470
460
471
461 def rep_f(self, arg):
472 def rep_f(self, arg):
462 r""" Repeat a command, or get command to input line for editing
473 r""" Repeat a command, or get command to input line for editing
463
474
464 - %rep (no arguments):
475 - %rep (no arguments):
465
476
466 Place a string version of last computation result (stored in the special '_'
477 Place a string version of last computation result (stored in the special '_'
467 variable) to the next input prompt. Allows you to create elaborate command
478 variable) to the next input prompt. Allows you to create elaborate command
468 lines without using copy-paste::
479 lines without using copy-paste::
469
480
470 $ l = ["hei", "vaan"]
481 $ l = ["hei", "vaan"]
471 $ "".join(l)
482 $ "".join(l)
472 ==> heivaan
483 ==> heivaan
473 $ %rep
484 $ %rep
474 $ heivaan_ <== cursor blinking
485 $ heivaan_ <== cursor blinking
475
486
476 %rep 45
487 %rep 45
477
488
478 Place history line 45 to next input prompt. Use %hist to find out the
489 Place history line 45 to next input prompt. Use %hist to find out the
479 number.
490 number.
480
491
481 %rep 1-4 6-7 3
492 %rep 1-4 6-7 3
482
493
483 Repeat the specified lines immediately. Input slice syntax is the same as
494 Repeat the specified lines immediately. Input slice syntax is the same as
484 in %macro and %save.
495 in %macro and %save.
485
496
486 %rep foo
497 %rep foo
487
498
488 Place the most recent line that has the substring "foo" to next input.
499 Place the most recent line that has the substring "foo" to next input.
489 (e.g. 'svn ci -m foobar').
500 (e.g. 'svn ci -m foobar').
490 """
501 """
491
502
492 opts,args = self.parse_options(arg,'',mode='list')
503 opts,args = self.parse_options(arg,'',mode='list')
493 if not args:
504 if not args:
494 self.set_next_input(str(self.shell.user_ns["_"]))
505 self.set_next_input(str(self.shell.user_ns["_"]))
495 return
506 return
496
507
497 if len(args) == 1 and not '-' in args[0]:
508 if len(args) == 1 and not '-' in args[0]:
498 arg = args[0]
509 arg = args[0]
499 if len(arg) > 1 and arg.startswith('0'):
510 if len(arg) > 1 and arg.startswith('0'):
500 # get from shadow hist
511 # get from shadow hist
501 num = int(arg[1:])
512 num = int(arg[1:])
502 line = self.shell.shadowhist.get(num)
513 line = self.shell.shadowhist.get(num)
503 self.set_next_input(str(line))
514 self.set_next_input(str(line))
504 return
515 return
505 try:
516 try:
506 num = int(args[0])
517 num = int(args[0])
507 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
518 self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip())
508 return
519 return
509 except ValueError:
520 except ValueError:
510 pass
521 pass
511
522
512 for h in reversed(self.shell.input_hist_raw):
523 for h in reversed(self.shell.input_hist_raw):
513 if 'rep' in h:
524 if 'rep' in h:
514 continue
525 continue
515 if fnmatch.fnmatch(h,'*' + arg + '*'):
526 if fnmatch.fnmatch(h,'*' + arg + '*'):
516 self.set_next_input(str(h).rstrip())
527 self.set_next_input(str(h).rstrip())
517 return
528 return
518
529
519 try:
530 try:
520 lines = self.extract_input_slices(args, True)
531 lines = self.extract_input_slices(args, True)
521 print("lines", lines)
532 print("lines", lines)
522 self.run_cell(lines)
533 self.run_cell(lines)
523 except ValueError:
534 except ValueError:
524 print("Not found in recent history:", args)
535 print("Not found in recent history:", args)
525
536
526
537
527 _sentinel = object()
538 _sentinel = object()
528
539
529 class ShadowHist(object):
540 class ShadowHist(object):
530 def __init__(self, db, shell):
541 def __init__(self, db, shell):
531 # cmd => idx mapping
542 # cmd => idx mapping
532 self.curidx = 0
543 self.curidx = 0
533 self.db = db
544 self.db = db
534 self.disabled = False
545 self.disabled = False
535 self.shell = shell
546 self.shell = shell
536
547
537 def inc_idx(self):
548 def inc_idx(self):
538 idx = self.db.get('shadowhist_idx', 1)
549 idx = self.db.get('shadowhist_idx', 1)
539 self.db['shadowhist_idx'] = idx + 1
550 self.db['shadowhist_idx'] = idx + 1
540 return idx
551 return idx
541
552
542 def add(self, ent):
553 def add(self, ent):
543 if self.disabled:
554 if self.disabled:
544 return
555 return
545 try:
556 try:
546 old = self.db.hget('shadowhist', ent, _sentinel)
557 old = self.db.hget('shadowhist', ent, _sentinel)
547 if old is not _sentinel:
558 if old is not _sentinel:
548 return
559 return
549 newidx = self.inc_idx()
560 newidx = self.inc_idx()
550 #print("new", newidx) # dbg
561 #print("new", newidx) # dbg
551 self.db.hset('shadowhist',ent, newidx)
562 self.db.hset('shadowhist',ent, newidx)
552 except:
563 except:
553 self.shell.showtraceback()
564 self.shell.showtraceback()
554 print("WARNING: disabling shadow history")
565 print("WARNING: disabling shadow history")
555 self.disabled = True
566 self.disabled = True
556
567
557 def all(self):
568 def all(self):
558 d = self.db.hdict('shadowhist')
569 d = self.db.hdict('shadowhist')
559 items = [(i,s) for (s,i) in d.iteritems()]
570 items = [(i,s) for (s,i) in d.iteritems()]
560 items.sort()
571 items.sort()
561 return items
572 return items
562
573
563 def get(self, idx):
574 def get(self, idx):
564 all = self.all()
575 all = self.all()
565
576
566 for k, v in all:
577 for k, v in all:
567 if k == idx:
578 if k == idx:
568 return v
579 return v
569
580
570
581
571 def init_ipython(ip):
582 def init_ipython(ip):
572 ip.define_magic("rep",rep_f)
583 ip.define_magic("rep",rep_f)
573 ip.define_magic("hist",magic_hist)
584 ip.define_magic("hist",magic_hist)
574 ip.define_magic("history",magic_history)
585 ip.define_magic("history",magic_history)
575
586
576 # XXX - ipy_completers are in quarantine, need to be updated to new apis
587 # XXX - ipy_completers are in quarantine, need to be updated to new apis
577 #import ipy_completers
588 #import ipy_completers
578 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
589 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,3429 +1,3463 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
188 if raw:
188 if raw:
189 hist = self.shell.history_manager.input_hist_raw
189 hist = self.shell.history_manager.input_hist_raw
190 else:
190 else:
191 hist = self.shell.history_manager.input_hist_parsed
191 hist = self.shell.history_manager.input_hist_parsed
192
192
193 cmds = []
193 cmds = []
194 for chunk in slices:
194 for chunk in slices:
195 if ':' in chunk:
195 if ':' in chunk:
196 ini,fin = map(int,chunk.split(':'))
196 ini,fin = map(int,chunk.split(':'))
197 elif '-' in chunk:
197 elif '-' in chunk:
198 ini,fin = map(int,chunk.split('-'))
198 ini,fin = map(int,chunk.split('-'))
199 fin += 1
199 fin += 1
200 else:
200 else:
201 ini = int(chunk)
201 ini = int(chunk)
202 fin = ini+1
202 fin = ini+1
203 cmds.append(''.join(hist[ini:fin]))
203 cmds.append(''.join(hist[ini:fin]))
204 return cmds
204 return cmds
205
205
206 def arg_err(self,func):
206 def arg_err(self,func):
207 """Print docstring if incorrect arguments were passed"""
207 """Print docstring if incorrect arguments were passed"""
208 print 'Error in arguments:'
208 print 'Error in arguments:'
209 print oinspect.getdoc(func)
209 print oinspect.getdoc(func)
210
210
211 def format_latex(self,strng):
211 def format_latex(self,strng):
212 """Format a string for latex inclusion."""
212 """Format a string for latex inclusion."""
213
213
214 # Characters that need to be escaped for latex:
214 # Characters that need to be escaped for latex:
215 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
215 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
216 # Magic command names as headers:
216 # Magic command names as headers:
217 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
217 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
218 re.MULTILINE)
218 re.MULTILINE)
219 # Magic commands
219 # Magic commands
220 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
220 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
221 re.MULTILINE)
221 re.MULTILINE)
222 # Paragraph continue
222 # Paragraph continue
223 par_re = re.compile(r'\\$',re.MULTILINE)
223 par_re = re.compile(r'\\$',re.MULTILINE)
224
224
225 # The "\n" symbol
225 # The "\n" symbol
226 newline_re = re.compile(r'\\n')
226 newline_re = re.compile(r'\\n')
227
227
228 # Now build the string for output:
228 # Now build the string for output:
229 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
229 #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}}:',
230 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
231 strng)
231 strng)
232 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
232 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
233 strng = par_re.sub(r'\\\\',strng)
233 strng = par_re.sub(r'\\\\',strng)
234 strng = escape_re.sub(r'\\\1',strng)
234 strng = escape_re.sub(r'\\\1',strng)
235 strng = newline_re.sub(r'\\textbackslash{}n',strng)
235 strng = newline_re.sub(r'\\textbackslash{}n',strng)
236 return strng
236 return strng
237
237
238 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
238 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
239 """Parse options passed to an argument string.
239 """Parse options passed to an argument string.
240
240
241 The interface is similar to that of getopt(), but it returns back a
241 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
242 Struct with the options as keys and the stripped argument string still
243 as a string.
243 as a string.
244
244
245 arg_str is quoted as a true sys.argv vector by using shlex.split.
245 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
246 This allows us to easily expand variables, glob files, quote
247 arguments, etc.
247 arguments, etc.
248
248
249 Options:
249 Options:
250 -mode: default 'string'. If given as 'list', the argument string is
250 -mode: default 'string'. If given as 'list', the argument string is
251 returned as a list (split on whitespace) instead of a string.
251 returned as a list (split on whitespace) instead of a string.
252
252
253 -list_all: put all option values in lists. Normally only options
253 -list_all: put all option values in lists. Normally only options
254 appearing more than once are put in a list.
254 appearing more than once are put in a list.
255
255
256 -posix (True): whether to split the input line in POSIX mode or not,
256 -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
257 as per the conventions outlined in the shlex module from the
258 standard library."""
258 standard library."""
259
259
260 # inject default options at the beginning of the input line
260 # inject default options at the beginning of the input line
261 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
261 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
262 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
262 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
263
263
264 mode = kw.get('mode','string')
264 mode = kw.get('mode','string')
265 if mode not in ['string','list']:
265 if mode not in ['string','list']:
266 raise ValueError,'incorrect mode given: %s' % mode
266 raise ValueError,'incorrect mode given: %s' % mode
267 # Get options
267 # Get options
268 list_all = kw.get('list_all',0)
268 list_all = kw.get('list_all',0)
269 posix = kw.get('posix', os.name == 'posix')
269 posix = kw.get('posix', os.name == 'posix')
270
270
271 # Check if we have more than one argument to warrant extra processing:
271 # Check if we have more than one argument to warrant extra processing:
272 odict = {} # Dictionary with options
272 odict = {} # Dictionary with options
273 args = arg_str.split()
273 args = arg_str.split()
274 if len(args) >= 1:
274 if len(args) >= 1:
275 # If the list of inputs only has 0 or 1 thing in it, there's no
275 # If the list of inputs only has 0 or 1 thing in it, there's no
276 # need to look for options
276 # need to look for options
277 argv = arg_split(arg_str,posix)
277 argv = arg_split(arg_str,posix)
278 # Do regular option processing
278 # Do regular option processing
279 try:
279 try:
280 opts,args = getopt(argv,opt_str,*long_opts)
280 opts,args = getopt(argv,opt_str,*long_opts)
281 except GetoptError,e:
281 except GetoptError,e:
282 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
282 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
283 " ".join(long_opts)))
283 " ".join(long_opts)))
284 for o,a in opts:
284 for o,a in opts:
285 if o.startswith('--'):
285 if o.startswith('--'):
286 o = o[2:]
286 o = o[2:]
287 else:
287 else:
288 o = o[1:]
288 o = o[1:]
289 try:
289 try:
290 odict[o].append(a)
290 odict[o].append(a)
291 except AttributeError:
291 except AttributeError:
292 odict[o] = [odict[o],a]
292 odict[o] = [odict[o],a]
293 except KeyError:
293 except KeyError:
294 if list_all:
294 if list_all:
295 odict[o] = [a]
295 odict[o] = [a]
296 else:
296 else:
297 odict[o] = a
297 odict[o] = a
298
298
299 # Prepare opts,args for return
299 # Prepare opts,args for return
300 opts = Struct(odict)
300 opts = Struct(odict)
301 if mode == 'string':
301 if mode == 'string':
302 args = ' '.join(args)
302 args = ' '.join(args)
303
303
304 return opts,args
304 return opts,args
305
305
306 #......................................................................
306 #......................................................................
307 # And now the actual magic functions
307 # And now the actual magic functions
308
308
309 # Functions for IPython shell work (vars,funcs, config, etc)
309 # Functions for IPython shell work (vars,funcs, config, etc)
310 def magic_lsmagic(self, parameter_s = ''):
310 def magic_lsmagic(self, parameter_s = ''):
311 """List currently available magic functions."""
311 """List currently available magic functions."""
312 mesc = ESC_MAGIC
312 mesc = ESC_MAGIC
313 print 'Available magic functions:\n'+mesc+\
313 print 'Available magic functions:\n'+mesc+\
314 (' '+mesc).join(self.lsmagic())
314 (' '+mesc).join(self.lsmagic())
315 print '\n' + Magic.auto_status[self.shell.automagic]
315 print '\n' + Magic.auto_status[self.shell.automagic]
316 return None
316 return None
317
317
318 def magic_magic(self, parameter_s = ''):
318 def magic_magic(self, parameter_s = ''):
319 """Print information about the magic function system.
319 """Print information about the magic function system.
320
320
321 Supported formats: -latex, -brief, -rest
321 Supported formats: -latex, -brief, -rest
322 """
322 """
323
323
324 mode = ''
324 mode = ''
325 try:
325 try:
326 if parameter_s.split()[0] == '-latex':
326 if parameter_s.split()[0] == '-latex':
327 mode = 'latex'
327 mode = 'latex'
328 if parameter_s.split()[0] == '-brief':
328 if parameter_s.split()[0] == '-brief':
329 mode = 'brief'
329 mode = 'brief'
330 if parameter_s.split()[0] == '-rest':
330 if parameter_s.split()[0] == '-rest':
331 mode = 'rest'
331 mode = 'rest'
332 rest_docs = []
332 rest_docs = []
333 except:
333 except:
334 pass
334 pass
335
335
336 magic_docs = []
336 magic_docs = []
337 for fname in self.lsmagic():
337 for fname in self.lsmagic():
338 mname = 'magic_' + fname
338 mname = 'magic_' + fname
339 for space in (Magic,self,self.__class__):
339 for space in (Magic,self,self.__class__):
340 try:
340 try:
341 fn = space.__dict__[mname]
341 fn = space.__dict__[mname]
342 except KeyError:
342 except KeyError:
343 pass
343 pass
344 else:
344 else:
345 break
345 break
346 if mode == 'brief':
346 if mode == 'brief':
347 # only first line
347 # only first line
348 if fn.__doc__:
348 if fn.__doc__:
349 fndoc = fn.__doc__.split('\n',1)[0]
349 fndoc = fn.__doc__.split('\n',1)[0]
350 else:
350 else:
351 fndoc = 'No documentation'
351 fndoc = 'No documentation'
352 else:
352 else:
353 if fn.__doc__:
353 if fn.__doc__:
354 fndoc = fn.__doc__.rstrip()
354 fndoc = fn.__doc__.rstrip()
355 else:
355 else:
356 fndoc = 'No documentation'
356 fndoc = 'No documentation'
357
357
358
358
359 if mode == 'rest':
359 if mode == 'rest':
360 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
360 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
361 fname,fndoc))
361 fname,fndoc))
362
362
363 else:
363 else:
364 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
364 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
365 fname,fndoc))
365 fname,fndoc))
366
366
367 magic_docs = ''.join(magic_docs)
367 magic_docs = ''.join(magic_docs)
368
368
369 if mode == 'rest':
369 if mode == 'rest':
370 return "".join(rest_docs)
370 return "".join(rest_docs)
371
371
372 if mode == 'latex':
372 if mode == 'latex':
373 print self.format_latex(magic_docs)
373 print self.format_latex(magic_docs)
374 return
374 return
375 else:
375 else:
376 magic_docs = format_screen(magic_docs)
376 magic_docs = format_screen(magic_docs)
377 if mode == 'brief':
377 if mode == 'brief':
378 return magic_docs
378 return magic_docs
379
379
380 outmsg = """
380 outmsg = """
381 IPython's 'magic' functions
381 IPython's 'magic' functions
382 ===========================
382 ===========================
383
383
384 The magic function system provides a series of functions which allow you to
384 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
385 control the behavior of IPython itself, plus a lot of system-type
386 features. All these functions are prefixed with a % character, but parameters
386 features. All these functions are prefixed with a % character, but parameters
387 are given without parentheses or quotes.
387 are given without parentheses or quotes.
388
388
389 NOTE: If you have 'automagic' enabled (via the command line option or with the
389 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,
390 %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.
391 IPython ships with automagic on, so you should only rarely need the % escape.
392
392
393 Example: typing '%cd mydir' (without the quotes) changes you working directory
393 Example: typing '%cd mydir' (without the quotes) changes you working directory
394 to 'mydir', if it exists.
394 to 'mydir', if it exists.
395
395
396 You can define your own magic functions to extend the system. See the supplied
396 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
397 ipythonrc and example-magic.py files for details (in your ipython
398 configuration directory, typically $HOME/.ipython/).
398 configuration directory, typically $HOME/.ipython/).
399
399
400 You can also define your own aliased names for magic functions. In your
400 You can also define your own aliased names for magic functions. In your
401 ipythonrc file, placing a line like:
401 ipythonrc file, placing a line like:
402
402
403 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
403 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
404
404
405 will define %pf as a new name for %profile.
405 will define %pf as a new name for %profile.
406
406
407 You can also call magics in code using the magic() function, which IPython
407 You can also call magics in code using the magic() function, which IPython
408 automatically adds to the builtin namespace. Type 'magic?' for details.
408 automatically adds to the builtin namespace. Type 'magic?' for details.
409
409
410 For a list of the available magic functions, use %lsmagic. For a description
410 For a list of the available magic functions, use %lsmagic. For a description
411 of any of them, type %magic_name?, e.g. '%cd?'.
411 of any of them, type %magic_name?, e.g. '%cd?'.
412
412
413 Currently the magic system has the following functions:\n"""
413 Currently the magic system has the following functions:\n"""
414
414
415 mesc = ESC_MAGIC
415 mesc = ESC_MAGIC
416 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
416 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
417 "\n\n%s%s\n\n%s" % (outmsg,
417 "\n\n%s%s\n\n%s" % (outmsg,
418 magic_docs,mesc,mesc,
418 magic_docs,mesc,mesc,
419 (' '+mesc).join(self.lsmagic()),
419 (' '+mesc).join(self.lsmagic()),
420 Magic.auto_status[self.shell.automagic] ) )
420 Magic.auto_status[self.shell.automagic] ) )
421 page.page(outmsg)
421 page.page(outmsg)
422
422
423 def magic_automagic(self, parameter_s = ''):
423 def magic_automagic(self, parameter_s = ''):
424 """Make magic functions callable without having to type the initial %.
424 """Make magic functions callable without having to type the initial %.
425
425
426 Without argumentsl toggles on/off (when off, you must call it as
426 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
427 %automagic, of course). With arguments it sets the value, and you can
428 use any of (case insensitive):
428 use any of (case insensitive):
429
429
430 - on,1,True: to activate
430 - on,1,True: to activate
431
431
432 - off,0,False: to deactivate.
432 - off,0,False: to deactivate.
433
433
434 Note that magic functions have lowest priority, so if there's a
434 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
435 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
436 work for that function (you get the variable instead). However, if you
437 delete the variable (del var), the previously shadowed magic function
437 delete the variable (del var), the previously shadowed magic function
438 becomes visible to automagic again."""
438 becomes visible to automagic again."""
439
439
440 arg = parameter_s.lower()
440 arg = parameter_s.lower()
441 if parameter_s in ('on','1','true'):
441 if parameter_s in ('on','1','true'):
442 self.shell.automagic = True
442 self.shell.automagic = True
443 elif parameter_s in ('off','0','false'):
443 elif parameter_s in ('off','0','false'):
444 self.shell.automagic = False
444 self.shell.automagic = False
445 else:
445 else:
446 self.shell.automagic = not self.shell.automagic
446 self.shell.automagic = not self.shell.automagic
447 print '\n' + Magic.auto_status[self.shell.automagic]
447 print '\n' + Magic.auto_status[self.shell.automagic]
448
448
449 @testdec.skip_doctest
449 @testdec.skip_doctest
450 def magic_autocall(self, parameter_s = ''):
450 def magic_autocall(self, parameter_s = ''):
451 """Make functions callable without having to type parentheses.
451 """Make functions callable without having to type parentheses.
452
452
453 Usage:
453 Usage:
454
454
455 %autocall [mode]
455 %autocall [mode]
456
456
457 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
457 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).
458 value is toggled on and off (remembering the previous state).
459
459
460 In more detail, these values mean:
460 In more detail, these values mean:
461
461
462 0 -> fully disabled
462 0 -> fully disabled
463
463
464 1 -> active, but do not apply if there are no arguments on the line.
464 1 -> active, but do not apply if there are no arguments on the line.
465
465
466 In this mode, you get:
466 In this mode, you get:
467
467
468 In [1]: callable
468 In [1]: callable
469 Out[1]: <built-in function callable>
469 Out[1]: <built-in function callable>
470
470
471 In [2]: callable 'hello'
471 In [2]: callable 'hello'
472 ------> callable('hello')
472 ------> callable('hello')
473 Out[2]: False
473 Out[2]: False
474
474
475 2 -> Active always. Even if no arguments are present, the callable
475 2 -> Active always. Even if no arguments are present, the callable
476 object is called:
476 object is called:
477
477
478 In [2]: float
478 In [2]: float
479 ------> float()
479 ------> float()
480 Out[2]: 0.0
480 Out[2]: 0.0
481
481
482 Note that even with autocall off, you can still use '/' at the start of
482 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
483 a line to treat the first argument on the command line as a function
484 and add parentheses to it:
484 and add parentheses to it:
485
485
486 In [8]: /str 43
486 In [8]: /str 43
487 ------> str(43)
487 ------> str(43)
488 Out[8]: '43'
488 Out[8]: '43'
489
489
490 # all-random (note for auto-testing)
490 # all-random (note for auto-testing)
491 """
491 """
492
492
493 if parameter_s:
493 if parameter_s:
494 arg = int(parameter_s)
494 arg = int(parameter_s)
495 else:
495 else:
496 arg = 'toggle'
496 arg = 'toggle'
497
497
498 if not arg in (0,1,2,'toggle'):
498 if not arg in (0,1,2,'toggle'):
499 error('Valid modes: (0->Off, 1->Smart, 2->Full')
499 error('Valid modes: (0->Off, 1->Smart, 2->Full')
500 return
500 return
501
501
502 if arg in (0,1,2):
502 if arg in (0,1,2):
503 self.shell.autocall = arg
503 self.shell.autocall = arg
504 else: # toggle
504 else: # toggle
505 if self.shell.autocall:
505 if self.shell.autocall:
506 self._magic_state.autocall_save = self.shell.autocall
506 self._magic_state.autocall_save = self.shell.autocall
507 self.shell.autocall = 0
507 self.shell.autocall = 0
508 else:
508 else:
509 try:
509 try:
510 self.shell.autocall = self._magic_state.autocall_save
510 self.shell.autocall = self._magic_state.autocall_save
511 except AttributeError:
511 except AttributeError:
512 self.shell.autocall = self._magic_state.autocall_save = 1
512 self.shell.autocall = self._magic_state.autocall_save = 1
513
513
514 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
514 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
515
515
516
516
517 def magic_page(self, parameter_s=''):
517 def magic_page(self, parameter_s=''):
518 """Pretty print the object and display it through a pager.
518 """Pretty print the object and display it through a pager.
519
519
520 %page [options] OBJECT
520 %page [options] OBJECT
521
521
522 If no object is given, use _ (last output).
522 If no object is given, use _ (last output).
523
523
524 Options:
524 Options:
525
525
526 -r: page str(object), don't pretty-print it."""
526 -r: page str(object), don't pretty-print it."""
527
527
528 # After a function contributed by Olivier Aubert, slightly modified.
528 # After a function contributed by Olivier Aubert, slightly modified.
529
529
530 # Process options/args
530 # Process options/args
531 opts,args = self.parse_options(parameter_s,'r')
531 opts,args = self.parse_options(parameter_s,'r')
532 raw = 'r' in opts
532 raw = 'r' in opts
533
533
534 oname = args and args or '_'
534 oname = args and args or '_'
535 info = self._ofind(oname)
535 info = self._ofind(oname)
536 if info['found']:
536 if info['found']:
537 txt = (raw and str or pformat)( info['obj'] )
537 txt = (raw and str or pformat)( info['obj'] )
538 page.page(txt)
538 page.page(txt)
539 else:
539 else:
540 print 'Object `%s` not found' % oname
540 print 'Object `%s` not found' % oname
541
541
542 def magic_profile(self, parameter_s=''):
542 def magic_profile(self, parameter_s=''):
543 """Print your currently active IPython profile."""
543 """Print your currently active IPython profile."""
544 if self.shell.profile:
544 if self.shell.profile:
545 printpl('Current IPython profile: $self.shell.profile.')
545 printpl('Current IPython profile: $self.shell.profile.')
546 else:
546 else:
547 print 'No profile active.'
547 print 'No profile active.'
548
548
549 def magic_pinfo(self, parameter_s='', namespaces=None):
549 def magic_pinfo(self, parameter_s='', namespaces=None):
550 """Provide detailed information about an object.
550 """Provide detailed information about an object.
551
551
552 '%pinfo object' is just a synonym for object? or ?object."""
552 '%pinfo object' is just a synonym for object? or ?object."""
553
553
554 #print 'pinfo par: <%s>' % parameter_s # dbg
554 #print 'pinfo par: <%s>' % parameter_s # dbg
555
555
556
556
557 # detail_level: 0 -> obj? , 1 -> obj??
557 # detail_level: 0 -> obj? , 1 -> obj??
558 detail_level = 0
558 detail_level = 0
559 # We need to detect if we got called as 'pinfo pinfo foo', which can
559 # 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.
560 # happen if the user types 'pinfo foo?' at the cmd line.
561 pinfo,qmark1,oname,qmark2 = \
561 pinfo,qmark1,oname,qmark2 = \
562 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
562 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
563 if pinfo or qmark1 or qmark2:
563 if pinfo or qmark1 or qmark2:
564 detail_level = 1
564 detail_level = 1
565 if "*" in oname:
565 if "*" in oname:
566 self.magic_psearch(oname)
566 self.magic_psearch(oname)
567 else:
567 else:
568 self.shell._inspect('pinfo', oname, detail_level=detail_level,
568 self.shell._inspect('pinfo', oname, detail_level=detail_level,
569 namespaces=namespaces)
569 namespaces=namespaces)
570
570
571 def magic_pinfo2(self, parameter_s='', namespaces=None):
571 def magic_pinfo2(self, parameter_s='', namespaces=None):
572 """Provide extra detailed information about an object.
572 """Provide extra detailed information about an object.
573
573
574 '%pinfo2 object' is just a synonym for object?? or ??object."""
574 '%pinfo2 object' is just a synonym for object?? or ??object."""
575 self.shell._inspect('pinfo', parameter_s, detail_level=1,
575 self.shell._inspect('pinfo', parameter_s, detail_level=1,
576 namespaces=namespaces)
576 namespaces=namespaces)
577
577
578 @testdec.skip_doctest
578 def magic_pdef(self, parameter_s='', namespaces=None):
579 def magic_pdef(self, parameter_s='', namespaces=None):
579 """Print the definition header for any callable object.
580 """Print the definition header for any callable object.
580
581
581 If the object is a class, print the constructor information."""
582 If the object is a class, print the constructor information.
583
584 Examples
585 --------
586 ::
587
588 In [3]: %pdef urllib.urlopen
589 urllib.urlopen(url, data=None, proxies=None)
590 """
582 self._inspect('pdef',parameter_s, namespaces)
591 self._inspect('pdef',parameter_s, namespaces)
583
592
584 def magic_pdoc(self, parameter_s='', namespaces=None):
593 def magic_pdoc(self, parameter_s='', namespaces=None):
585 """Print the docstring for an object.
594 """Print the docstring for an object.
586
595
587 If the given object is a class, it will print both the class and the
596 If the given object is a class, it will print both the class and the
588 constructor docstrings."""
597 constructor docstrings."""
589 self._inspect('pdoc',parameter_s, namespaces)
598 self._inspect('pdoc',parameter_s, namespaces)
590
599
591 def magic_psource(self, parameter_s='', namespaces=None):
600 def magic_psource(self, parameter_s='', namespaces=None):
592 """Print (or run through pager) the source code for an object."""
601 """Print (or run through pager) the source code for an object."""
593 self._inspect('psource',parameter_s, namespaces)
602 self._inspect('psource',parameter_s, namespaces)
594
603
595 def magic_pfile(self, parameter_s=''):
604 def magic_pfile(self, parameter_s=''):
596 """Print (or run through pager) the file where an object is defined.
605 """Print (or run through pager) the file where an object is defined.
597
606
598 The file opens at the line where the object definition begins. IPython
607 The file opens at the line where the object definition begins. IPython
599 will honor the environment variable PAGER if set, and otherwise will
608 will honor the environment variable PAGER if set, and otherwise will
600 do its best to print the file in a convenient form.
609 do its best to print the file in a convenient form.
601
610
602 If the given argument is not an object currently defined, IPython will
611 If the given argument is not an object currently defined, IPython will
603 try to interpret it as a filename (automatically adding a .py extension
612 try to interpret it as a filename (automatically adding a .py extension
604 if needed). You can thus use %pfile as a syntax highlighting code
613 if needed). You can thus use %pfile as a syntax highlighting code
605 viewer."""
614 viewer."""
606
615
607 # first interpret argument as an object name
616 # first interpret argument as an object name
608 out = self._inspect('pfile',parameter_s)
617 out = self._inspect('pfile',parameter_s)
609 # if not, try the input as a filename
618 # if not, try the input as a filename
610 if out == 'not found':
619 if out == 'not found':
611 try:
620 try:
612 filename = get_py_filename(parameter_s)
621 filename = get_py_filename(parameter_s)
613 except IOError,msg:
622 except IOError,msg:
614 print msg
623 print msg
615 return
624 return
616 page.page(self.shell.inspector.format(file(filename).read()))
625 page.page(self.shell.inspector.format(file(filename).read()))
617
626
618 def magic_psearch(self, parameter_s=''):
627 def magic_psearch(self, parameter_s=''):
619 """Search for object in namespaces by wildcard.
628 """Search for object in namespaces by wildcard.
620
629
621 %psearch [options] PATTERN [OBJECT TYPE]
630 %psearch [options] PATTERN [OBJECT TYPE]
622
631
623 Note: ? can be used as a synonym for %psearch, at the beginning or at
632 Note: ? can be used as a synonym for %psearch, at the beginning or at
624 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
633 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
625 rest of the command line must be unchanged (options come first), so
634 rest of the command line must be unchanged (options come first), so
626 for example the following forms are equivalent
635 for example the following forms are equivalent
627
636
628 %psearch -i a* function
637 %psearch -i a* function
629 -i a* function?
638 -i a* function?
630 ?-i a* function
639 ?-i a* function
631
640
632 Arguments:
641 Arguments:
633
642
634 PATTERN
643 PATTERN
635
644
636 where PATTERN is a string containing * as a wildcard similar to its
645 where PATTERN is a string containing * as a wildcard similar to its
637 use in a shell. The pattern is matched in all namespaces on the
646 use in a shell. The pattern is matched in all namespaces on the
638 search path. By default objects starting with a single _ are not
647 search path. By default objects starting with a single _ are not
639 matched, many IPython generated objects have a single
648 matched, many IPython generated objects have a single
640 underscore. The default is case insensitive matching. Matching is
649 underscore. The default is case insensitive matching. Matching is
641 also done on the attributes of objects and not only on the objects
650 also done on the attributes of objects and not only on the objects
642 in a module.
651 in a module.
643
652
644 [OBJECT TYPE]
653 [OBJECT TYPE]
645
654
646 Is the name of a python type from the types module. The name is
655 Is the name of a python type from the types module. The name is
647 given in lowercase without the ending type, ex. StringType is
656 given in lowercase without the ending type, ex. StringType is
648 written string. By adding a type here only objects matching the
657 written string. By adding a type here only objects matching the
649 given type are matched. Using all here makes the pattern match all
658 given type are matched. Using all here makes the pattern match all
650 types (this is the default).
659 types (this is the default).
651
660
652 Options:
661 Options:
653
662
654 -a: makes the pattern match even objects whose names start with a
663 -a: makes the pattern match even objects whose names start with a
655 single underscore. These names are normally ommitted from the
664 single underscore. These names are normally ommitted from the
656 search.
665 search.
657
666
658 -i/-c: make the pattern case insensitive/sensitive. If neither of
667 -i/-c: make the pattern case insensitive/sensitive. If neither of
659 these options is given, the default is read from your ipythonrc
668 these options is given, the default is read from your ipythonrc
660 file. The option name which sets this value is
669 file. The option name which sets this value is
661 'wildcards_case_sensitive'. If this option is not specified in your
670 'wildcards_case_sensitive'. If this option is not specified in your
662 ipythonrc file, IPython's internal default is to do a case sensitive
671 ipythonrc file, IPython's internal default is to do a case sensitive
663 search.
672 search.
664
673
665 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
674 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
666 specifiy can be searched in any of the following namespaces:
675 specifiy can be searched in any of the following namespaces:
667 'builtin', 'user', 'user_global','internal', 'alias', where
676 'builtin', 'user', 'user_global','internal', 'alias', where
668 'builtin' and 'user' are the search defaults. Note that you should
677 'builtin' and 'user' are the search defaults. Note that you should
669 not use quotes when specifying namespaces.
678 not use quotes when specifying namespaces.
670
679
671 'Builtin' contains the python module builtin, 'user' contains all
680 'Builtin' contains the python module builtin, 'user' contains all
672 user data, 'alias' only contain the shell aliases and no python
681 user data, 'alias' only contain the shell aliases and no python
673 objects, 'internal' contains objects used by IPython. The
682 objects, 'internal' contains objects used by IPython. The
674 'user_global' namespace is only used by embedded IPython instances,
683 'user_global' namespace is only used by embedded IPython instances,
675 and it contains module-level globals. You can add namespaces to the
684 and it contains module-level globals. You can add namespaces to the
676 search with -s or exclude them with -e (these options can be given
685 search with -s or exclude them with -e (these options can be given
677 more than once).
686 more than once).
678
687
679 Examples:
688 Examples:
680
689
681 %psearch a* -> objects beginning with an a
690 %psearch a* -> objects beginning with an a
682 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
691 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
683 %psearch a* function -> all functions beginning with an a
692 %psearch a* function -> all functions beginning with an a
684 %psearch re.e* -> objects beginning with an e in module re
693 %psearch re.e* -> objects beginning with an e in module re
685 %psearch r*.e* -> objects that start with e in modules starting in r
694 %psearch r*.e* -> objects that start with e in modules starting in r
686 %psearch r*.* string -> all strings in modules beginning with r
695 %psearch r*.* string -> all strings in modules beginning with r
687
696
688 Case sensitve search:
697 Case sensitve search:
689
698
690 %psearch -c a* list all object beginning with lower case a
699 %psearch -c a* list all object beginning with lower case a
691
700
692 Show objects beginning with a single _:
701 Show objects beginning with a single _:
693
702
694 %psearch -a _* list objects beginning with a single underscore"""
703 %psearch -a _* list objects beginning with a single underscore"""
695 try:
704 try:
696 parameter_s = parameter_s.encode('ascii')
705 parameter_s = parameter_s.encode('ascii')
697 except UnicodeEncodeError:
706 except UnicodeEncodeError:
698 print 'Python identifiers can only contain ascii characters.'
707 print 'Python identifiers can only contain ascii characters.'
699 return
708 return
700
709
701 # default namespaces to be searched
710 # default namespaces to be searched
702 def_search = ['user','builtin']
711 def_search = ['user','builtin']
703
712
704 # Process options/args
713 # Process options/args
705 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
714 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
706 opt = opts.get
715 opt = opts.get
707 shell = self.shell
716 shell = self.shell
708 psearch = shell.inspector.psearch
717 psearch = shell.inspector.psearch
709
718
710 # select case options
719 # select case options
711 if opts.has_key('i'):
720 if opts.has_key('i'):
712 ignore_case = True
721 ignore_case = True
713 elif opts.has_key('c'):
722 elif opts.has_key('c'):
714 ignore_case = False
723 ignore_case = False
715 else:
724 else:
716 ignore_case = not shell.wildcards_case_sensitive
725 ignore_case = not shell.wildcards_case_sensitive
717
726
718 # Build list of namespaces to search from user options
727 # Build list of namespaces to search from user options
719 def_search.extend(opt('s',[]))
728 def_search.extend(opt('s',[]))
720 ns_exclude = ns_exclude=opt('e',[])
729 ns_exclude = ns_exclude=opt('e',[])
721 ns_search = [nm for nm in def_search if nm not in ns_exclude]
730 ns_search = [nm for nm in def_search if nm not in ns_exclude]
722
731
723 # Call the actual search
732 # Call the actual search
724 try:
733 try:
725 psearch(args,shell.ns_table,ns_search,
734 psearch(args,shell.ns_table,ns_search,
726 show_all=opt('a'),ignore_case=ignore_case)
735 show_all=opt('a'),ignore_case=ignore_case)
727 except:
736 except:
728 shell.showtraceback()
737 shell.showtraceback()
729
738
730 @testdec.skip_doctest
739 @testdec.skip_doctest
731 def magic_who_ls(self, parameter_s=''):
740 def magic_who_ls(self, parameter_s=''):
732 """Return a sorted list of all interactive variables.
741 """Return a sorted list of all interactive variables.
733
742
734 If arguments are given, only variables of types matching these
743 If arguments are given, only variables of types matching these
735 arguments are returned.
744 arguments are returned.
736
745
737 Examples
746 Examples
738 --------
747 --------
739
748
740 Define two variables and list them with who_ls::
749 Define two variables and list them with who_ls::
741
750
742 In [1]: alpha = 123
751 In [1]: alpha = 123
743
752
744 In [2]: beta = 'test'
753 In [2]: beta = 'test'
745
754
746 In [3]: %who_ls
755 In [3]: %who_ls
747 Out[3]: ['alpha', 'beta']
756 Out[3]: ['alpha', 'beta']
748
757
749 In [4]: %who_ls int
758 In [4]: %who_ls int
750 Out[4]: ['alpha']
759 Out[4]: ['alpha']
751
760
752 In [5]: %who_ls str
761 In [5]: %who_ls str
753 Out[5]: ['beta']
762 Out[5]: ['beta']
754 """
763 """
755
764
756 user_ns = self.shell.user_ns
765 user_ns = self.shell.user_ns
757 internal_ns = self.shell.internal_ns
766 internal_ns = self.shell.internal_ns
758 user_ns_hidden = self.shell.user_ns_hidden
767 user_ns_hidden = self.shell.user_ns_hidden
759 out = [ i for i in user_ns
768 out = [ i for i in user_ns
760 if not i.startswith('_') \
769 if not i.startswith('_') \
761 and not (i in internal_ns or i in user_ns_hidden) ]
770 and not (i in internal_ns or i in user_ns_hidden) ]
762
771
763 typelist = parameter_s.split()
772 typelist = parameter_s.split()
764 if typelist:
773 if typelist:
765 typeset = set(typelist)
774 typeset = set(typelist)
766 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
775 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
767
776
768 out.sort()
777 out.sort()
769 return out
778 return out
770
779
771 @testdec.skip_doctest
780 @testdec.skip_doctest
772 def magic_who(self, parameter_s=''):
781 def magic_who(self, parameter_s=''):
773 """Print all interactive variables, with some minimal formatting.
782 """Print all interactive variables, with some minimal formatting.
774
783
775 If any arguments are given, only variables whose type matches one of
784 If any arguments are given, only variables whose type matches one of
776 these are printed. For example:
785 these are printed. For example:
777
786
778 %who function str
787 %who function str
779
788
780 will only list functions and strings, excluding all other types of
789 will only list functions and strings, excluding all other types of
781 variables. To find the proper type names, simply use type(var) at a
790 variables. To find the proper type names, simply use type(var) at a
782 command line to see how python prints type names. For example:
791 command line to see how python prints type names. For example:
783
792
784 In [1]: type('hello')\\
793 In [1]: type('hello')\\
785 Out[1]: <type 'str'>
794 Out[1]: <type 'str'>
786
795
787 indicates that the type name for strings is 'str'.
796 indicates that the type name for strings is 'str'.
788
797
789 %who always excludes executed names loaded through your configuration
798 %who always excludes executed names loaded through your configuration
790 file and things which are internal to IPython.
799 file and things which are internal to IPython.
791
800
792 This is deliberate, as typically you may load many modules and the
801 This is deliberate, as typically you may load many modules and the
793 purpose of %who is to show you only what you've manually defined.
802 purpose of %who is to show you only what you've manually defined.
794
803
795 Examples
804 Examples
796 --------
805 --------
797
806
798 Define two variables and list them with who::
807 Define two variables and list them with who::
799
808
800 In [1]: alpha = 123
809 In [1]: alpha = 123
801
810
802 In [2]: beta = 'test'
811 In [2]: beta = 'test'
803
812
804 In [3]: %who
813 In [3]: %who
805 alpha beta
814 alpha beta
806
815
807 In [4]: %who int
816 In [4]: %who int
808 alpha
817 alpha
809
818
810 In [5]: %who str
819 In [5]: %who str
811 beta
820 beta
812 """
821 """
813
822
814 varlist = self.magic_who_ls(parameter_s)
823 varlist = self.magic_who_ls(parameter_s)
815 if not varlist:
824 if not varlist:
816 if parameter_s:
825 if parameter_s:
817 print 'No variables match your requested type.'
826 print 'No variables match your requested type.'
818 else:
827 else:
819 print 'Interactive namespace is empty.'
828 print 'Interactive namespace is empty.'
820 return
829 return
821
830
822 # if we have variables, move on...
831 # if we have variables, move on...
823 count = 0
832 count = 0
824 for i in varlist:
833 for i in varlist:
825 print i+'\t',
834 print i+'\t',
826 count += 1
835 count += 1
827 if count > 8:
836 if count > 8:
828 count = 0
837 count = 0
829 print
838 print
830 print
839 print
831
840
832 @testdec.skip_doctest
841 @testdec.skip_doctest
833 def magic_whos(self, parameter_s=''):
842 def magic_whos(self, parameter_s=''):
834 """Like %who, but gives some extra information about each variable.
843 """Like %who, but gives some extra information about each variable.
835
844
836 The same type filtering of %who can be applied here.
845 The same type filtering of %who can be applied here.
837
846
838 For all variables, the type is printed. Additionally it prints:
847 For all variables, the type is printed. Additionally it prints:
839
848
840 - For {},[],(): their length.
849 - For {},[],(): their length.
841
850
842 - For numpy and Numeric arrays, a summary with shape, number of
851 - For numpy and Numeric arrays, a summary with shape, number of
843 elements, typecode and size in memory.
852 elements, typecode and size in memory.
844
853
845 - Everything else: a string representation, snipping their middle if
854 - Everything else: a string representation, snipping their middle if
846 too long.
855 too long.
847
856
848 Examples
857 Examples
849 --------
858 --------
850
859
851 Define two variables and list them with whos::
860 Define two variables and list them with whos::
852
861
853 In [1]: alpha = 123
862 In [1]: alpha = 123
854
863
855 In [2]: beta = 'test'
864 In [2]: beta = 'test'
856
865
857 In [3]: %whos
866 In [3]: %whos
858 Variable Type Data/Info
867 Variable Type Data/Info
859 --------------------------------
868 --------------------------------
860 alpha int 123
869 alpha int 123
861 beta str test
870 beta str test
862 """
871 """
863
872
864 varnames = self.magic_who_ls(parameter_s)
873 varnames = self.magic_who_ls(parameter_s)
865 if not varnames:
874 if not varnames:
866 if parameter_s:
875 if parameter_s:
867 print 'No variables match your requested type.'
876 print 'No variables match your requested type.'
868 else:
877 else:
869 print 'Interactive namespace is empty.'
878 print 'Interactive namespace is empty.'
870 return
879 return
871
880
872 # if we have variables, move on...
881 # if we have variables, move on...
873
882
874 # for these types, show len() instead of data:
883 # for these types, show len() instead of data:
875 seq_types = [types.DictType,types.ListType,types.TupleType]
884 seq_types = [types.DictType,types.ListType,types.TupleType]
876
885
877 # for numpy/Numeric arrays, display summary info
886 # for numpy/Numeric arrays, display summary info
878 try:
887 try:
879 import numpy
888 import numpy
880 except ImportError:
889 except ImportError:
881 ndarray_type = None
890 ndarray_type = None
882 else:
891 else:
883 ndarray_type = numpy.ndarray.__name__
892 ndarray_type = numpy.ndarray.__name__
884 try:
893 try:
885 import Numeric
894 import Numeric
886 except ImportError:
895 except ImportError:
887 array_type = None
896 array_type = None
888 else:
897 else:
889 array_type = Numeric.ArrayType.__name__
898 array_type = Numeric.ArrayType.__name__
890
899
891 # Find all variable names and types so we can figure out column sizes
900 # Find all variable names and types so we can figure out column sizes
892 def get_vars(i):
901 def get_vars(i):
893 return self.shell.user_ns[i]
902 return self.shell.user_ns[i]
894
903
895 # some types are well known and can be shorter
904 # some types are well known and can be shorter
896 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
905 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
897 def type_name(v):
906 def type_name(v):
898 tn = type(v).__name__
907 tn = type(v).__name__
899 return abbrevs.get(tn,tn)
908 return abbrevs.get(tn,tn)
900
909
901 varlist = map(get_vars,varnames)
910 varlist = map(get_vars,varnames)
902
911
903 typelist = []
912 typelist = []
904 for vv in varlist:
913 for vv in varlist:
905 tt = type_name(vv)
914 tt = type_name(vv)
906
915
907 if tt=='instance':
916 if tt=='instance':
908 typelist.append( abbrevs.get(str(vv.__class__),
917 typelist.append( abbrevs.get(str(vv.__class__),
909 str(vv.__class__)))
918 str(vv.__class__)))
910 else:
919 else:
911 typelist.append(tt)
920 typelist.append(tt)
912
921
913 # column labels and # of spaces as separator
922 # column labels and # of spaces as separator
914 varlabel = 'Variable'
923 varlabel = 'Variable'
915 typelabel = 'Type'
924 typelabel = 'Type'
916 datalabel = 'Data/Info'
925 datalabel = 'Data/Info'
917 colsep = 3
926 colsep = 3
918 # variable format strings
927 # variable format strings
919 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
928 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
920 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
929 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
921 aformat = "%s: %s elems, type `%s`, %s bytes"
930 aformat = "%s: %s elems, type `%s`, %s bytes"
922 # find the size of the columns to format the output nicely
931 # find the size of the columns to format the output nicely
923 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
932 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
924 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
933 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
925 # table header
934 # table header
926 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
935 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
927 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
936 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
928 # and the table itself
937 # and the table itself
929 kb = 1024
938 kb = 1024
930 Mb = 1048576 # kb**2
939 Mb = 1048576 # kb**2
931 for vname,var,vtype in zip(varnames,varlist,typelist):
940 for vname,var,vtype in zip(varnames,varlist,typelist):
932 print itpl(vformat),
941 print itpl(vformat),
933 if vtype in seq_types:
942 if vtype in seq_types:
934 print len(var)
943 print len(var)
935 elif vtype in [array_type,ndarray_type]:
944 elif vtype in [array_type,ndarray_type]:
936 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
945 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
937 if vtype==ndarray_type:
946 if vtype==ndarray_type:
938 # numpy
947 # numpy
939 vsize = var.size
948 vsize = var.size
940 vbytes = vsize*var.itemsize
949 vbytes = vsize*var.itemsize
941 vdtype = var.dtype
950 vdtype = var.dtype
942 else:
951 else:
943 # Numeric
952 # Numeric
944 vsize = Numeric.size(var)
953 vsize = Numeric.size(var)
945 vbytes = vsize*var.itemsize()
954 vbytes = vsize*var.itemsize()
946 vdtype = var.typecode()
955 vdtype = var.typecode()
947
956
948 if vbytes < 100000:
957 if vbytes < 100000:
949 print aformat % (vshape,vsize,vdtype,vbytes)
958 print aformat % (vshape,vsize,vdtype,vbytes)
950 else:
959 else:
951 print aformat % (vshape,vsize,vdtype,vbytes),
960 print aformat % (vshape,vsize,vdtype,vbytes),
952 if vbytes < Mb:
961 if vbytes < Mb:
953 print '(%s kb)' % (vbytes/kb,)
962 print '(%s kb)' % (vbytes/kb,)
954 else:
963 else:
955 print '(%s Mb)' % (vbytes/Mb,)
964 print '(%s Mb)' % (vbytes/Mb,)
956 else:
965 else:
957 try:
966 try:
958 vstr = str(var)
967 vstr = str(var)
959 except UnicodeEncodeError:
968 except UnicodeEncodeError:
960 vstr = unicode(var).encode(sys.getdefaultencoding(),
969 vstr = unicode(var).encode(sys.getdefaultencoding(),
961 'backslashreplace')
970 'backslashreplace')
962 vstr = vstr.replace('\n','\\n')
971 vstr = vstr.replace('\n','\\n')
963 if len(vstr) < 50:
972 if len(vstr) < 50:
964 print vstr
973 print vstr
965 else:
974 else:
966 printpl(vfmt_short)
975 printpl(vfmt_short)
967
976
968 def magic_reset(self, parameter_s=''):
977 def magic_reset(self, parameter_s=''):
969 """Resets the namespace by removing all names defined by the user.
978 """Resets the namespace by removing all names defined by the user.
970
979
971 Input/Output history are left around in case you need them.
980 Input/Output history are left around in case you need them.
972
981
973 Parameters
982 Parameters
974 ----------
983 ----------
975 -y : force reset without asking for confirmation.
984 -y : force reset without asking for confirmation.
976
985
977 Examples
986 Examples
978 --------
987 --------
979 In [6]: a = 1
988 In [6]: a = 1
980
989
981 In [7]: a
990 In [7]: a
982 Out[7]: 1
991 Out[7]: 1
983
992
984 In [8]: 'a' in _ip.user_ns
993 In [8]: 'a' in _ip.user_ns
985 Out[8]: True
994 Out[8]: True
986
995
987 In [9]: %reset -f
996 In [9]: %reset -f
988
997
989 In [10]: 'a' in _ip.user_ns
998 In [10]: 'a' in _ip.user_ns
990 Out[10]: False
999 Out[10]: False
991 """
1000 """
992
1001
993 if parameter_s == '-f':
1002 if parameter_s == '-f':
994 ans = True
1003 ans = True
995 else:
1004 else:
996 ans = self.shell.ask_yes_no(
1005 ans = self.shell.ask_yes_no(
997 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1006 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
998 if not ans:
1007 if not ans:
999 print 'Nothing done.'
1008 print 'Nothing done.'
1000 return
1009 return
1001 user_ns = self.shell.user_ns
1010 user_ns = self.shell.user_ns
1002 for i in self.magic_who_ls():
1011 for i in self.magic_who_ls():
1003 del(user_ns[i])
1012 del(user_ns[i])
1004
1013
1005 # Also flush the private list of module references kept for script
1014 # Also flush the private list of module references kept for script
1006 # execution protection
1015 # execution protection
1007 self.shell.clear_main_mod_cache()
1016 self.shell.clear_main_mod_cache()
1008
1017
1009 def magic_reset_selective(self, parameter_s=''):
1018 def magic_reset_selective(self, parameter_s=''):
1010 """Resets the namespace by removing names defined by the user.
1019 """Resets the namespace by removing names defined by the user.
1011
1020
1012 Input/Output history are left around in case you need them.
1021 Input/Output history are left around in case you need them.
1013
1022
1014 %reset_selective [-f] regex
1023 %reset_selective [-f] regex
1015
1024
1016 No action is taken if regex is not included
1025 No action is taken if regex is not included
1017
1026
1018 Options
1027 Options
1019 -f : force reset without asking for confirmation.
1028 -f : force reset without asking for confirmation.
1020
1029
1021 Examples
1030 Examples
1022 --------
1031 --------
1023
1032
1024 We first fully reset the namespace so your output looks identical to
1033 We first fully reset the namespace so your output looks identical to
1025 this example for pedagogical reasons; in practice you do not need a
1034 this example for pedagogical reasons; in practice you do not need a
1026 full reset.
1035 full reset.
1027
1036
1028 In [1]: %reset -f
1037 In [1]: %reset -f
1029
1038
1030 Now, with a clean namespace we can make a few variables and use
1039 Now, with a clean namespace we can make a few variables and use
1031 %reset_selective to only delete names that match our regexp:
1040 %reset_selective to only delete names that match our regexp:
1032
1041
1033 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1042 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1034
1043
1035 In [3]: who_ls
1044 In [3]: who_ls
1036 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1045 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1037
1046
1038 In [4]: %reset_selective -f b[2-3]m
1047 In [4]: %reset_selective -f b[2-3]m
1039
1048
1040 In [5]: who_ls
1049 In [5]: who_ls
1041 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1050 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1042
1051
1043 In [6]: %reset_selective -f d
1052 In [6]: %reset_selective -f d
1044
1053
1045 In [7]: who_ls
1054 In [7]: who_ls
1046 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1055 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1047
1056
1048 In [8]: %reset_selective -f c
1057 In [8]: %reset_selective -f c
1049
1058
1050 In [9]: who_ls
1059 In [9]: who_ls
1051 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1060 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1052
1061
1053 In [10]: %reset_selective -f b
1062 In [10]: %reset_selective -f b
1054
1063
1055 In [11]: who_ls
1064 In [11]: who_ls
1056 Out[11]: ['a']
1065 Out[11]: ['a']
1057 """
1066 """
1058
1067
1059 opts, regex = self.parse_options(parameter_s,'f')
1068 opts, regex = self.parse_options(parameter_s,'f')
1060
1069
1061 if opts.has_key('f'):
1070 if opts.has_key('f'):
1062 ans = True
1071 ans = True
1063 else:
1072 else:
1064 ans = self.shell.ask_yes_no(
1073 ans = self.shell.ask_yes_no(
1065 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1074 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1066 if not ans:
1075 if not ans:
1067 print 'Nothing done.'
1076 print 'Nothing done.'
1068 return
1077 return
1069 user_ns = self.shell.user_ns
1078 user_ns = self.shell.user_ns
1070 if not regex:
1079 if not regex:
1071 print 'No regex pattern specified. Nothing done.'
1080 print 'No regex pattern specified. Nothing done.'
1072 return
1081 return
1073 else:
1082 else:
1074 try:
1083 try:
1075 m = re.compile(regex)
1084 m = re.compile(regex)
1076 except TypeError:
1085 except TypeError:
1077 raise TypeError('regex must be a string or compiled pattern')
1086 raise TypeError('regex must be a string or compiled pattern')
1078 for i in self.magic_who_ls():
1087 for i in self.magic_who_ls():
1079 if m.search(i):
1088 if m.search(i):
1080 del(user_ns[i])
1089 del(user_ns[i])
1081
1090
1082 def magic_logstart(self,parameter_s=''):
1091 def magic_logstart(self,parameter_s=''):
1083 """Start logging anywhere in a session.
1092 """Start logging anywhere in a session.
1084
1093
1085 %logstart [-o|-r|-t] [log_name [log_mode]]
1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1086
1095
1087 If no name is given, it defaults to a file named 'ipython_log.py' in your
1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1088 current directory, in 'rotate' mode (see below).
1097 current directory, in 'rotate' mode (see below).
1089
1098
1090 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1091 history up to that point and then continues logging.
1100 history up to that point and then continues logging.
1092
1101
1093 %logstart takes a second optional parameter: logging mode. This can be one
1102 %logstart takes a second optional parameter: logging mode. This can be one
1094 of (note that the modes are given unquoted):\\
1103 of (note that the modes are given unquoted):\\
1095 append: well, that says it.\\
1104 append: well, that says it.\\
1096 backup: rename (if exists) to name~ and start name.\\
1105 backup: rename (if exists) to name~ and start name.\\
1097 global: single logfile in your home dir, appended to.\\
1106 global: single logfile in your home dir, appended to.\\
1098 over : overwrite existing log.\\
1107 over : overwrite existing log.\\
1099 rotate: create rotating logs name.1~, name.2~, etc.
1108 rotate: create rotating logs name.1~, name.2~, etc.
1100
1109
1101 Options:
1110 Options:
1102
1111
1103 -o: log also IPython's output. In this mode, all commands which
1112 -o: log also IPython's output. In this mode, all commands which
1104 generate an Out[NN] prompt are recorded to the logfile, right after
1113 generate an Out[NN] prompt are recorded to the logfile, right after
1105 their corresponding input line. The output lines are always
1114 their corresponding input line. The output lines are always
1106 prepended with a '#[Out]# ' marker, so that the log remains valid
1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1107 Python code.
1116 Python code.
1108
1117
1109 Since this marker is always the same, filtering only the output from
1118 Since this marker is always the same, filtering only the output from
1110 a log is very easy, using for example a simple awk call:
1119 a log is very easy, using for example a simple awk call:
1111
1120
1112 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1113
1122
1114 -r: log 'raw' input. Normally, IPython's logs contain the processed
1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1115 input, so that user lines are logged in their final form, converted
1124 input, so that user lines are logged in their final form, converted
1116 into valid Python. For example, %Exit is logged as
1125 into valid Python. For example, %Exit is logged as
1117 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1118 exactly as typed, with no transformations applied.
1127 exactly as typed, with no transformations applied.
1119
1128
1120 -t: put timestamps before each input line logged (these are put in
1129 -t: put timestamps before each input line logged (these are put in
1121 comments)."""
1130 comments)."""
1122
1131
1123 opts,par = self.parse_options(parameter_s,'ort')
1132 opts,par = self.parse_options(parameter_s,'ort')
1124 log_output = 'o' in opts
1133 log_output = 'o' in opts
1125 log_raw_input = 'r' in opts
1134 log_raw_input = 'r' in opts
1126 timestamp = 't' in opts
1135 timestamp = 't' in opts
1127
1136
1128 logger = self.shell.logger
1137 logger = self.shell.logger
1129
1138
1130 # if no args are given, the defaults set in the logger constructor by
1139 # if no args are given, the defaults set in the logger constructor by
1131 # ipytohn remain valid
1140 # ipytohn remain valid
1132 if par:
1141 if par:
1133 try:
1142 try:
1134 logfname,logmode = par.split()
1143 logfname,logmode = par.split()
1135 except:
1144 except:
1136 logfname = par
1145 logfname = par
1137 logmode = 'backup'
1146 logmode = 'backup'
1138 else:
1147 else:
1139 logfname = logger.logfname
1148 logfname = logger.logfname
1140 logmode = logger.logmode
1149 logmode = logger.logmode
1141 # put logfname into rc struct as if it had been called on the command
1150 # put logfname into rc struct as if it had been called on the command
1142 # line, so it ends up saved in the log header Save it in case we need
1151 # line, so it ends up saved in the log header Save it in case we need
1143 # to restore it...
1152 # to restore it...
1144 old_logfile = self.shell.logfile
1153 old_logfile = self.shell.logfile
1145 if logfname:
1154 if logfname:
1146 logfname = os.path.expanduser(logfname)
1155 logfname = os.path.expanduser(logfname)
1147 self.shell.logfile = logfname
1156 self.shell.logfile = logfname
1148
1157
1149 loghead = '# IPython log file\n\n'
1158 loghead = '# IPython log file\n\n'
1150 try:
1159 try:
1151 started = logger.logstart(logfname,loghead,logmode,
1160 started = logger.logstart(logfname,loghead,logmode,
1152 log_output,timestamp,log_raw_input)
1161 log_output,timestamp,log_raw_input)
1153 except:
1162 except:
1154 self.shell.logfile = old_logfile
1163 self.shell.logfile = old_logfile
1155 warn("Couldn't start log: %s" % sys.exc_info()[1])
1164 warn("Couldn't start log: %s" % sys.exc_info()[1])
1156 else:
1165 else:
1157 # log input history up to this point, optionally interleaving
1166 # log input history up to this point, optionally interleaving
1158 # output if requested
1167 # output if requested
1159
1168
1160 if timestamp:
1169 if timestamp:
1161 # disable timestamping for the previous history, since we've
1170 # disable timestamping for the previous history, since we've
1162 # lost those already (no time machine here).
1171 # lost those already (no time machine here).
1163 logger.timestamp = False
1172 logger.timestamp = False
1164
1173
1165 if log_raw_input:
1174 if log_raw_input:
1166 input_hist = self.shell.history_manager.input_hist_raw
1175 input_hist = self.shell.history_manager.input_hist_raw
1167 else:
1176 else:
1168 input_hist = self.shell.history_manager.input_hist_parsed
1177 input_hist = self.shell.history_manager.input_hist_parsed
1169
1178
1170 if log_output:
1179 if log_output:
1171 log_write = logger.log_write
1180 log_write = logger.log_write
1172 output_hist = self.shell.history_manager.output_hist
1181 output_hist = self.shell.history_manager.output_hist
1173 for n in range(1,len(input_hist)-1):
1182 for n in range(1,len(input_hist)-1):
1174 log_write(input_hist[n].rstrip())
1183 log_write(input_hist[n].rstrip())
1175 if n in output_hist:
1184 if n in output_hist:
1176 log_write(repr(output_hist[n]),'output')
1185 log_write(repr(output_hist[n]),'output')
1177 else:
1186 else:
1178 logger.log_write(''.join(input_hist[1:]))
1187 logger.log_write(''.join(input_hist[1:]))
1179 if timestamp:
1188 if timestamp:
1180 # re-enable timestamping
1189 # re-enable timestamping
1181 logger.timestamp = True
1190 logger.timestamp = True
1182
1191
1183 print ('Activating auto-logging. '
1192 print ('Activating auto-logging. '
1184 'Current session state plus future input saved.')
1193 'Current session state plus future input saved.')
1185 logger.logstate()
1194 logger.logstate()
1186
1195
1187 def magic_logstop(self,parameter_s=''):
1196 def magic_logstop(self,parameter_s=''):
1188 """Fully stop logging and close log file.
1197 """Fully stop logging and close log file.
1189
1198
1190 In order to start logging again, a new %logstart call needs to be made,
1199 In order to start logging again, a new %logstart call needs to be made,
1191 possibly (though not necessarily) with a new filename, mode and other
1200 possibly (though not necessarily) with a new filename, mode and other
1192 options."""
1201 options."""
1193 self.logger.logstop()
1202 self.logger.logstop()
1194
1203
1195 def magic_logoff(self,parameter_s=''):
1204 def magic_logoff(self,parameter_s=''):
1196 """Temporarily stop logging.
1205 """Temporarily stop logging.
1197
1206
1198 You must have previously started logging."""
1207 You must have previously started logging."""
1199 self.shell.logger.switch_log(0)
1208 self.shell.logger.switch_log(0)
1200
1209
1201 def magic_logon(self,parameter_s=''):
1210 def magic_logon(self,parameter_s=''):
1202 """Restart logging.
1211 """Restart logging.
1203
1212
1204 This function is for restarting logging which you've temporarily
1213 This function is for restarting logging which you've temporarily
1205 stopped with %logoff. For starting logging for the first time, you
1214 stopped with %logoff. For starting logging for the first time, you
1206 must use the %logstart function, which allows you to specify an
1215 must use the %logstart function, which allows you to specify an
1207 optional log filename."""
1216 optional log filename."""
1208
1217
1209 self.shell.logger.switch_log(1)
1218 self.shell.logger.switch_log(1)
1210
1219
1211 def magic_logstate(self,parameter_s=''):
1220 def magic_logstate(self,parameter_s=''):
1212 """Print the status of the logging system."""
1221 """Print the status of the logging system."""
1213
1222
1214 self.shell.logger.logstate()
1223 self.shell.logger.logstate()
1215
1224
1216 def magic_pdb(self, parameter_s=''):
1225 def magic_pdb(self, parameter_s=''):
1217 """Control the automatic calling of the pdb interactive debugger.
1226 """Control the automatic calling of the pdb interactive debugger.
1218
1227
1219 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1228 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1220 argument it works as a toggle.
1229 argument it works as a toggle.
1221
1230
1222 When an exception is triggered, IPython can optionally call the
1231 When an exception is triggered, IPython can optionally call the
1223 interactive pdb debugger after the traceback printout. %pdb toggles
1232 interactive pdb debugger after the traceback printout. %pdb toggles
1224 this feature on and off.
1233 this feature on and off.
1225
1234
1226 The initial state of this feature is set in your ipythonrc
1235 The initial state of this feature is set in your ipythonrc
1227 configuration file (the variable is called 'pdb').
1236 configuration file (the variable is called 'pdb').
1228
1237
1229 If you want to just activate the debugger AFTER an exception has fired,
1238 If you want to just activate the debugger AFTER an exception has fired,
1230 without having to type '%pdb on' and rerunning your code, you can use
1239 without having to type '%pdb on' and rerunning your code, you can use
1231 the %debug magic."""
1240 the %debug magic."""
1232
1241
1233 par = parameter_s.strip().lower()
1242 par = parameter_s.strip().lower()
1234
1243
1235 if par:
1244 if par:
1236 try:
1245 try:
1237 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1246 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1238 except KeyError:
1247 except KeyError:
1239 print ('Incorrect argument. Use on/1, off/0, '
1248 print ('Incorrect argument. Use on/1, off/0, '
1240 'or nothing for a toggle.')
1249 'or nothing for a toggle.')
1241 return
1250 return
1242 else:
1251 else:
1243 # toggle
1252 # toggle
1244 new_pdb = not self.shell.call_pdb
1253 new_pdb = not self.shell.call_pdb
1245
1254
1246 # set on the shell
1255 # set on the shell
1247 self.shell.call_pdb = new_pdb
1256 self.shell.call_pdb = new_pdb
1248 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1257 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1249
1258
1250 def magic_debug(self, parameter_s=''):
1259 def magic_debug(self, parameter_s=''):
1251 """Activate the interactive debugger in post-mortem mode.
1260 """Activate the interactive debugger in post-mortem mode.
1252
1261
1253 If an exception has just occurred, this lets you inspect its stack
1262 If an exception has just occurred, this lets you inspect its stack
1254 frames interactively. Note that this will always work only on the last
1263 frames interactively. Note that this will always work only on the last
1255 traceback that occurred, so you must call this quickly after an
1264 traceback that occurred, so you must call this quickly after an
1256 exception that you wish to inspect has fired, because if another one
1265 exception that you wish to inspect has fired, because if another one
1257 occurs, it clobbers the previous one.
1266 occurs, it clobbers the previous one.
1258
1267
1259 If you want IPython to automatically do this on every exception, see
1268 If you want IPython to automatically do this on every exception, see
1260 the %pdb magic for more details.
1269 the %pdb magic for more details.
1261 """
1270 """
1262 self.shell.debugger(force=True)
1271 self.shell.debugger(force=True)
1263
1272
1264 @testdec.skip_doctest
1273 @testdec.skip_doctest
1265 def magic_prun(self, parameter_s ='',user_mode=1,
1274 def magic_prun(self, parameter_s ='',user_mode=1,
1266 opts=None,arg_lst=None,prog_ns=None):
1275 opts=None,arg_lst=None,prog_ns=None):
1267
1276
1268 """Run a statement through the python code profiler.
1277 """Run a statement through the python code profiler.
1269
1278
1270 Usage:
1279 Usage:
1271 %prun [options] statement
1280 %prun [options] statement
1272
1281
1273 The given statement (which doesn't require quote marks) is run via the
1282 The given statement (which doesn't require quote marks) is run via the
1274 python profiler in a manner similar to the profile.run() function.
1283 python profiler in a manner similar to the profile.run() function.
1275 Namespaces are internally managed to work correctly; profile.run
1284 Namespaces are internally managed to work correctly; profile.run
1276 cannot be used in IPython because it makes certain assumptions about
1285 cannot be used in IPython because it makes certain assumptions about
1277 namespaces which do not hold under IPython.
1286 namespaces which do not hold under IPython.
1278
1287
1279 Options:
1288 Options:
1280
1289
1281 -l <limit>: you can place restrictions on what or how much of the
1290 -l <limit>: you can place restrictions on what or how much of the
1282 profile gets printed. The limit value can be:
1291 profile gets printed. The limit value can be:
1283
1292
1284 * A string: only information for function names containing this string
1293 * A string: only information for function names containing this string
1285 is printed.
1294 is printed.
1286
1295
1287 * An integer: only these many lines are printed.
1296 * An integer: only these many lines are printed.
1288
1297
1289 * A float (between 0 and 1): this fraction of the report is printed
1298 * A float (between 0 and 1): this fraction of the report is printed
1290 (for example, use a limit of 0.4 to see the topmost 40% only).
1299 (for example, use a limit of 0.4 to see the topmost 40% only).
1291
1300
1292 You can combine several limits with repeated use of the option. For
1301 You can combine several limits with repeated use of the option. For
1293 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1302 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1294 information about class constructors.
1303 information about class constructors.
1295
1304
1296 -r: return the pstats.Stats object generated by the profiling. This
1305 -r: return the pstats.Stats object generated by the profiling. This
1297 object has all the information about the profile in it, and you can
1306 object has all the information about the profile in it, and you can
1298 later use it for further analysis or in other functions.
1307 later use it for further analysis or in other functions.
1299
1308
1300 -s <key>: sort profile by given key. You can provide more than one key
1309 -s <key>: sort profile by given key. You can provide more than one key
1301 by using the option several times: '-s key1 -s key2 -s key3...'. The
1310 by using the option several times: '-s key1 -s key2 -s key3...'. The
1302 default sorting key is 'time'.
1311 default sorting key is 'time'.
1303
1312
1304 The following is copied verbatim from the profile documentation
1313 The following is copied verbatim from the profile documentation
1305 referenced below:
1314 referenced below:
1306
1315
1307 When more than one key is provided, additional keys are used as
1316 When more than one key is provided, additional keys are used as
1308 secondary criteria when the there is equality in all keys selected
1317 secondary criteria when the there is equality in all keys selected
1309 before them.
1318 before them.
1310
1319
1311 Abbreviations can be used for any key names, as long as the
1320 Abbreviations can be used for any key names, as long as the
1312 abbreviation is unambiguous. The following are the keys currently
1321 abbreviation is unambiguous. The following are the keys currently
1313 defined:
1322 defined:
1314
1323
1315 Valid Arg Meaning
1324 Valid Arg Meaning
1316 "calls" call count
1325 "calls" call count
1317 "cumulative" cumulative time
1326 "cumulative" cumulative time
1318 "file" file name
1327 "file" file name
1319 "module" file name
1328 "module" file name
1320 "pcalls" primitive call count
1329 "pcalls" primitive call count
1321 "line" line number
1330 "line" line number
1322 "name" function name
1331 "name" function name
1323 "nfl" name/file/line
1332 "nfl" name/file/line
1324 "stdname" standard name
1333 "stdname" standard name
1325 "time" internal time
1334 "time" internal time
1326
1335
1327 Note that all sorts on statistics are in descending order (placing
1336 Note that all sorts on statistics are in descending order (placing
1328 most time consuming items first), where as name, file, and line number
1337 most time consuming items first), where as name, file, and line number
1329 searches are in ascending order (i.e., alphabetical). The subtle
1338 searches are in ascending order (i.e., alphabetical). The subtle
1330 distinction between "nfl" and "stdname" is that the standard name is a
1339 distinction between "nfl" and "stdname" is that the standard name is a
1331 sort of the name as printed, which means that the embedded line
1340 sort of the name as printed, which means that the embedded line
1332 numbers get compared in an odd way. For example, lines 3, 20, and 40
1341 numbers get compared in an odd way. For example, lines 3, 20, and 40
1333 would (if the file names were the same) appear in the string order
1342 would (if the file names were the same) appear in the string order
1334 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1343 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1335 line numbers. In fact, sort_stats("nfl") is the same as
1344 line numbers. In fact, sort_stats("nfl") is the same as
1336 sort_stats("name", "file", "line").
1345 sort_stats("name", "file", "line").
1337
1346
1338 -T <filename>: save profile results as shown on screen to a text
1347 -T <filename>: save profile results as shown on screen to a text
1339 file. The profile is still shown on screen.
1348 file. The profile is still shown on screen.
1340
1349
1341 -D <filename>: save (via dump_stats) profile statistics to given
1350 -D <filename>: save (via dump_stats) profile statistics to given
1342 filename. This data is in a format understod by the pstats module, and
1351 filename. This data is in a format understod by the pstats module, and
1343 is generated by a call to the dump_stats() method of profile
1352 is generated by a call to the dump_stats() method of profile
1344 objects. The profile is still shown on screen.
1353 objects. The profile is still shown on screen.
1345
1354
1346 If you want to run complete programs under the profiler's control, use
1355 If you want to run complete programs under the profiler's control, use
1347 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1356 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1348 contains profiler specific options as described here.
1357 contains profiler specific options as described here.
1349
1358
1350 You can read the complete documentation for the profile module with::
1359 You can read the complete documentation for the profile module with::
1351
1360
1352 In [1]: import profile; profile.help()
1361 In [1]: import profile; profile.help()
1353 """
1362 """
1354
1363
1355 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1364 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1356 # protect user quote marks
1365 # protect user quote marks
1357 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1366 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1358
1367
1359 if user_mode: # regular user call
1368 if user_mode: # regular user call
1360 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1369 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1361 list_all=1)
1370 list_all=1)
1362 namespace = self.shell.user_ns
1371 namespace = self.shell.user_ns
1363 else: # called to run a program by %run -p
1372 else: # called to run a program by %run -p
1364 try:
1373 try:
1365 filename = get_py_filename(arg_lst[0])
1374 filename = get_py_filename(arg_lst[0])
1366 except IOError,msg:
1375 except IOError,msg:
1367 error(msg)
1376 error(msg)
1368 return
1377 return
1369
1378
1370 arg_str = 'execfile(filename,prog_ns)'
1379 arg_str = 'execfile(filename,prog_ns)'
1371 namespace = locals()
1380 namespace = locals()
1372
1381
1373 opts.merge(opts_def)
1382 opts.merge(opts_def)
1374
1383
1375 prof = profile.Profile()
1384 prof = profile.Profile()
1376 try:
1385 try:
1377 prof = prof.runctx(arg_str,namespace,namespace)
1386 prof = prof.runctx(arg_str,namespace,namespace)
1378 sys_exit = ''
1387 sys_exit = ''
1379 except SystemExit:
1388 except SystemExit:
1380 sys_exit = """*** SystemExit exception caught in code being profiled."""
1389 sys_exit = """*** SystemExit exception caught in code being profiled."""
1381
1390
1382 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1391 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1383
1392
1384 lims = opts.l
1393 lims = opts.l
1385 if lims:
1394 if lims:
1386 lims = [] # rebuild lims with ints/floats/strings
1395 lims = [] # rebuild lims with ints/floats/strings
1387 for lim in opts.l:
1396 for lim in opts.l:
1388 try:
1397 try:
1389 lims.append(int(lim))
1398 lims.append(int(lim))
1390 except ValueError:
1399 except ValueError:
1391 try:
1400 try:
1392 lims.append(float(lim))
1401 lims.append(float(lim))
1393 except ValueError:
1402 except ValueError:
1394 lims.append(lim)
1403 lims.append(lim)
1395
1404
1396 # Trap output.
1405 # Trap output.
1397 stdout_trap = StringIO()
1406 stdout_trap = StringIO()
1398
1407
1399 if hasattr(stats,'stream'):
1408 if hasattr(stats,'stream'):
1400 # In newer versions of python, the stats object has a 'stream'
1409 # In newer versions of python, the stats object has a 'stream'
1401 # attribute to write into.
1410 # attribute to write into.
1402 stats.stream = stdout_trap
1411 stats.stream = stdout_trap
1403 stats.print_stats(*lims)
1412 stats.print_stats(*lims)
1404 else:
1413 else:
1405 # For older versions, we manually redirect stdout during printing
1414 # For older versions, we manually redirect stdout during printing
1406 sys_stdout = sys.stdout
1415 sys_stdout = sys.stdout
1407 try:
1416 try:
1408 sys.stdout = stdout_trap
1417 sys.stdout = stdout_trap
1409 stats.print_stats(*lims)
1418 stats.print_stats(*lims)
1410 finally:
1419 finally:
1411 sys.stdout = sys_stdout
1420 sys.stdout = sys_stdout
1412
1421
1413 output = stdout_trap.getvalue()
1422 output = stdout_trap.getvalue()
1414 output = output.rstrip()
1423 output = output.rstrip()
1415
1424
1416 page.page(output)
1425 page.page(output)
1417 print sys_exit,
1426 print sys_exit,
1418
1427
1419 dump_file = opts.D[0]
1428 dump_file = opts.D[0]
1420 text_file = opts.T[0]
1429 text_file = opts.T[0]
1421 if dump_file:
1430 if dump_file:
1422 prof.dump_stats(dump_file)
1431 prof.dump_stats(dump_file)
1423 print '\n*** Profile stats marshalled to file',\
1432 print '\n*** Profile stats marshalled to file',\
1424 `dump_file`+'.',sys_exit
1433 `dump_file`+'.',sys_exit
1425 if text_file:
1434 if text_file:
1426 pfile = file(text_file,'w')
1435 pfile = file(text_file,'w')
1427 pfile.write(output)
1436 pfile.write(output)
1428 pfile.close()
1437 pfile.close()
1429 print '\n*** Profile printout saved to text file',\
1438 print '\n*** Profile printout saved to text file',\
1430 `text_file`+'.',sys_exit
1439 `text_file`+'.',sys_exit
1431
1440
1432 if opts.has_key('r'):
1441 if opts.has_key('r'):
1433 return stats
1442 return stats
1434 else:
1443 else:
1435 return None
1444 return None
1436
1445
1437 @testdec.skip_doctest
1446 @testdec.skip_doctest
1438 def magic_run(self, parameter_s ='',runner=None,
1447 def magic_run(self, parameter_s ='',runner=None,
1439 file_finder=get_py_filename):
1448 file_finder=get_py_filename):
1440 """Run the named file inside IPython as a program.
1449 """Run the named file inside IPython as a program.
1441
1450
1442 Usage:\\
1451 Usage:\\
1443 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1452 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1444
1453
1445 Parameters after the filename are passed as command-line arguments to
1454 Parameters after the filename are passed as command-line arguments to
1446 the program (put in sys.argv). Then, control returns to IPython's
1455 the program (put in sys.argv). Then, control returns to IPython's
1447 prompt.
1456 prompt.
1448
1457
1449 This is similar to running at a system prompt:\\
1458 This is similar to running at a system prompt:\\
1450 $ python file args\\
1459 $ python file args\\
1451 but with the advantage of giving you IPython's tracebacks, and of
1460 but with the advantage of giving you IPython's tracebacks, and of
1452 loading all variables into your interactive namespace for further use
1461 loading all variables into your interactive namespace for further use
1453 (unless -p is used, see below).
1462 (unless -p is used, see below).
1454
1463
1455 The file is executed in a namespace initially consisting only of
1464 The file is executed in a namespace initially consisting only of
1456 __name__=='__main__' and sys.argv constructed as indicated. It thus
1465 __name__=='__main__' and sys.argv constructed as indicated. It thus
1457 sees its environment as if it were being run as a stand-alone program
1466 sees its environment as if it were being run as a stand-alone program
1458 (except for sharing global objects such as previously imported
1467 (except for sharing global objects such as previously imported
1459 modules). But after execution, the IPython interactive namespace gets
1468 modules). But after execution, the IPython interactive namespace gets
1460 updated with all variables defined in the program (except for __name__
1469 updated with all variables defined in the program (except for __name__
1461 and sys.argv). This allows for very convenient loading of code for
1470 and sys.argv). This allows for very convenient loading of code for
1462 interactive work, while giving each program a 'clean sheet' to run in.
1471 interactive work, while giving each program a 'clean sheet' to run in.
1463
1472
1464 Options:
1473 Options:
1465
1474
1466 -n: __name__ is NOT set to '__main__', but to the running file's name
1475 -n: __name__ is NOT set to '__main__', but to the running file's name
1467 without extension (as python does under import). This allows running
1476 without extension (as python does under import). This allows running
1468 scripts and reloading the definitions in them without calling code
1477 scripts and reloading the definitions in them without calling code
1469 protected by an ' if __name__ == "__main__" ' clause.
1478 protected by an ' if __name__ == "__main__" ' clause.
1470
1479
1471 -i: run the file in IPython's namespace instead of an empty one. This
1480 -i: run the file in IPython's namespace instead of an empty one. This
1472 is useful if you are experimenting with code written in a text editor
1481 is useful if you are experimenting with code written in a text editor
1473 which depends on variables defined interactively.
1482 which depends on variables defined interactively.
1474
1483
1475 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1484 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1476 being run. This is particularly useful if IPython is being used to
1485 being run. This is particularly useful if IPython is being used to
1477 run unittests, which always exit with a sys.exit() call. In such
1486 run unittests, which always exit with a sys.exit() call. In such
1478 cases you are interested in the output of the test results, not in
1487 cases you are interested in the output of the test results, not in
1479 seeing a traceback of the unittest module.
1488 seeing a traceback of the unittest module.
1480
1489
1481 -t: print timing information at the end of the run. IPython will give
1490 -t: print timing information at the end of the run. IPython will give
1482 you an estimated CPU time consumption for your script, which under
1491 you an estimated CPU time consumption for your script, which under
1483 Unix uses the resource module to avoid the wraparound problems of
1492 Unix uses the resource module to avoid the wraparound problems of
1484 time.clock(). Under Unix, an estimate of time spent on system tasks
1493 time.clock(). Under Unix, an estimate of time spent on system tasks
1485 is also given (for Windows platforms this is reported as 0.0).
1494 is also given (for Windows platforms this is reported as 0.0).
1486
1495
1487 If -t is given, an additional -N<N> option can be given, where <N>
1496 If -t is given, an additional -N<N> option can be given, where <N>
1488 must be an integer indicating how many times you want the script to
1497 must be an integer indicating how many times you want the script to
1489 run. The final timing report will include total and per run results.
1498 run. The final timing report will include total and per run results.
1490
1499
1491 For example (testing the script uniq_stable.py):
1500 For example (testing the script uniq_stable.py):
1492
1501
1493 In [1]: run -t uniq_stable
1502 In [1]: run -t uniq_stable
1494
1503
1495 IPython CPU timings (estimated):\\
1504 IPython CPU timings (estimated):\\
1496 User : 0.19597 s.\\
1505 User : 0.19597 s.\\
1497 System: 0.0 s.\\
1506 System: 0.0 s.\\
1498
1507
1499 In [2]: run -t -N5 uniq_stable
1508 In [2]: run -t -N5 uniq_stable
1500
1509
1501 IPython CPU timings (estimated):\\
1510 IPython CPU timings (estimated):\\
1502 Total runs performed: 5\\
1511 Total runs performed: 5\\
1503 Times : Total Per run\\
1512 Times : Total Per run\\
1504 User : 0.910862 s, 0.1821724 s.\\
1513 User : 0.910862 s, 0.1821724 s.\\
1505 System: 0.0 s, 0.0 s.
1514 System: 0.0 s, 0.0 s.
1506
1515
1507 -d: run your program under the control of pdb, the Python debugger.
1516 -d: run your program under the control of pdb, the Python debugger.
1508 This allows you to execute your program step by step, watch variables,
1517 This allows you to execute your program step by step, watch variables,
1509 etc. Internally, what IPython does is similar to calling:
1518 etc. Internally, what IPython does is similar to calling:
1510
1519
1511 pdb.run('execfile("YOURFILENAME")')
1520 pdb.run('execfile("YOURFILENAME")')
1512
1521
1513 with a breakpoint set on line 1 of your file. You can change the line
1522 with a breakpoint set on line 1 of your file. You can change the line
1514 number for this automatic breakpoint to be <N> by using the -bN option
1523 number for this automatic breakpoint to be <N> by using the -bN option
1515 (where N must be an integer). For example:
1524 (where N must be an integer). For example:
1516
1525
1517 %run -d -b40 myscript
1526 %run -d -b40 myscript
1518
1527
1519 will set the first breakpoint at line 40 in myscript.py. Note that
1528 will set the first breakpoint at line 40 in myscript.py. Note that
1520 the first breakpoint must be set on a line which actually does
1529 the first breakpoint must be set on a line which actually does
1521 something (not a comment or docstring) for it to stop execution.
1530 something (not a comment or docstring) for it to stop execution.
1522
1531
1523 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1532 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1524 first enter 'c' (without qoutes) to start execution up to the first
1533 first enter 'c' (without qoutes) to start execution up to the first
1525 breakpoint.
1534 breakpoint.
1526
1535
1527 Entering 'help' gives information about the use of the debugger. You
1536 Entering 'help' gives information about the use of the debugger. You
1528 can easily see pdb's full documentation with "import pdb;pdb.help()"
1537 can easily see pdb's full documentation with "import pdb;pdb.help()"
1529 at a prompt.
1538 at a prompt.
1530
1539
1531 -p: run program under the control of the Python profiler module (which
1540 -p: run program under the control of the Python profiler module (which
1532 prints a detailed report of execution times, function calls, etc).
1541 prints a detailed report of execution times, function calls, etc).
1533
1542
1534 You can pass other options after -p which affect the behavior of the
1543 You can pass other options after -p which affect the behavior of the
1535 profiler itself. See the docs for %prun for details.
1544 profiler itself. See the docs for %prun for details.
1536
1545
1537 In this mode, the program's variables do NOT propagate back to the
1546 In this mode, the program's variables do NOT propagate back to the
1538 IPython interactive namespace (because they remain in the namespace
1547 IPython interactive namespace (because they remain in the namespace
1539 where the profiler executes them).
1548 where the profiler executes them).
1540
1549
1541 Internally this triggers a call to %prun, see its documentation for
1550 Internally this triggers a call to %prun, see its documentation for
1542 details on the options available specifically for profiling.
1551 details on the options available specifically for profiling.
1543
1552
1544 There is one special usage for which the text above doesn't apply:
1553 There is one special usage for which the text above doesn't apply:
1545 if the filename ends with .ipy, the file is run as ipython script,
1554 if the filename ends with .ipy, the file is run as ipython script,
1546 just as if the commands were written on IPython prompt.
1555 just as if the commands were written on IPython prompt.
1547 """
1556 """
1548
1557
1549 # get arguments and set sys.argv for program to be run.
1558 # get arguments and set sys.argv for program to be run.
1550 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1559 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1551 mode='list',list_all=1)
1560 mode='list',list_all=1)
1552
1561
1553 try:
1562 try:
1554 filename = file_finder(arg_lst[0])
1563 filename = file_finder(arg_lst[0])
1555 except IndexError:
1564 except IndexError:
1556 warn('you must provide at least a filename.')
1565 warn('you must provide at least a filename.')
1557 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1566 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1558 return
1567 return
1559 except IOError,msg:
1568 except IOError,msg:
1560 error(msg)
1569 error(msg)
1561 return
1570 return
1562
1571
1563 if filename.lower().endswith('.ipy'):
1572 if filename.lower().endswith('.ipy'):
1564 self.shell.safe_execfile_ipy(filename)
1573 self.shell.safe_execfile_ipy(filename)
1565 return
1574 return
1566
1575
1567 # Control the response to exit() calls made by the script being run
1576 # Control the response to exit() calls made by the script being run
1568 exit_ignore = opts.has_key('e')
1577 exit_ignore = opts.has_key('e')
1569
1578
1570 # Make sure that the running script gets a proper sys.argv as if it
1579 # Make sure that the running script gets a proper sys.argv as if it
1571 # were run from a system shell.
1580 # were run from a system shell.
1572 save_argv = sys.argv # save it for later restoring
1581 save_argv = sys.argv # save it for later restoring
1573 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1582 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1574
1583
1575 if opts.has_key('i'):
1584 if opts.has_key('i'):
1576 # Run in user's interactive namespace
1585 # Run in user's interactive namespace
1577 prog_ns = self.shell.user_ns
1586 prog_ns = self.shell.user_ns
1578 __name__save = self.shell.user_ns['__name__']
1587 __name__save = self.shell.user_ns['__name__']
1579 prog_ns['__name__'] = '__main__'
1588 prog_ns['__name__'] = '__main__'
1580 main_mod = self.shell.new_main_mod(prog_ns)
1589 main_mod = self.shell.new_main_mod(prog_ns)
1581 else:
1590 else:
1582 # Run in a fresh, empty namespace
1591 # Run in a fresh, empty namespace
1583 if opts.has_key('n'):
1592 if opts.has_key('n'):
1584 name = os.path.splitext(os.path.basename(filename))[0]
1593 name = os.path.splitext(os.path.basename(filename))[0]
1585 else:
1594 else:
1586 name = '__main__'
1595 name = '__main__'
1587
1596
1588 main_mod = self.shell.new_main_mod()
1597 main_mod = self.shell.new_main_mod()
1589 prog_ns = main_mod.__dict__
1598 prog_ns = main_mod.__dict__
1590 prog_ns['__name__'] = name
1599 prog_ns['__name__'] = name
1591
1600
1592 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1601 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1593 # set the __file__ global in the script's namespace
1602 # set the __file__ global in the script's namespace
1594 prog_ns['__file__'] = filename
1603 prog_ns['__file__'] = filename
1595
1604
1596 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1605 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1597 # that, if we overwrite __main__, we replace it at the end
1606 # that, if we overwrite __main__, we replace it at the end
1598 main_mod_name = prog_ns['__name__']
1607 main_mod_name = prog_ns['__name__']
1599
1608
1600 if main_mod_name == '__main__':
1609 if main_mod_name == '__main__':
1601 restore_main = sys.modules['__main__']
1610 restore_main = sys.modules['__main__']
1602 else:
1611 else:
1603 restore_main = False
1612 restore_main = False
1604
1613
1605 # This needs to be undone at the end to prevent holding references to
1614 # This needs to be undone at the end to prevent holding references to
1606 # every single object ever created.
1615 # every single object ever created.
1607 sys.modules[main_mod_name] = main_mod
1616 sys.modules[main_mod_name] = main_mod
1608
1617
1609 stats = None
1618 stats = None
1610 try:
1619 try:
1611 self.shell.save_history()
1620 self.shell.save_history()
1612
1621
1613 if opts.has_key('p'):
1622 if opts.has_key('p'):
1614 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1623 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1615 else:
1624 else:
1616 if opts.has_key('d'):
1625 if opts.has_key('d'):
1617 deb = debugger.Pdb(self.shell.colors)
1626 deb = debugger.Pdb(self.shell.colors)
1618 # reset Breakpoint state, which is moronically kept
1627 # reset Breakpoint state, which is moronically kept
1619 # in a class
1628 # in a class
1620 bdb.Breakpoint.next = 1
1629 bdb.Breakpoint.next = 1
1621 bdb.Breakpoint.bplist = {}
1630 bdb.Breakpoint.bplist = {}
1622 bdb.Breakpoint.bpbynumber = [None]
1631 bdb.Breakpoint.bpbynumber = [None]
1623 # Set an initial breakpoint to stop execution
1632 # Set an initial breakpoint to stop execution
1624 maxtries = 10
1633 maxtries = 10
1625 bp = int(opts.get('b',[1])[0])
1634 bp = int(opts.get('b',[1])[0])
1626 checkline = deb.checkline(filename,bp)
1635 checkline = deb.checkline(filename,bp)
1627 if not checkline:
1636 if not checkline:
1628 for bp in range(bp+1,bp+maxtries+1):
1637 for bp in range(bp+1,bp+maxtries+1):
1629 if deb.checkline(filename,bp):
1638 if deb.checkline(filename,bp):
1630 break
1639 break
1631 else:
1640 else:
1632 msg = ("\nI failed to find a valid line to set "
1641 msg = ("\nI failed to find a valid line to set "
1633 "a breakpoint\n"
1642 "a breakpoint\n"
1634 "after trying up to line: %s.\n"
1643 "after trying up to line: %s.\n"
1635 "Please set a valid breakpoint manually "
1644 "Please set a valid breakpoint manually "
1636 "with the -b option." % bp)
1645 "with the -b option." % bp)
1637 error(msg)
1646 error(msg)
1638 return
1647 return
1639 # if we find a good linenumber, set the breakpoint
1648 # if we find a good linenumber, set the breakpoint
1640 deb.do_break('%s:%s' % (filename,bp))
1649 deb.do_break('%s:%s' % (filename,bp))
1641 # Start file run
1650 # Start file run
1642 print "NOTE: Enter 'c' at the",
1651 print "NOTE: Enter 'c' at the",
1643 print "%s prompt to start your script." % deb.prompt
1652 print "%s prompt to start your script." % deb.prompt
1644 try:
1653 try:
1645 deb.run('execfile("%s")' % filename,prog_ns)
1654 deb.run('execfile("%s")' % filename,prog_ns)
1646
1655
1647 except:
1656 except:
1648 etype, value, tb = sys.exc_info()
1657 etype, value, tb = sys.exc_info()
1649 # Skip three frames in the traceback: the %run one,
1658 # Skip three frames in the traceback: the %run one,
1650 # one inside bdb.py, and the command-line typed by the
1659 # one inside bdb.py, and the command-line typed by the
1651 # user (run by exec in pdb itself).
1660 # user (run by exec in pdb itself).
1652 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1661 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1653 else:
1662 else:
1654 if runner is None:
1663 if runner is None:
1655 runner = self.shell.safe_execfile
1664 runner = self.shell.safe_execfile
1656 if opts.has_key('t'):
1665 if opts.has_key('t'):
1657 # timed execution
1666 # timed execution
1658 try:
1667 try:
1659 nruns = int(opts['N'][0])
1668 nruns = int(opts['N'][0])
1660 if nruns < 1:
1669 if nruns < 1:
1661 error('Number of runs must be >=1')
1670 error('Number of runs must be >=1')
1662 return
1671 return
1663 except (KeyError):
1672 except (KeyError):
1664 nruns = 1
1673 nruns = 1
1665 if nruns == 1:
1674 if nruns == 1:
1666 t0 = clock2()
1675 t0 = clock2()
1667 runner(filename,prog_ns,prog_ns,
1676 runner(filename,prog_ns,prog_ns,
1668 exit_ignore=exit_ignore)
1677 exit_ignore=exit_ignore)
1669 t1 = clock2()
1678 t1 = clock2()
1670 t_usr = t1[0]-t0[0]
1679 t_usr = t1[0]-t0[0]
1671 t_sys = t1[1]-t0[1]
1680 t_sys = t1[1]-t0[1]
1672 print "\nIPython CPU timings (estimated):"
1681 print "\nIPython CPU timings (estimated):"
1673 print " User : %10s s." % t_usr
1682 print " User : %10s s." % t_usr
1674 print " System: %10s s." % t_sys
1683 print " System: %10s s." % t_sys
1675 else:
1684 else:
1676 runs = range(nruns)
1685 runs = range(nruns)
1677 t0 = clock2()
1686 t0 = clock2()
1678 for nr in runs:
1687 for nr in runs:
1679 runner(filename,prog_ns,prog_ns,
1688 runner(filename,prog_ns,prog_ns,
1680 exit_ignore=exit_ignore)
1689 exit_ignore=exit_ignore)
1681 t1 = clock2()
1690 t1 = clock2()
1682 t_usr = t1[0]-t0[0]
1691 t_usr = t1[0]-t0[0]
1683 t_sys = t1[1]-t0[1]
1692 t_sys = t1[1]-t0[1]
1684 print "\nIPython CPU timings (estimated):"
1693 print "\nIPython CPU timings (estimated):"
1685 print "Total runs performed:",nruns
1694 print "Total runs performed:",nruns
1686 print " Times : %10s %10s" % ('Total','Per run')
1695 print " Times : %10s %10s" % ('Total','Per run')
1687 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1696 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1688 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1697 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1689
1698
1690 else:
1699 else:
1691 # regular execution
1700 # regular execution
1692 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1701 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1693
1702
1694 if opts.has_key('i'):
1703 if opts.has_key('i'):
1695 self.shell.user_ns['__name__'] = __name__save
1704 self.shell.user_ns['__name__'] = __name__save
1696 else:
1705 else:
1697 # The shell MUST hold a reference to prog_ns so after %run
1706 # The shell MUST hold a reference to prog_ns so after %run
1698 # exits, the python deletion mechanism doesn't zero it out
1707 # exits, the python deletion mechanism doesn't zero it out
1699 # (leaving dangling references).
1708 # (leaving dangling references).
1700 self.shell.cache_main_mod(prog_ns,filename)
1709 self.shell.cache_main_mod(prog_ns,filename)
1701 # update IPython interactive namespace
1710 # update IPython interactive namespace
1702
1711
1703 # Some forms of read errors on the file may mean the
1712 # Some forms of read errors on the file may mean the
1704 # __name__ key was never set; using pop we don't have to
1713 # __name__ key was never set; using pop we don't have to
1705 # worry about a possible KeyError.
1714 # worry about a possible KeyError.
1706 prog_ns.pop('__name__', None)
1715 prog_ns.pop('__name__', None)
1707
1716
1708 self.shell.user_ns.update(prog_ns)
1717 self.shell.user_ns.update(prog_ns)
1709 finally:
1718 finally:
1710 # It's a bit of a mystery why, but __builtins__ can change from
1719 # It's a bit of a mystery why, but __builtins__ can change from
1711 # being a module to becoming a dict missing some key data after
1720 # being a module to becoming a dict missing some key data after
1712 # %run. As best I can see, this is NOT something IPython is doing
1721 # %run. As best I can see, this is NOT something IPython is doing
1713 # at all, and similar problems have been reported before:
1722 # at all, and similar problems have been reported before:
1714 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1723 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1715 # Since this seems to be done by the interpreter itself, the best
1724 # Since this seems to be done by the interpreter itself, the best
1716 # we can do is to at least restore __builtins__ for the user on
1725 # we can do is to at least restore __builtins__ for the user on
1717 # exit.
1726 # exit.
1718 self.shell.user_ns['__builtins__'] = __builtin__
1727 self.shell.user_ns['__builtins__'] = __builtin__
1719
1728
1720 # Ensure key global structures are restored
1729 # Ensure key global structures are restored
1721 sys.argv = save_argv
1730 sys.argv = save_argv
1722 if restore_main:
1731 if restore_main:
1723 sys.modules['__main__'] = restore_main
1732 sys.modules['__main__'] = restore_main
1724 else:
1733 else:
1725 # Remove from sys.modules the reference to main_mod we'd
1734 # Remove from sys.modules the reference to main_mod we'd
1726 # added. Otherwise it will trap references to objects
1735 # added. Otherwise it will trap references to objects
1727 # contained therein.
1736 # contained therein.
1728 del sys.modules[main_mod_name]
1737 del sys.modules[main_mod_name]
1729
1738
1730 self.shell.reload_history()
1739 self.shell.reload_history()
1731
1740
1732 return stats
1741 return stats
1733
1742
1734 @testdec.skip_doctest
1743 @testdec.skip_doctest
1735 def magic_timeit(self, parameter_s =''):
1744 def magic_timeit(self, parameter_s =''):
1736 """Time execution of a Python statement or expression
1745 """Time execution of a Python statement or expression
1737
1746
1738 Usage:\\
1747 Usage:\\
1739 %timeit [-n<N> -r<R> [-t|-c]] statement
1748 %timeit [-n<N> -r<R> [-t|-c]] statement
1740
1749
1741 Time execution of a Python statement or expression using the timeit
1750 Time execution of a Python statement or expression using the timeit
1742 module.
1751 module.
1743
1752
1744 Options:
1753 Options:
1745 -n<N>: execute the given statement <N> times in a loop. If this value
1754 -n<N>: execute the given statement <N> times in a loop. If this value
1746 is not given, a fitting value is chosen.
1755 is not given, a fitting value is chosen.
1747
1756
1748 -r<R>: repeat the loop iteration <R> times and take the best result.
1757 -r<R>: repeat the loop iteration <R> times and take the best result.
1749 Default: 3
1758 Default: 3
1750
1759
1751 -t: use time.time to measure the time, which is the default on Unix.
1760 -t: use time.time to measure the time, which is the default on Unix.
1752 This function measures wall time.
1761 This function measures wall time.
1753
1762
1754 -c: use time.clock to measure the time, which is the default on
1763 -c: use time.clock to measure the time, which is the default on
1755 Windows and measures wall time. On Unix, resource.getrusage is used
1764 Windows and measures wall time. On Unix, resource.getrusage is used
1756 instead and returns the CPU user time.
1765 instead and returns the CPU user time.
1757
1766
1758 -p<P>: use a precision of <P> digits to display the timing result.
1767 -p<P>: use a precision of <P> digits to display the timing result.
1759 Default: 3
1768 Default: 3
1760
1769
1761
1770
1762 Examples:
1771 Examples:
1763
1772
1764 In [1]: %timeit pass
1773 In [1]: %timeit pass
1765 10000000 loops, best of 3: 53.3 ns per loop
1774 10000000 loops, best of 3: 53.3 ns per loop
1766
1775
1767 In [2]: u = None
1776 In [2]: u = None
1768
1777
1769 In [3]: %timeit u is None
1778 In [3]: %timeit u is None
1770 10000000 loops, best of 3: 184 ns per loop
1779 10000000 loops, best of 3: 184 ns per loop
1771
1780
1772 In [4]: %timeit -r 4 u == None
1781 In [4]: %timeit -r 4 u == None
1773 1000000 loops, best of 4: 242 ns per loop
1782 1000000 loops, best of 4: 242 ns per loop
1774
1783
1775 In [5]: import time
1784 In [5]: import time
1776
1785
1777 In [6]: %timeit -n1 time.sleep(2)
1786 In [6]: %timeit -n1 time.sleep(2)
1778 1 loops, best of 3: 2 s per loop
1787 1 loops, best of 3: 2 s per loop
1779
1788
1780
1789
1781 The times reported by %timeit will be slightly higher than those
1790 The times reported by %timeit will be slightly higher than those
1782 reported by the timeit.py script when variables are accessed. This is
1791 reported by the timeit.py script when variables are accessed. This is
1783 due to the fact that %timeit executes the statement in the namespace
1792 due to the fact that %timeit executes the statement in the namespace
1784 of the shell, compared with timeit.py, which uses a single setup
1793 of the shell, compared with timeit.py, which uses a single setup
1785 statement to import function or create variables. Generally, the bias
1794 statement to import function or create variables. Generally, the bias
1786 does not matter as long as results from timeit.py are not mixed with
1795 does not matter as long as results from timeit.py are not mixed with
1787 those from %timeit."""
1796 those from %timeit."""
1788
1797
1789 import timeit
1798 import timeit
1790 import math
1799 import math
1791
1800
1792 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1801 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1793 # certain terminals. Until we figure out a robust way of
1802 # certain terminals. Until we figure out a robust way of
1794 # auto-detecting if the terminal can deal with it, use plain 'us' for
1803 # auto-detecting if the terminal can deal with it, use plain 'us' for
1795 # microseconds. I am really NOT happy about disabling the proper
1804 # microseconds. I am really NOT happy about disabling the proper
1796 # 'micro' prefix, but crashing is worse... If anyone knows what the
1805 # 'micro' prefix, but crashing is worse... If anyone knows what the
1797 # right solution for this is, I'm all ears...
1806 # right solution for this is, I'm all ears...
1798 #
1807 #
1799 # Note: using
1808 # Note: using
1800 #
1809 #
1801 # s = u'\xb5'
1810 # s = u'\xb5'
1802 # s.encode(sys.getdefaultencoding())
1811 # s.encode(sys.getdefaultencoding())
1803 #
1812 #
1804 # is not sufficient, as I've seen terminals where that fails but
1813 # is not sufficient, as I've seen terminals where that fails but
1805 # print s
1814 # print s
1806 #
1815 #
1807 # succeeds
1816 # succeeds
1808 #
1817 #
1809 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1818 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1810
1819
1811 #units = [u"s", u"ms",u'\xb5',"ns"]
1820 #units = [u"s", u"ms",u'\xb5',"ns"]
1812 units = [u"s", u"ms",u'us',"ns"]
1821 units = [u"s", u"ms",u'us',"ns"]
1813
1822
1814 scaling = [1, 1e3, 1e6, 1e9]
1823 scaling = [1, 1e3, 1e6, 1e9]
1815
1824
1816 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1825 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1817 posix=False)
1826 posix=False)
1818 if stmt == "":
1827 if stmt == "":
1819 return
1828 return
1820 timefunc = timeit.default_timer
1829 timefunc = timeit.default_timer
1821 number = int(getattr(opts, "n", 0))
1830 number = int(getattr(opts, "n", 0))
1822 repeat = int(getattr(opts, "r", timeit.default_repeat))
1831 repeat = int(getattr(opts, "r", timeit.default_repeat))
1823 precision = int(getattr(opts, "p", 3))
1832 precision = int(getattr(opts, "p", 3))
1824 if hasattr(opts, "t"):
1833 if hasattr(opts, "t"):
1825 timefunc = time.time
1834 timefunc = time.time
1826 if hasattr(opts, "c"):
1835 if hasattr(opts, "c"):
1827 timefunc = clock
1836 timefunc = clock
1828
1837
1829 timer = timeit.Timer(timer=timefunc)
1838 timer = timeit.Timer(timer=timefunc)
1830 # this code has tight coupling to the inner workings of timeit.Timer,
1839 # this code has tight coupling to the inner workings of timeit.Timer,
1831 # but is there a better way to achieve that the code stmt has access
1840 # but is there a better way to achieve that the code stmt has access
1832 # to the shell namespace?
1841 # to the shell namespace?
1833
1842
1834 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1843 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1835 'setup': "pass"}
1844 'setup': "pass"}
1836 # Track compilation time so it can be reported if too long
1845 # Track compilation time so it can be reported if too long
1837 # Minimum time above which compilation time will be reported
1846 # Minimum time above which compilation time will be reported
1838 tc_min = 0.1
1847 tc_min = 0.1
1839
1848
1840 t0 = clock()
1849 t0 = clock()
1841 code = compile(src, "<magic-timeit>", "exec")
1850 code = compile(src, "<magic-timeit>", "exec")
1842 tc = clock()-t0
1851 tc = clock()-t0
1843
1852
1844 ns = {}
1853 ns = {}
1845 exec code in self.shell.user_ns, ns
1854 exec code in self.shell.user_ns, ns
1846 timer.inner = ns["inner"]
1855 timer.inner = ns["inner"]
1847
1856
1848 if number == 0:
1857 if number == 0:
1849 # determine number so that 0.2 <= total time < 2.0
1858 # determine number so that 0.2 <= total time < 2.0
1850 number = 1
1859 number = 1
1851 for i in range(1, 10):
1860 for i in range(1, 10):
1852 if timer.timeit(number) >= 0.2:
1861 if timer.timeit(number) >= 0.2:
1853 break
1862 break
1854 number *= 10
1863 number *= 10
1855
1864
1856 best = min(timer.repeat(repeat, number)) / number
1865 best = min(timer.repeat(repeat, number)) / number
1857
1866
1858 if best > 0.0 and best < 1000.0:
1867 if best > 0.0 and best < 1000.0:
1859 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1868 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1860 elif best >= 1000.0:
1869 elif best >= 1000.0:
1861 order = 0
1870 order = 0
1862 else:
1871 else:
1863 order = 3
1872 order = 3
1864 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1873 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1865 precision,
1874 precision,
1866 best * scaling[order],
1875 best * scaling[order],
1867 units[order])
1876 units[order])
1868 if tc > tc_min:
1877 if tc > tc_min:
1869 print "Compiler time: %.2f s" % tc
1878 print "Compiler time: %.2f s" % tc
1870
1879
1871 @testdec.skip_doctest
1880 @testdec.skip_doctest
1872 def magic_time(self,parameter_s = ''):
1881 def magic_time(self,parameter_s = ''):
1873 """Time execution of a Python statement or expression.
1882 """Time execution of a Python statement or expression.
1874
1883
1875 The CPU and wall clock times are printed, and the value of the
1884 The CPU and wall clock times are printed, and the value of the
1876 expression (if any) is returned. Note that under Win32, system time
1885 expression (if any) is returned. Note that under Win32, system time
1877 is always reported as 0, since it can not be measured.
1886 is always reported as 0, since it can not be measured.
1878
1887
1879 This function provides very basic timing functionality. In Python
1888 This function provides very basic timing functionality. In Python
1880 2.3, the timeit module offers more control and sophistication, so this
1889 2.3, the timeit module offers more control and sophistication, so this
1881 could be rewritten to use it (patches welcome).
1890 could be rewritten to use it (patches welcome).
1882
1891
1883 Some examples:
1892 Some examples:
1884
1893
1885 In [1]: time 2**128
1894 In [1]: time 2**128
1886 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1895 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1887 Wall time: 0.00
1896 Wall time: 0.00
1888 Out[1]: 340282366920938463463374607431768211456L
1897 Out[1]: 340282366920938463463374607431768211456L
1889
1898
1890 In [2]: n = 1000000
1899 In [2]: n = 1000000
1891
1900
1892 In [3]: time sum(range(n))
1901 In [3]: time sum(range(n))
1893 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1902 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1894 Wall time: 1.37
1903 Wall time: 1.37
1895 Out[3]: 499999500000L
1904 Out[3]: 499999500000L
1896
1905
1897 In [4]: time print 'hello world'
1906 In [4]: time print 'hello world'
1898 hello world
1907 hello world
1899 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1900 Wall time: 0.00
1909 Wall time: 0.00
1901
1910
1902 Note that the time needed by Python to compile the given expression
1911 Note that the time needed by Python to compile the given expression
1903 will be reported if it is more than 0.1s. In this example, the
1912 will be reported if it is more than 0.1s. In this example, the
1904 actual exponentiation is done by Python at compilation time, so while
1913 actual exponentiation is done by Python at compilation time, so while
1905 the expression can take a noticeable amount of time to compute, that
1914 the expression can take a noticeable amount of time to compute, that
1906 time is purely due to the compilation:
1915 time is purely due to the compilation:
1907
1916
1908 In [5]: time 3**9999;
1917 In [5]: time 3**9999;
1909 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1910 Wall time: 0.00 s
1919 Wall time: 0.00 s
1911
1920
1912 In [6]: time 3**999999;
1921 In [6]: time 3**999999;
1913 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1914 Wall time: 0.00 s
1923 Wall time: 0.00 s
1915 Compiler : 0.78 s
1924 Compiler : 0.78 s
1916 """
1925 """
1917
1926
1918 # fail immediately if the given expression can't be compiled
1927 # fail immediately if the given expression can't be compiled
1919
1928
1920 expr = self.shell.prefilter(parameter_s,False)
1929 expr = self.shell.prefilter(parameter_s,False)
1921
1930
1922 # Minimum time above which compilation time will be reported
1931 # Minimum time above which compilation time will be reported
1923 tc_min = 0.1
1932 tc_min = 0.1
1924
1933
1925 try:
1934 try:
1926 mode = 'eval'
1935 mode = 'eval'
1927 t0 = clock()
1936 t0 = clock()
1928 code = compile(expr,'<timed eval>',mode)
1937 code = compile(expr,'<timed eval>',mode)
1929 tc = clock()-t0
1938 tc = clock()-t0
1930 except SyntaxError:
1939 except SyntaxError:
1931 mode = 'exec'
1940 mode = 'exec'
1932 t0 = clock()
1941 t0 = clock()
1933 code = compile(expr,'<timed exec>',mode)
1942 code = compile(expr,'<timed exec>',mode)
1934 tc = clock()-t0
1943 tc = clock()-t0
1935 # skew measurement as little as possible
1944 # skew measurement as little as possible
1936 glob = self.shell.user_ns
1945 glob = self.shell.user_ns
1937 clk = clock2
1946 clk = clock2
1938 wtime = time.time
1947 wtime = time.time
1939 # time execution
1948 # time execution
1940 wall_st = wtime()
1949 wall_st = wtime()
1941 if mode=='eval':
1950 if mode=='eval':
1942 st = clk()
1951 st = clk()
1943 out = eval(code,glob)
1952 out = eval(code,glob)
1944 end = clk()
1953 end = clk()
1945 else:
1954 else:
1946 st = clk()
1955 st = clk()
1947 exec code in glob
1956 exec code in glob
1948 end = clk()
1957 end = clk()
1949 out = None
1958 out = None
1950 wall_end = wtime()
1959 wall_end = wtime()
1951 # Compute actual times and report
1960 # Compute actual times and report
1952 wall_time = wall_end-wall_st
1961 wall_time = wall_end-wall_st
1953 cpu_user = end[0]-st[0]
1962 cpu_user = end[0]-st[0]
1954 cpu_sys = end[1]-st[1]
1963 cpu_sys = end[1]-st[1]
1955 cpu_tot = cpu_user+cpu_sys
1964 cpu_tot = cpu_user+cpu_sys
1956 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1965 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1957 (cpu_user,cpu_sys,cpu_tot)
1966 (cpu_user,cpu_sys,cpu_tot)
1958 print "Wall time: %.2f s" % wall_time
1967 print "Wall time: %.2f s" % wall_time
1959 if tc > tc_min:
1968 if tc > tc_min:
1960 print "Compiler : %.2f s" % tc
1969 print "Compiler : %.2f s" % tc
1961 return out
1970 return out
1962
1971
1963 @testdec.skip_doctest
1972 @testdec.skip_doctest
1964 def magic_macro(self,parameter_s = ''):
1973 def magic_macro(self,parameter_s = ''):
1965 """Define a set of input lines as a macro for future re-execution.
1974 """Define a set of input lines as a macro for future re-execution.
1966
1975
1967 Usage:\\
1976 Usage:\\
1968 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1977 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1969
1978
1970 Options:
1979 Options:
1971
1980
1972 -r: use 'raw' input. By default, the 'processed' history is used,
1981 -r: use 'raw' input. By default, the 'processed' history is used,
1973 so that magics are loaded in their transformed version to valid
1982 so that magics are loaded in their transformed version to valid
1974 Python. If this option is given, the raw input as typed as the
1983 Python. If this option is given, the raw input as typed as the
1975 command line is used instead.
1984 command line is used instead.
1976
1985
1977 This will define a global variable called `name` which is a string
1986 This will define a global variable called `name` which is a string
1978 made of joining the slices and lines you specify (n1,n2,... numbers
1987 made of joining the slices and lines you specify (n1,n2,... numbers
1979 above) from your input history into a single string. This variable
1988 above) from your input history into a single string. This variable
1980 acts like an automatic function which re-executes those lines as if
1989 acts like an automatic function which re-executes those lines as if
1981 you had typed them. You just type 'name' at the prompt and the code
1990 you had typed them. You just type 'name' at the prompt and the code
1982 executes.
1991 executes.
1983
1992
1984 The notation for indicating number ranges is: n1-n2 means 'use line
1993 The notation for indicating number ranges is: n1-n2 means 'use line
1985 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1994 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1986 using the lines numbered 5,6 and 7.
1995 using the lines numbered 5,6 and 7.
1987
1996
1988 Note: as a 'hidden' feature, you can also use traditional python slice
1997 Note: as a 'hidden' feature, you can also use traditional python slice
1989 notation, where N:M means numbers N through M-1.
1998 notation, where N:M means numbers N through M-1.
1990
1999
1991 For example, if your history contains (%hist prints it):
2000 For example, if your history contains (%hist prints it):
1992
2001
1993 44: x=1
2002 44: x=1
1994 45: y=3
2003 45: y=3
1995 46: z=x+y
2004 46: z=x+y
1996 47: print x
2005 47: print x
1997 48: a=5
2006 48: a=5
1998 49: print 'x',x,'y',y
2007 49: print 'x',x,'y',y
1999
2008
2000 you can create a macro with lines 44 through 47 (included) and line 49
2009 you can create a macro with lines 44 through 47 (included) and line 49
2001 called my_macro with:
2010 called my_macro with:
2002
2011
2003 In [55]: %macro my_macro 44-47 49
2012 In [55]: %macro my_macro 44-47 49
2004
2013
2005 Now, typing `my_macro` (without quotes) will re-execute all this code
2014 Now, typing `my_macro` (without quotes) will re-execute all this code
2006 in one pass.
2015 in one pass.
2007
2016
2008 You don't need to give the line-numbers in order, and any given line
2017 You don't need to give the line-numbers in order, and any given line
2009 number can appear multiple times. You can assemble macros with any
2018 number can appear multiple times. You can assemble macros with any
2010 lines from your input history in any order.
2019 lines from your input history in any order.
2011
2020
2012 The macro is a simple object which holds its value in an attribute,
2021 The macro is a simple object which holds its value in an attribute,
2013 but IPython's display system checks for macros and executes them as
2022 but IPython's display system checks for macros and executes them as
2014 code instead of printing them when you type their name.
2023 code instead of printing them when you type their name.
2015
2024
2016 You can view a macro's contents by explicitly printing it with:
2025 You can view a macro's contents by explicitly printing it with:
2017
2026
2018 'print macro_name'.
2027 'print macro_name'.
2019
2028
2020 For one-off cases which DON'T contain magic function calls in them you
2029 For one-off cases which DON'T contain magic function calls in them you
2021 can obtain similar results by explicitly executing slices from your
2030 can obtain similar results by explicitly executing slices from your
2022 input history with:
2031 input history with:
2023
2032
2024 In [60]: exec In[44:48]+In[49]"""
2033 In [60]: exec In[44:48]+In[49]"""
2025
2034
2026 opts,args = self.parse_options(parameter_s,'r',mode='list')
2035 opts,args = self.parse_options(parameter_s,'r',mode='list')
2027 if not args:
2036 if not args:
2028 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2037 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2029 macs.sort()
2038 macs.sort()
2030 return macs
2039 return macs
2031 if len(args) == 1:
2040 if len(args) == 1:
2032 raise UsageError(
2041 raise UsageError(
2033 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2042 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2034 name,ranges = args[0], args[1:]
2043 name,ranges = args[0], args[1:]
2035
2044
2036 #print 'rng',ranges # dbg
2045 #print 'rng',ranges # dbg
2037 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2046 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2038 macro = Macro(lines)
2047 macro = Macro(lines)
2039 self.shell.define_macro(name, macro)
2048 self.shell.define_macro(name, macro)
2040 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2049 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2041 print 'Macro contents:'
2050 print 'Macro contents:'
2042 print macro,
2051 print macro,
2043
2052
2044 def magic_save(self,parameter_s = ''):
2053 def magic_save(self,parameter_s = ''):
2045 """Save a set of lines to a given filename.
2054 """Save a set of lines to a given filename.
2046
2055
2047 Usage:\\
2056 Usage:\\
2048 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2057 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2049
2058
2050 Options:
2059 Options:
2051
2060
2052 -r: use 'raw' input. By default, the 'processed' history is used,
2061 -r: use 'raw' input. By default, the 'processed' history is used,
2053 so that magics are loaded in their transformed version to valid
2062 so that magics are loaded in their transformed version to valid
2054 Python. If this option is given, the raw input as typed as the
2063 Python. If this option is given, the raw input as typed as the
2055 command line is used instead.
2064 command line is used instead.
2056
2065
2057 This function uses the same syntax as %macro for line extraction, but
2066 This function uses the same syntax as %macro for line extraction, but
2058 instead of creating a macro it saves the resulting string to the
2067 instead of creating a macro it saves the resulting string to the
2059 filename you specify.
2068 filename you specify.
2060
2069
2061 It adds a '.py' extension to the file if you don't do so yourself, and
2070 It adds a '.py' extension to the file if you don't do so yourself, and
2062 it asks for confirmation before overwriting existing files."""
2071 it asks for confirmation before overwriting existing files."""
2063
2072
2064 opts,args = self.parse_options(parameter_s,'r',mode='list')
2073 opts,args = self.parse_options(parameter_s,'r',mode='list')
2065 fname,ranges = args[0], args[1:]
2074 fname,ranges = args[0], args[1:]
2066 if not fname.endswith('.py'):
2075 if not fname.endswith('.py'):
2067 fname += '.py'
2076 fname += '.py'
2068 if os.path.isfile(fname):
2077 if os.path.isfile(fname):
2069 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2078 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2070 if ans.lower() not in ['y','yes']:
2079 if ans.lower() not in ['y','yes']:
2071 print 'Operation cancelled.'
2080 print 'Operation cancelled.'
2072 return
2081 return
2073 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2082 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2074 f = file(fname,'w')
2083 f = file(fname,'w')
2075 f.write(cmds)
2084 f.write(cmds)
2076 f.close()
2085 f.close()
2077 print 'The following commands were written to file `%s`:' % fname
2086 print 'The following commands were written to file `%s`:' % fname
2078 print cmds
2087 print cmds
2079
2088
2080 def _edit_macro(self,mname,macro):
2089 def _edit_macro(self,mname,macro):
2081 """open an editor with the macro data in a file"""
2090 """open an editor with the macro data in a file"""
2082 filename = self.shell.mktempfile(macro.value)
2091 filename = self.shell.mktempfile(macro.value)
2083 self.shell.hooks.editor(filename)
2092 self.shell.hooks.editor(filename)
2084
2093
2085 # and make a new macro object, to replace the old one
2094 # and make a new macro object, to replace the old one
2086 mfile = open(filename)
2095 mfile = open(filename)
2087 mvalue = mfile.read()
2096 mvalue = mfile.read()
2088 mfile.close()
2097 mfile.close()
2089 self.shell.user_ns[mname] = Macro(mvalue)
2098 self.shell.user_ns[mname] = Macro(mvalue)
2090
2099
2091 def magic_ed(self,parameter_s=''):
2100 def magic_ed(self,parameter_s=''):
2092 """Alias to %edit."""
2101 """Alias to %edit."""
2093 return self.magic_edit(parameter_s)
2102 return self.magic_edit(parameter_s)
2094
2103
2095 @testdec.skip_doctest
2104 @testdec.skip_doctest
2096 def magic_edit(self,parameter_s='',last_call=['','']):
2105 def magic_edit(self,parameter_s='',last_call=['','']):
2097 """Bring up an editor and execute the resulting code.
2106 """Bring up an editor and execute the resulting code.
2098
2107
2099 Usage:
2108 Usage:
2100 %edit [options] [args]
2109 %edit [options] [args]
2101
2110
2102 %edit runs IPython's editor hook. The default version of this hook is
2111 %edit runs IPython's editor hook. The default version of this hook is
2103 set to call the __IPYTHON__.rc.editor command. This is read from your
2112 set to call the __IPYTHON__.rc.editor command. This is read from your
2104 environment variable $EDITOR. If this isn't found, it will default to
2113 environment variable $EDITOR. If this isn't found, it will default to
2105 vi under Linux/Unix and to notepad under Windows. See the end of this
2114 vi under Linux/Unix and to notepad under Windows. See the end of this
2106 docstring for how to change the editor hook.
2115 docstring for how to change the editor hook.
2107
2116
2108 You can also set the value of this editor via the command line option
2117 You can also set the value of this editor via the command line option
2109 '-editor' or in your ipythonrc file. This is useful if you wish to use
2118 '-editor' or in your ipythonrc file. This is useful if you wish to use
2110 specifically for IPython an editor different from your typical default
2119 specifically for IPython an editor different from your typical default
2111 (and for Windows users who typically don't set environment variables).
2120 (and for Windows users who typically don't set environment variables).
2112
2121
2113 This command allows you to conveniently edit multi-line code right in
2122 This command allows you to conveniently edit multi-line code right in
2114 your IPython session.
2123 your IPython session.
2115
2124
2116 If called without arguments, %edit opens up an empty editor with a
2125 If called without arguments, %edit opens up an empty editor with a
2117 temporary file and will execute the contents of this file when you
2126 temporary file and will execute the contents of this file when you
2118 close it (don't forget to save it!).
2127 close it (don't forget to save it!).
2119
2128
2120
2129
2121 Options:
2130 Options:
2122
2131
2123 -n <number>: open the editor at a specified line number. By default,
2132 -n <number>: open the editor at a specified line number. By default,
2124 the IPython editor hook uses the unix syntax 'editor +N filename', but
2133 the IPython editor hook uses the unix syntax 'editor +N filename', but
2125 you can configure this by providing your own modified hook if your
2134 you can configure this by providing your own modified hook if your
2126 favorite editor supports line-number specifications with a different
2135 favorite editor supports line-number specifications with a different
2127 syntax.
2136 syntax.
2128
2137
2129 -p: this will call the editor with the same data as the previous time
2138 -p: this will call the editor with the same data as the previous time
2130 it was used, regardless of how long ago (in your current session) it
2139 it was used, regardless of how long ago (in your current session) it
2131 was.
2140 was.
2132
2141
2133 -r: use 'raw' input. This option only applies to input taken from the
2142 -r: use 'raw' input. This option only applies to input taken from the
2134 user's history. By default, the 'processed' history is used, so that
2143 user's history. By default, the 'processed' history is used, so that
2135 magics are loaded in their transformed version to valid Python. If
2144 magics are loaded in their transformed version to valid Python. If
2136 this option is given, the raw input as typed as the command line is
2145 this option is given, the raw input as typed as the command line is
2137 used instead. When you exit the editor, it will be executed by
2146 used instead. When you exit the editor, it will be executed by
2138 IPython's own processor.
2147 IPython's own processor.
2139
2148
2140 -x: do not execute the edited code immediately upon exit. This is
2149 -x: do not execute the edited code immediately upon exit. This is
2141 mainly useful if you are editing programs which need to be called with
2150 mainly useful if you are editing programs which need to be called with
2142 command line arguments, which you can then do using %run.
2151 command line arguments, which you can then do using %run.
2143
2152
2144
2153
2145 Arguments:
2154 Arguments:
2146
2155
2147 If arguments are given, the following possibilites exist:
2156 If arguments are given, the following possibilites exist:
2148
2157
2149 - The arguments are numbers or pairs of colon-separated numbers (like
2158 - The arguments are numbers or pairs of colon-separated numbers (like
2150 1 4:8 9). These are interpreted as lines of previous input to be
2159 1 4:8 9). These are interpreted as lines of previous input to be
2151 loaded into the editor. The syntax is the same of the %macro command.
2160 loaded into the editor. The syntax is the same of the %macro command.
2152
2161
2153 - If the argument doesn't start with a number, it is evaluated as a
2162 - If the argument doesn't start with a number, it is evaluated as a
2154 variable and its contents loaded into the editor. You can thus edit
2163 variable and its contents loaded into the editor. You can thus edit
2155 any string which contains python code (including the result of
2164 any string which contains python code (including the result of
2156 previous edits).
2165 previous edits).
2157
2166
2158 - If the argument is the name of an object (other than a string),
2167 - If the argument is the name of an object (other than a string),
2159 IPython will try to locate the file where it was defined and open the
2168 IPython will try to locate the file where it was defined and open the
2160 editor at the point where it is defined. You can use `%edit function`
2169 editor at the point where it is defined. You can use `%edit function`
2161 to load an editor exactly at the point where 'function' is defined,
2170 to load an editor exactly at the point where 'function' is defined,
2162 edit it and have the file be executed automatically.
2171 edit it and have the file be executed automatically.
2163
2172
2164 If the object is a macro (see %macro for details), this opens up your
2173 If the object is a macro (see %macro for details), this opens up your
2165 specified editor with a temporary file containing the macro's data.
2174 specified editor with a temporary file containing the macro's data.
2166 Upon exit, the macro is reloaded with the contents of the file.
2175 Upon exit, the macro is reloaded with the contents of the file.
2167
2176
2168 Note: opening at an exact line is only supported under Unix, and some
2177 Note: opening at an exact line is only supported under Unix, and some
2169 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2178 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2170 '+NUMBER' parameter necessary for this feature. Good editors like
2179 '+NUMBER' parameter necessary for this feature. Good editors like
2171 (X)Emacs, vi, jed, pico and joe all do.
2180 (X)Emacs, vi, jed, pico and joe all do.
2172
2181
2173 - If the argument is not found as a variable, IPython will look for a
2182 - If the argument is not found as a variable, IPython will look for a
2174 file with that name (adding .py if necessary) and load it into the
2183 file with that name (adding .py if necessary) and load it into the
2175 editor. It will execute its contents with execfile() when you exit,
2184 editor. It will execute its contents with execfile() when you exit,
2176 loading any code in the file into your interactive namespace.
2185 loading any code in the file into your interactive namespace.
2177
2186
2178 After executing your code, %edit will return as output the code you
2187 After executing your code, %edit will return as output the code you
2179 typed in the editor (except when it was an existing file). This way
2188 typed in the editor (except when it was an existing file). This way
2180 you can reload the code in further invocations of %edit as a variable,
2189 you can reload the code in further invocations of %edit as a variable,
2181 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2190 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2182 the output.
2191 the output.
2183
2192
2184 Note that %edit is also available through the alias %ed.
2193 Note that %edit is also available through the alias %ed.
2185
2194
2186 This is an example of creating a simple function inside the editor and
2195 This is an example of creating a simple function inside the editor and
2187 then modifying it. First, start up the editor:
2196 then modifying it. First, start up the editor:
2188
2197
2189 In [1]: ed
2198 In [1]: ed
2190 Editing... done. Executing edited code...
2199 Editing... done. Executing edited code...
2191 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2200 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2192
2201
2193 We can then call the function foo():
2202 We can then call the function foo():
2194
2203
2195 In [2]: foo()
2204 In [2]: foo()
2196 foo() was defined in an editing session
2205 foo() was defined in an editing session
2197
2206
2198 Now we edit foo. IPython automatically loads the editor with the
2207 Now we edit foo. IPython automatically loads the editor with the
2199 (temporary) file where foo() was previously defined:
2208 (temporary) file where foo() was previously defined:
2200
2209
2201 In [3]: ed foo
2210 In [3]: ed foo
2202 Editing... done. Executing edited code...
2211 Editing... done. Executing edited code...
2203
2212
2204 And if we call foo() again we get the modified version:
2213 And if we call foo() again we get the modified version:
2205
2214
2206 In [4]: foo()
2215 In [4]: foo()
2207 foo() has now been changed!
2216 foo() has now been changed!
2208
2217
2209 Here is an example of how to edit a code snippet successive
2218 Here is an example of how to edit a code snippet successive
2210 times. First we call the editor:
2219 times. First we call the editor:
2211
2220
2212 In [5]: ed
2221 In [5]: ed
2213 Editing... done. Executing edited code...
2222 Editing... done. Executing edited code...
2214 hello
2223 hello
2215 Out[5]: "print 'hello'n"
2224 Out[5]: "print 'hello'n"
2216
2225
2217 Now we call it again with the previous output (stored in _):
2226 Now we call it again with the previous output (stored in _):
2218
2227
2219 In [6]: ed _
2228 In [6]: ed _
2220 Editing... done. Executing edited code...
2229 Editing... done. Executing edited code...
2221 hello world
2230 hello world
2222 Out[6]: "print 'hello world'n"
2231 Out[6]: "print 'hello world'n"
2223
2232
2224 Now we call it with the output #8 (stored in _8, also as Out[8]):
2233 Now we call it with the output #8 (stored in _8, also as Out[8]):
2225
2234
2226 In [7]: ed _8
2235 In [7]: ed _8
2227 Editing... done. Executing edited code...
2236 Editing... done. Executing edited code...
2228 hello again
2237 hello again
2229 Out[7]: "print 'hello again'n"
2238 Out[7]: "print 'hello again'n"
2230
2239
2231
2240
2232 Changing the default editor hook:
2241 Changing the default editor hook:
2233
2242
2234 If you wish to write your own editor hook, you can put it in a
2243 If you wish to write your own editor hook, you can put it in a
2235 configuration file which you load at startup time. The default hook
2244 configuration file which you load at startup time. The default hook
2236 is defined in the IPython.core.hooks module, and you can use that as a
2245 is defined in the IPython.core.hooks module, and you can use that as a
2237 starting example for further modifications. That file also has
2246 starting example for further modifications. That file also has
2238 general instructions on how to set a new hook for use once you've
2247 general instructions on how to set a new hook for use once you've
2239 defined it."""
2248 defined it."""
2240
2249
2241 # FIXME: This function has become a convoluted mess. It needs a
2250 # FIXME: This function has become a convoluted mess. It needs a
2242 # ground-up rewrite with clean, simple logic.
2251 # ground-up rewrite with clean, simple logic.
2243
2252
2244 def make_filename(arg):
2253 def make_filename(arg):
2245 "Make a filename from the given args"
2254 "Make a filename from the given args"
2246 try:
2255 try:
2247 filename = get_py_filename(arg)
2256 filename = get_py_filename(arg)
2248 except IOError:
2257 except IOError:
2249 if args.endswith('.py'):
2258 if args.endswith('.py'):
2250 filename = arg
2259 filename = arg
2251 else:
2260 else:
2252 filename = None
2261 filename = None
2253 return filename
2262 return filename
2254
2263
2255 # custom exceptions
2264 # custom exceptions
2256 class DataIsObject(Exception): pass
2265 class DataIsObject(Exception): pass
2257
2266
2258 opts,args = self.parse_options(parameter_s,'prxn:')
2267 opts,args = self.parse_options(parameter_s,'prxn:')
2259 # Set a few locals from the options for convenience:
2268 # Set a few locals from the options for convenience:
2260 opts_p = opts.has_key('p')
2269 opts_p = opts.has_key('p')
2261 opts_r = opts.has_key('r')
2270 opts_r = opts.has_key('r')
2262
2271
2263 # Default line number value
2272 # Default line number value
2264 lineno = opts.get('n',None)
2273 lineno = opts.get('n',None)
2265
2274
2266 if opts_p:
2275 if opts_p:
2267 args = '_%s' % last_call[0]
2276 args = '_%s' % last_call[0]
2268 if not self.shell.user_ns.has_key(args):
2277 if not self.shell.user_ns.has_key(args):
2269 args = last_call[1]
2278 args = last_call[1]
2270
2279
2271 # use last_call to remember the state of the previous call, but don't
2280 # use last_call to remember the state of the previous call, but don't
2272 # let it be clobbered by successive '-p' calls.
2281 # let it be clobbered by successive '-p' calls.
2273 try:
2282 try:
2274 last_call[0] = self.shell.displayhook.prompt_count
2283 last_call[0] = self.shell.displayhook.prompt_count
2275 if not opts_p:
2284 if not opts_p:
2276 last_call[1] = parameter_s
2285 last_call[1] = parameter_s
2277 except:
2286 except:
2278 pass
2287 pass
2279
2288
2280 # by default this is done with temp files, except when the given
2289 # by default this is done with temp files, except when the given
2281 # arg is a filename
2290 # arg is a filename
2282 use_temp = 1
2291 use_temp = 1
2283
2292
2284 if re.match(r'\d',args):
2293 if re.match(r'\d',args):
2285 # Mode where user specifies ranges of lines, like in %macro.
2294 # Mode where user specifies ranges of lines, like in %macro.
2286 # This means that you can't edit files whose names begin with
2295 # This means that you can't edit files whose names begin with
2287 # numbers this way. Tough.
2296 # numbers this way. Tough.
2288 ranges = args.split()
2297 ranges = args.split()
2289 data = ''.join(self.extract_input_slices(ranges,opts_r))
2298 data = ''.join(self.extract_input_slices(ranges,opts_r))
2290 elif args.endswith('.py'):
2299 elif args.endswith('.py'):
2291 filename = make_filename(args)
2300 filename = make_filename(args)
2292 data = ''
2301 data = ''
2293 use_temp = 0
2302 use_temp = 0
2294 elif args:
2303 elif args:
2295 try:
2304 try:
2296 # Load the parameter given as a variable. If not a string,
2305 # Load the parameter given as a variable. If not a string,
2297 # process it as an object instead (below)
2306 # process it as an object instead (below)
2298
2307
2299 #print '*** args',args,'type',type(args) # dbg
2308 #print '*** args',args,'type',type(args) # dbg
2300 data = eval(args,self.shell.user_ns)
2309 data = eval(args,self.shell.user_ns)
2301 if not type(data) in StringTypes:
2310 if not type(data) in StringTypes:
2302 raise DataIsObject
2311 raise DataIsObject
2303
2312
2304 except (NameError,SyntaxError):
2313 except (NameError,SyntaxError):
2305 # given argument is not a variable, try as a filename
2314 # given argument is not a variable, try as a filename
2306 filename = make_filename(args)
2315 filename = make_filename(args)
2307 if filename is None:
2316 if filename is None:
2308 warn("Argument given (%s) can't be found as a variable "
2317 warn("Argument given (%s) can't be found as a variable "
2309 "or as a filename." % args)
2318 "or as a filename." % args)
2310 return
2319 return
2311
2320
2312 data = ''
2321 data = ''
2313 use_temp = 0
2322 use_temp = 0
2314 except DataIsObject:
2323 except DataIsObject:
2315
2324
2316 # macros have a special edit function
2325 # macros have a special edit function
2317 if isinstance(data,Macro):
2326 if isinstance(data,Macro):
2318 self._edit_macro(args,data)
2327 self._edit_macro(args,data)
2319 return
2328 return
2320
2329
2321 # For objects, try to edit the file where they are defined
2330 # For objects, try to edit the file where they are defined
2322 try:
2331 try:
2323 filename = inspect.getabsfile(data)
2332 filename = inspect.getabsfile(data)
2324 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2333 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2325 # class created by %edit? Try to find source
2334 # class created by %edit? Try to find source
2326 # by looking for method definitions instead, the
2335 # by looking for method definitions instead, the
2327 # __module__ in those classes is FakeModule.
2336 # __module__ in those classes is FakeModule.
2328 attrs = [getattr(data, aname) for aname in dir(data)]
2337 attrs = [getattr(data, aname) for aname in dir(data)]
2329 for attr in attrs:
2338 for attr in attrs:
2330 if not inspect.ismethod(attr):
2339 if not inspect.ismethod(attr):
2331 continue
2340 continue
2332 filename = inspect.getabsfile(attr)
2341 filename = inspect.getabsfile(attr)
2333 if filename and 'fakemodule' not in filename.lower():
2342 if filename and 'fakemodule' not in filename.lower():
2334 # change the attribute to be the edit target instead
2343 # change the attribute to be the edit target instead
2335 data = attr
2344 data = attr
2336 break
2345 break
2337
2346
2338 datafile = 1
2347 datafile = 1
2339 except TypeError:
2348 except TypeError:
2340 filename = make_filename(args)
2349 filename = make_filename(args)
2341 datafile = 1
2350 datafile = 1
2342 warn('Could not find file where `%s` is defined.\n'
2351 warn('Could not find file where `%s` is defined.\n'
2343 'Opening a file named `%s`' % (args,filename))
2352 'Opening a file named `%s`' % (args,filename))
2344 # Now, make sure we can actually read the source (if it was in
2353 # Now, make sure we can actually read the source (if it was in
2345 # a temp file it's gone by now).
2354 # a temp file it's gone by now).
2346 if datafile:
2355 if datafile:
2347 try:
2356 try:
2348 if lineno is None:
2357 if lineno is None:
2349 lineno = inspect.getsourcelines(data)[1]
2358 lineno = inspect.getsourcelines(data)[1]
2350 except IOError:
2359 except IOError:
2351 filename = make_filename(args)
2360 filename = make_filename(args)
2352 if filename is None:
2361 if filename is None:
2353 warn('The file `%s` where `%s` was defined cannot '
2362 warn('The file `%s` where `%s` was defined cannot '
2354 'be read.' % (filename,data))
2363 'be read.' % (filename,data))
2355 return
2364 return
2356 use_temp = 0
2365 use_temp = 0
2357 else:
2366 else:
2358 data = ''
2367 data = ''
2359
2368
2360 if use_temp:
2369 if use_temp:
2361 filename = self.shell.mktempfile(data)
2370 filename = self.shell.mktempfile(data)
2362 print 'IPython will make a temporary file named:',filename
2371 print 'IPython will make a temporary file named:',filename
2363
2372
2364 # do actual editing here
2373 # do actual editing here
2365 print 'Editing...',
2374 print 'Editing...',
2366 sys.stdout.flush()
2375 sys.stdout.flush()
2367 try:
2376 try:
2368 # Quote filenames that may have spaces in them
2377 # Quote filenames that may have spaces in them
2369 if ' ' in filename:
2378 if ' ' in filename:
2370 filename = "%s" % filename
2379 filename = "%s" % filename
2371 self.shell.hooks.editor(filename,lineno)
2380 self.shell.hooks.editor(filename,lineno)
2372 except TryNext:
2381 except TryNext:
2373 warn('Could not open editor')
2382 warn('Could not open editor')
2374 return
2383 return
2375
2384
2376 # XXX TODO: should this be generalized for all string vars?
2385 # XXX TODO: should this be generalized for all string vars?
2377 # For now, this is special-cased to blocks created by cpaste
2386 # For now, this is special-cased to blocks created by cpaste
2378 if args.strip() == 'pasted_block':
2387 if args.strip() == 'pasted_block':
2379 self.shell.user_ns['pasted_block'] = file_read(filename)
2388 self.shell.user_ns['pasted_block'] = file_read(filename)
2380
2389
2381 if opts.has_key('x'): # -x prevents actual execution
2390 if opts.has_key('x'): # -x prevents actual execution
2382 print
2391 print
2383 else:
2392 else:
2384 print 'done. Executing edited code...'
2393 print 'done. Executing edited code...'
2385 if opts_r:
2394 if opts_r:
2386 self.shell.run_cell(file_read(filename))
2395 self.shell.run_cell(file_read(filename))
2387 else:
2396 else:
2388 self.shell.safe_execfile(filename,self.shell.user_ns,
2397 self.shell.safe_execfile(filename,self.shell.user_ns,
2389 self.shell.user_ns)
2398 self.shell.user_ns)
2390
2399
2391
2400
2392 if use_temp:
2401 if use_temp:
2393 try:
2402 try:
2394 return open(filename).read()
2403 return open(filename).read()
2395 except IOError,msg:
2404 except IOError,msg:
2396 if msg.filename == filename:
2405 if msg.filename == filename:
2397 warn('File not found. Did you forget to save?')
2406 warn('File not found. Did you forget to save?')
2398 return
2407 return
2399 else:
2408 else:
2400 self.shell.showtraceback()
2409 self.shell.showtraceback()
2401
2410
2402 def magic_xmode(self,parameter_s = ''):
2411 def magic_xmode(self,parameter_s = ''):
2403 """Switch modes for the exception handlers.
2412 """Switch modes for the exception handlers.
2404
2413
2405 Valid modes: Plain, Context and Verbose.
2414 Valid modes: Plain, Context and Verbose.
2406
2415
2407 If called without arguments, acts as a toggle."""
2416 If called without arguments, acts as a toggle."""
2408
2417
2409 def xmode_switch_err(name):
2418 def xmode_switch_err(name):
2410 warn('Error changing %s exception modes.\n%s' %
2419 warn('Error changing %s exception modes.\n%s' %
2411 (name,sys.exc_info()[1]))
2420 (name,sys.exc_info()[1]))
2412
2421
2413 shell = self.shell
2422 shell = self.shell
2414 new_mode = parameter_s.strip().capitalize()
2423 new_mode = parameter_s.strip().capitalize()
2415 try:
2424 try:
2416 shell.InteractiveTB.set_mode(mode=new_mode)
2425 shell.InteractiveTB.set_mode(mode=new_mode)
2417 print 'Exception reporting mode:',shell.InteractiveTB.mode
2426 print 'Exception reporting mode:',shell.InteractiveTB.mode
2418 except:
2427 except:
2419 xmode_switch_err('user')
2428 xmode_switch_err('user')
2420
2429
2421 def magic_colors(self,parameter_s = ''):
2430 def magic_colors(self,parameter_s = ''):
2422 """Switch color scheme for prompts, info system and exception handlers.
2431 """Switch color scheme for prompts, info system and exception handlers.
2423
2432
2424 Currently implemented schemes: NoColor, Linux, LightBG.
2433 Currently implemented schemes: NoColor, Linux, LightBG.
2425
2434
2426 Color scheme names are not case-sensitive."""
2435 Color scheme names are not case-sensitive.
2436
2437 Examples
2438 --------
2439 To get a plain black and white terminal::
2440
2441 %colors nocolor
2442 """
2427
2443
2428 def color_switch_err(name):
2444 def color_switch_err(name):
2429 warn('Error changing %s color schemes.\n%s' %
2445 warn('Error changing %s color schemes.\n%s' %
2430 (name,sys.exc_info()[1]))
2446 (name,sys.exc_info()[1]))
2431
2447
2432
2448
2433 new_scheme = parameter_s.strip()
2449 new_scheme = parameter_s.strip()
2434 if not new_scheme:
2450 if not new_scheme:
2435 raise UsageError(
2451 raise UsageError(
2436 "%colors: you must specify a color scheme. See '%colors?'")
2452 "%colors: you must specify a color scheme. See '%colors?'")
2437 return
2453 return
2438 # local shortcut
2454 # local shortcut
2439 shell = self.shell
2455 shell = self.shell
2440
2456
2441 import IPython.utils.rlineimpl as readline
2457 import IPython.utils.rlineimpl as readline
2442
2458
2443 if not readline.have_readline and sys.platform == "win32":
2459 if not readline.have_readline and sys.platform == "win32":
2444 msg = """\
2460 msg = """\
2445 Proper color support under MS Windows requires the pyreadline library.
2461 Proper color support under MS Windows requires the pyreadline library.
2446 You can find it at:
2462 You can find it at:
2447 http://ipython.scipy.org/moin/PyReadline/Intro
2463 http://ipython.scipy.org/moin/PyReadline/Intro
2448 Gary's readline needs the ctypes module, from:
2464 Gary's readline needs the ctypes module, from:
2449 http://starship.python.net/crew/theller/ctypes
2465 http://starship.python.net/crew/theller/ctypes
2450 (Note that ctypes is already part of Python versions 2.5 and newer).
2466 (Note that ctypes is already part of Python versions 2.5 and newer).
2451
2467
2452 Defaulting color scheme to 'NoColor'"""
2468 Defaulting color scheme to 'NoColor'"""
2453 new_scheme = 'NoColor'
2469 new_scheme = 'NoColor'
2454 warn(msg)
2470 warn(msg)
2455
2471
2456 # readline option is 0
2472 # readline option is 0
2457 if not shell.has_readline:
2473 if not shell.has_readline:
2458 new_scheme = 'NoColor'
2474 new_scheme = 'NoColor'
2459
2475
2460 # Set prompt colors
2476 # Set prompt colors
2461 try:
2477 try:
2462 shell.displayhook.set_colors(new_scheme)
2478 shell.displayhook.set_colors(new_scheme)
2463 except:
2479 except:
2464 color_switch_err('prompt')
2480 color_switch_err('prompt')
2465 else:
2481 else:
2466 shell.colors = \
2482 shell.colors = \
2467 shell.displayhook.color_table.active_scheme_name
2483 shell.displayhook.color_table.active_scheme_name
2468 # Set exception colors
2484 # Set exception colors
2469 try:
2485 try:
2470 shell.InteractiveTB.set_colors(scheme = new_scheme)
2486 shell.InteractiveTB.set_colors(scheme = new_scheme)
2471 shell.SyntaxTB.set_colors(scheme = new_scheme)
2487 shell.SyntaxTB.set_colors(scheme = new_scheme)
2472 except:
2488 except:
2473 color_switch_err('exception')
2489 color_switch_err('exception')
2474
2490
2475 # Set info (for 'object?') colors
2491 # Set info (for 'object?') colors
2476 if shell.color_info:
2492 if shell.color_info:
2477 try:
2493 try:
2478 shell.inspector.set_active_scheme(new_scheme)
2494 shell.inspector.set_active_scheme(new_scheme)
2479 except:
2495 except:
2480 color_switch_err('object inspector')
2496 color_switch_err('object inspector')
2481 else:
2497 else:
2482 shell.inspector.set_active_scheme('NoColor')
2498 shell.inspector.set_active_scheme('NoColor')
2483
2499
2484 def magic_pprint(self, parameter_s=''):
2500 def magic_pprint(self, parameter_s=''):
2485 """Toggle pretty printing on/off."""
2501 """Toggle pretty printing on/off."""
2486 ptformatter = self.shell.display_formatter.formatters['text/plain']
2502 ptformatter = self.shell.display_formatter.formatters['text/plain']
2487 ptformatter.pprint = bool(1 - ptformatter.pprint)
2503 ptformatter.pprint = bool(1 - ptformatter.pprint)
2488 print 'Pretty printing has been turned', \
2504 print 'Pretty printing has been turned', \
2489 ['OFF','ON'][ptformatter.pprint]
2505 ['OFF','ON'][ptformatter.pprint]
2490
2506
2491 def magic_Exit(self, parameter_s=''):
2507 def magic_Exit(self, parameter_s=''):
2492 """Exit IPython."""
2508 """Exit IPython."""
2493
2509
2494 self.shell.ask_exit()
2510 self.shell.ask_exit()
2495
2511
2496 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2512 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2497 magic_exit = magic_quit = magic_Quit = magic_Exit
2513 magic_exit = magic_quit = magic_Quit = magic_Exit
2498
2514
2499 #......................................................................
2515 #......................................................................
2500 # Functions to implement unix shell-type things
2516 # Functions to implement unix shell-type things
2501
2517
2502 @testdec.skip_doctest
2518 @testdec.skip_doctest
2503 def magic_alias(self, parameter_s = ''):
2519 def magic_alias(self, parameter_s = ''):
2504 """Define an alias for a system command.
2520 """Define an alias for a system command.
2505
2521
2506 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2522 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2507
2523
2508 Then, typing 'alias_name params' will execute the system command 'cmd
2524 Then, typing 'alias_name params' will execute the system command 'cmd
2509 params' (from your underlying operating system).
2525 params' (from your underlying operating system).
2510
2526
2511 Aliases have lower precedence than magic functions and Python normal
2527 Aliases have lower precedence than magic functions and Python normal
2512 variables, so if 'foo' is both a Python variable and an alias, the
2528 variables, so if 'foo' is both a Python variable and an alias, the
2513 alias can not be executed until 'del foo' removes the Python variable.
2529 alias can not be executed until 'del foo' removes the Python variable.
2514
2530
2515 You can use the %l specifier in an alias definition to represent the
2531 You can use the %l specifier in an alias definition to represent the
2516 whole line when the alias is called. For example:
2532 whole line when the alias is called. For example:
2517
2533
2518 In [2]: alias bracket echo "Input in brackets: <%l>"
2534 In [2]: alias bracket echo "Input in brackets: <%l>"
2519 In [3]: bracket hello world
2535 In [3]: bracket hello world
2520 Input in brackets: <hello world>
2536 Input in brackets: <hello world>
2521
2537
2522 You can also define aliases with parameters using %s specifiers (one
2538 You can also define aliases with parameters using %s specifiers (one
2523 per parameter):
2539 per parameter):
2524
2540
2525 In [1]: alias parts echo first %s second %s
2541 In [1]: alias parts echo first %s second %s
2526 In [2]: %parts A B
2542 In [2]: %parts A B
2527 first A second B
2543 first A second B
2528 In [3]: %parts A
2544 In [3]: %parts A
2529 Incorrect number of arguments: 2 expected.
2545 Incorrect number of arguments: 2 expected.
2530 parts is an alias to: 'echo first %s second %s'
2546 parts is an alias to: 'echo first %s second %s'
2531
2547
2532 Note that %l and %s are mutually exclusive. You can only use one or
2548 Note that %l and %s are mutually exclusive. You can only use one or
2533 the other in your aliases.
2549 the other in your aliases.
2534
2550
2535 Aliases expand Python variables just like system calls using ! or !!
2551 Aliases expand Python variables just like system calls using ! or !!
2536 do: all expressions prefixed with '$' get expanded. For details of
2552 do: all expressions prefixed with '$' get expanded. For details of
2537 the semantic rules, see PEP-215:
2553 the semantic rules, see PEP-215:
2538 http://www.python.org/peps/pep-0215.html. This is the library used by
2554 http://www.python.org/peps/pep-0215.html. This is the library used by
2539 IPython for variable expansion. If you want to access a true shell
2555 IPython for variable expansion. If you want to access a true shell
2540 variable, an extra $ is necessary to prevent its expansion by IPython:
2556 variable, an extra $ is necessary to prevent its expansion by IPython:
2541
2557
2542 In [6]: alias show echo
2558 In [6]: alias show echo
2543 In [7]: PATH='A Python string'
2559 In [7]: PATH='A Python string'
2544 In [8]: show $PATH
2560 In [8]: show $PATH
2545 A Python string
2561 A Python string
2546 In [9]: show $$PATH
2562 In [9]: show $$PATH
2547 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2563 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2548
2564
2549 You can use the alias facility to acess all of $PATH. See the %rehash
2565 You can use the alias facility to acess all of $PATH. See the %rehash
2550 and %rehashx functions, which automatically create aliases for the
2566 and %rehashx functions, which automatically create aliases for the
2551 contents of your $PATH.
2567 contents of your $PATH.
2552
2568
2553 If called with no parameters, %alias prints the current alias table."""
2569 If called with no parameters, %alias prints the current alias table."""
2554
2570
2555 par = parameter_s.strip()
2571 par = parameter_s.strip()
2556 if not par:
2572 if not par:
2557 stored = self.db.get('stored_aliases', {} )
2573 stored = self.db.get('stored_aliases', {} )
2558 aliases = sorted(self.shell.alias_manager.aliases)
2574 aliases = sorted(self.shell.alias_manager.aliases)
2559 # for k, v in stored:
2575 # for k, v in stored:
2560 # atab.append(k, v[0])
2576 # atab.append(k, v[0])
2561
2577
2562 print "Total number of aliases:", len(aliases)
2578 print "Total number of aliases:", len(aliases)
2563 sys.stdout.flush()
2579 sys.stdout.flush()
2564 return aliases
2580 return aliases
2565
2581
2566 # Now try to define a new one
2582 # Now try to define a new one
2567 try:
2583 try:
2568 alias,cmd = par.split(None, 1)
2584 alias,cmd = par.split(None, 1)
2569 except:
2585 except:
2570 print oinspect.getdoc(self.magic_alias)
2586 print oinspect.getdoc(self.magic_alias)
2571 else:
2587 else:
2572 self.shell.alias_manager.soft_define_alias(alias, cmd)
2588 self.shell.alias_manager.soft_define_alias(alias, cmd)
2573 # end magic_alias
2589 # end magic_alias
2574
2590
2575 def magic_unalias(self, parameter_s = ''):
2591 def magic_unalias(self, parameter_s = ''):
2576 """Remove an alias"""
2592 """Remove an alias"""
2577
2593
2578 aname = parameter_s.strip()
2594 aname = parameter_s.strip()
2579 self.shell.alias_manager.undefine_alias(aname)
2595 self.shell.alias_manager.undefine_alias(aname)
2580 stored = self.db.get('stored_aliases', {} )
2596 stored = self.db.get('stored_aliases', {} )
2581 if aname in stored:
2597 if aname in stored:
2582 print "Removing %stored alias",aname
2598 print "Removing %stored alias",aname
2583 del stored[aname]
2599 del stored[aname]
2584 self.db['stored_aliases'] = stored
2600 self.db['stored_aliases'] = stored
2585
2601
2586 def magic_rehashx(self, parameter_s = ''):
2602 def magic_rehashx(self, parameter_s = ''):
2587 """Update the alias table with all executable files in $PATH.
2603 """Update the alias table with all executable files in $PATH.
2588
2604
2589 This version explicitly checks that every entry in $PATH is a file
2605 This version explicitly checks that every entry in $PATH is a file
2590 with execute access (os.X_OK), so it is much slower than %rehash.
2606 with execute access (os.X_OK), so it is much slower than %rehash.
2591
2607
2592 Under Windows, it checks executability as a match agains a
2608 Under Windows, it checks executability as a match agains a
2593 '|'-separated string of extensions, stored in the IPython config
2609 '|'-separated string of extensions, stored in the IPython config
2594 variable win_exec_ext. This defaults to 'exe|com|bat'.
2610 variable win_exec_ext. This defaults to 'exe|com|bat'.
2595
2611
2596 This function also resets the root module cache of module completer,
2612 This function also resets the root module cache of module completer,
2597 used on slow filesystems.
2613 used on slow filesystems.
2598 """
2614 """
2599 from IPython.core.alias import InvalidAliasError
2615 from IPython.core.alias import InvalidAliasError
2600
2616
2601 # for the benefit of module completer in ipy_completers.py
2617 # for the benefit of module completer in ipy_completers.py
2602 del self.db['rootmodules']
2618 del self.db['rootmodules']
2603
2619
2604 path = [os.path.abspath(os.path.expanduser(p)) for p in
2620 path = [os.path.abspath(os.path.expanduser(p)) for p in
2605 os.environ.get('PATH','').split(os.pathsep)]
2621 os.environ.get('PATH','').split(os.pathsep)]
2606 path = filter(os.path.isdir,path)
2622 path = filter(os.path.isdir,path)
2607
2623
2608 syscmdlist = []
2624 syscmdlist = []
2609 # Now define isexec in a cross platform manner.
2625 # Now define isexec in a cross platform manner.
2610 if os.name == 'posix':
2626 if os.name == 'posix':
2611 isexec = lambda fname:os.path.isfile(fname) and \
2627 isexec = lambda fname:os.path.isfile(fname) and \
2612 os.access(fname,os.X_OK)
2628 os.access(fname,os.X_OK)
2613 else:
2629 else:
2614 try:
2630 try:
2615 winext = os.environ['pathext'].replace(';','|').replace('.','')
2631 winext = os.environ['pathext'].replace(';','|').replace('.','')
2616 except KeyError:
2632 except KeyError:
2617 winext = 'exe|com|bat|py'
2633 winext = 'exe|com|bat|py'
2618 if 'py' not in winext:
2634 if 'py' not in winext:
2619 winext += '|py'
2635 winext += '|py'
2620 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2636 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2621 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2637 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2622 savedir = os.getcwd()
2638 savedir = os.getcwd()
2623
2639
2624 # Now walk the paths looking for executables to alias.
2640 # Now walk the paths looking for executables to alias.
2625 try:
2641 try:
2626 # write the whole loop for posix/Windows so we don't have an if in
2642 # write the whole loop for posix/Windows so we don't have an if in
2627 # the innermost part
2643 # the innermost part
2628 if os.name == 'posix':
2644 if os.name == 'posix':
2629 for pdir in path:
2645 for pdir in path:
2630 os.chdir(pdir)
2646 os.chdir(pdir)
2631 for ff in os.listdir(pdir):
2647 for ff in os.listdir(pdir):
2632 if isexec(ff):
2648 if isexec(ff):
2633 try:
2649 try:
2634 # Removes dots from the name since ipython
2650 # Removes dots from the name since ipython
2635 # will assume names with dots to be python.
2651 # will assume names with dots to be python.
2636 self.shell.alias_manager.define_alias(
2652 self.shell.alias_manager.define_alias(
2637 ff.replace('.',''), ff)
2653 ff.replace('.',''), ff)
2638 except InvalidAliasError:
2654 except InvalidAliasError:
2639 pass
2655 pass
2640 else:
2656 else:
2641 syscmdlist.append(ff)
2657 syscmdlist.append(ff)
2642 else:
2658 else:
2643 no_alias = self.shell.alias_manager.no_alias
2659 no_alias = self.shell.alias_manager.no_alias
2644 for pdir in path:
2660 for pdir in path:
2645 os.chdir(pdir)
2661 os.chdir(pdir)
2646 for ff in os.listdir(pdir):
2662 for ff in os.listdir(pdir):
2647 base, ext = os.path.splitext(ff)
2663 base, ext = os.path.splitext(ff)
2648 if isexec(ff) and base.lower() not in no_alias:
2664 if isexec(ff) and base.lower() not in no_alias:
2649 if ext.lower() == '.exe':
2665 if ext.lower() == '.exe':
2650 ff = base
2666 ff = base
2651 try:
2667 try:
2652 # Removes dots from the name since ipython
2668 # Removes dots from the name since ipython
2653 # will assume names with dots to be python.
2669 # will assume names with dots to be python.
2654 self.shell.alias_manager.define_alias(
2670 self.shell.alias_manager.define_alias(
2655 base.lower().replace('.',''), ff)
2671 base.lower().replace('.',''), ff)
2656 except InvalidAliasError:
2672 except InvalidAliasError:
2657 pass
2673 pass
2658 syscmdlist.append(ff)
2674 syscmdlist.append(ff)
2659 db = self.db
2675 db = self.db
2660 db['syscmdlist'] = syscmdlist
2676 db['syscmdlist'] = syscmdlist
2661 finally:
2677 finally:
2662 os.chdir(savedir)
2678 os.chdir(savedir)
2663
2679
2680 @testdec.skip_doctest
2664 def magic_pwd(self, parameter_s = ''):
2681 def magic_pwd(self, parameter_s = ''):
2665 """Return the current working directory path."""
2682 """Return the current working directory path.
2683
2684 Examples
2685 --------
2686 ::
2687
2688 In [9]: pwd
2689 Out[9]: '/home/tsuser/sprint/ipython'
2690 """
2666 return os.getcwd()
2691 return os.getcwd()
2667
2692
2693 @testdec.skip_doctest
2668 def magic_cd(self, parameter_s=''):
2694 def magic_cd(self, parameter_s=''):
2669 """Change the current working directory.
2695 """Change the current working directory.
2670
2696
2671 This command automatically maintains an internal list of directories
2697 This command automatically maintains an internal list of directories
2672 you visit during your IPython session, in the variable _dh. The
2698 you visit during your IPython session, in the variable _dh. The
2673 command %dhist shows this history nicely formatted. You can also
2699 command %dhist shows this history nicely formatted. You can also
2674 do 'cd -<tab>' to see directory history conveniently.
2700 do 'cd -<tab>' to see directory history conveniently.
2675
2701
2676 Usage:
2702 Usage:
2677
2703
2678 cd 'dir': changes to directory 'dir'.
2704 cd 'dir': changes to directory 'dir'.
2679
2705
2680 cd -: changes to the last visited directory.
2706 cd -: changes to the last visited directory.
2681
2707
2682 cd -<n>: changes to the n-th directory in the directory history.
2708 cd -<n>: changes to the n-th directory in the directory history.
2683
2709
2684 cd --foo: change to directory that matches 'foo' in history
2710 cd --foo: change to directory that matches 'foo' in history
2685
2711
2686 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2712 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2687 (note: cd <bookmark_name> is enough if there is no
2713 (note: cd <bookmark_name> is enough if there is no
2688 directory <bookmark_name>, but a bookmark with the name exists.)
2714 directory <bookmark_name>, but a bookmark with the name exists.)
2689 'cd -b <tab>' allows you to tab-complete bookmark names.
2715 'cd -b <tab>' allows you to tab-complete bookmark names.
2690
2716
2691 Options:
2717 Options:
2692
2718
2693 -q: quiet. Do not print the working directory after the cd command is
2719 -q: quiet. Do not print the working directory after the cd command is
2694 executed. By default IPython's cd command does print this directory,
2720 executed. By default IPython's cd command does print this directory,
2695 since the default prompts do not display path information.
2721 since the default prompts do not display path information.
2696
2722
2697 Note that !cd doesn't work for this purpose because the shell where
2723 Note that !cd doesn't work for this purpose because the shell where
2698 !command runs is immediately discarded after executing 'command'."""
2724 !command runs is immediately discarded after executing 'command'.
2725
2726 Examples
2727 --------
2728 ::
2729
2730 In [10]: cd parent/child
2731 /home/tsuser/parent/child
2732 """
2699
2733
2700 parameter_s = parameter_s.strip()
2734 parameter_s = parameter_s.strip()
2701 #bkms = self.shell.persist.get("bookmarks",{})
2735 #bkms = self.shell.persist.get("bookmarks",{})
2702
2736
2703 oldcwd = os.getcwd()
2737 oldcwd = os.getcwd()
2704 numcd = re.match(r'(-)(\d+)$',parameter_s)
2738 numcd = re.match(r'(-)(\d+)$',parameter_s)
2705 # jump in directory history by number
2739 # jump in directory history by number
2706 if numcd:
2740 if numcd:
2707 nn = int(numcd.group(2))
2741 nn = int(numcd.group(2))
2708 try:
2742 try:
2709 ps = self.shell.user_ns['_dh'][nn]
2743 ps = self.shell.user_ns['_dh'][nn]
2710 except IndexError:
2744 except IndexError:
2711 print 'The requested directory does not exist in history.'
2745 print 'The requested directory does not exist in history.'
2712 return
2746 return
2713 else:
2747 else:
2714 opts = {}
2748 opts = {}
2715 elif parameter_s.startswith('--'):
2749 elif parameter_s.startswith('--'):
2716 ps = None
2750 ps = None
2717 fallback = None
2751 fallback = None
2718 pat = parameter_s[2:]
2752 pat = parameter_s[2:]
2719 dh = self.shell.user_ns['_dh']
2753 dh = self.shell.user_ns['_dh']
2720 # first search only by basename (last component)
2754 # first search only by basename (last component)
2721 for ent in reversed(dh):
2755 for ent in reversed(dh):
2722 if pat in os.path.basename(ent) and os.path.isdir(ent):
2756 if pat in os.path.basename(ent) and os.path.isdir(ent):
2723 ps = ent
2757 ps = ent
2724 break
2758 break
2725
2759
2726 if fallback is None and pat in ent and os.path.isdir(ent):
2760 if fallback is None and pat in ent and os.path.isdir(ent):
2727 fallback = ent
2761 fallback = ent
2728
2762
2729 # if we have no last part match, pick the first full path match
2763 # if we have no last part match, pick the first full path match
2730 if ps is None:
2764 if ps is None:
2731 ps = fallback
2765 ps = fallback
2732
2766
2733 if ps is None:
2767 if ps is None:
2734 print "No matching entry in directory history"
2768 print "No matching entry in directory history"
2735 return
2769 return
2736 else:
2770 else:
2737 opts = {}
2771 opts = {}
2738
2772
2739
2773
2740 else:
2774 else:
2741 #turn all non-space-escaping backslashes to slashes,
2775 #turn all non-space-escaping backslashes to slashes,
2742 # for c:\windows\directory\names\
2776 # for c:\windows\directory\names\
2743 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2777 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2744 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2778 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2745 # jump to previous
2779 # jump to previous
2746 if ps == '-':
2780 if ps == '-':
2747 try:
2781 try:
2748 ps = self.shell.user_ns['_dh'][-2]
2782 ps = self.shell.user_ns['_dh'][-2]
2749 except IndexError:
2783 except IndexError:
2750 raise UsageError('%cd -: No previous directory to change to.')
2784 raise UsageError('%cd -: No previous directory to change to.')
2751 # jump to bookmark if needed
2785 # jump to bookmark if needed
2752 else:
2786 else:
2753 if not os.path.isdir(ps) or opts.has_key('b'):
2787 if not os.path.isdir(ps) or opts.has_key('b'):
2754 bkms = self.db.get('bookmarks', {})
2788 bkms = self.db.get('bookmarks', {})
2755
2789
2756 if bkms.has_key(ps):
2790 if bkms.has_key(ps):
2757 target = bkms[ps]
2791 target = bkms[ps]
2758 print '(bookmark:%s) -> %s' % (ps,target)
2792 print '(bookmark:%s) -> %s' % (ps,target)
2759 ps = target
2793 ps = target
2760 else:
2794 else:
2761 if opts.has_key('b'):
2795 if opts.has_key('b'):
2762 raise UsageError("Bookmark '%s' not found. "
2796 raise UsageError("Bookmark '%s' not found. "
2763 "Use '%%bookmark -l' to see your bookmarks." % ps)
2797 "Use '%%bookmark -l' to see your bookmarks." % ps)
2764
2798
2765 # at this point ps should point to the target dir
2799 # at this point ps should point to the target dir
2766 if ps:
2800 if ps:
2767 try:
2801 try:
2768 os.chdir(os.path.expanduser(ps))
2802 os.chdir(os.path.expanduser(ps))
2769 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2803 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2770 set_term_title('IPython: ' + abbrev_cwd())
2804 set_term_title('IPython: ' + abbrev_cwd())
2771 except OSError:
2805 except OSError:
2772 print sys.exc_info()[1]
2806 print sys.exc_info()[1]
2773 else:
2807 else:
2774 cwd = os.getcwd()
2808 cwd = os.getcwd()
2775 dhist = self.shell.user_ns['_dh']
2809 dhist = self.shell.user_ns['_dh']
2776 if oldcwd != cwd:
2810 if oldcwd != cwd:
2777 dhist.append(cwd)
2811 dhist.append(cwd)
2778 self.db['dhist'] = compress_dhist(dhist)[-100:]
2812 self.db['dhist'] = compress_dhist(dhist)[-100:]
2779
2813
2780 else:
2814 else:
2781 os.chdir(self.shell.home_dir)
2815 os.chdir(self.shell.home_dir)
2782 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2816 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2783 set_term_title('IPython: ' + '~')
2817 set_term_title('IPython: ' + '~')
2784 cwd = os.getcwd()
2818 cwd = os.getcwd()
2785 dhist = self.shell.user_ns['_dh']
2819 dhist = self.shell.user_ns['_dh']
2786
2820
2787 if oldcwd != cwd:
2821 if oldcwd != cwd:
2788 dhist.append(cwd)
2822 dhist.append(cwd)
2789 self.db['dhist'] = compress_dhist(dhist)[-100:]
2823 self.db['dhist'] = compress_dhist(dhist)[-100:]
2790 if not 'q' in opts and self.shell.user_ns['_dh']:
2824 if not 'q' in opts and self.shell.user_ns['_dh']:
2791 print self.shell.user_ns['_dh'][-1]
2825 print self.shell.user_ns['_dh'][-1]
2792
2826
2793
2827
2794 def magic_env(self, parameter_s=''):
2828 def magic_env(self, parameter_s=''):
2795 """List environment variables."""
2829 """List environment variables."""
2796
2830
2797 return os.environ.data
2831 return os.environ.data
2798
2832
2799 def magic_pushd(self, parameter_s=''):
2833 def magic_pushd(self, parameter_s=''):
2800 """Place the current dir on stack and change directory.
2834 """Place the current dir on stack and change directory.
2801
2835
2802 Usage:\\
2836 Usage:\\
2803 %pushd ['dirname']
2837 %pushd ['dirname']
2804 """
2838 """
2805
2839
2806 dir_s = self.shell.dir_stack
2840 dir_s = self.shell.dir_stack
2807 tgt = os.path.expanduser(parameter_s)
2841 tgt = os.path.expanduser(parameter_s)
2808 cwd = os.getcwd().replace(self.home_dir,'~')
2842 cwd = os.getcwd().replace(self.home_dir,'~')
2809 if tgt:
2843 if tgt:
2810 self.magic_cd(parameter_s)
2844 self.magic_cd(parameter_s)
2811 dir_s.insert(0,cwd)
2845 dir_s.insert(0,cwd)
2812 return self.magic_dirs()
2846 return self.magic_dirs()
2813
2847
2814 def magic_popd(self, parameter_s=''):
2848 def magic_popd(self, parameter_s=''):
2815 """Change to directory popped off the top of the stack.
2849 """Change to directory popped off the top of the stack.
2816 """
2850 """
2817 if not self.shell.dir_stack:
2851 if not self.shell.dir_stack:
2818 raise UsageError("%popd on empty stack")
2852 raise UsageError("%popd on empty stack")
2819 top = self.shell.dir_stack.pop(0)
2853 top = self.shell.dir_stack.pop(0)
2820 self.magic_cd(top)
2854 self.magic_cd(top)
2821 print "popd ->",top
2855 print "popd ->",top
2822
2856
2823 def magic_dirs(self, parameter_s=''):
2857 def magic_dirs(self, parameter_s=''):
2824 """Return the current directory stack."""
2858 """Return the current directory stack."""
2825
2859
2826 return self.shell.dir_stack
2860 return self.shell.dir_stack
2827
2861
2828 def magic_dhist(self, parameter_s=''):
2862 def magic_dhist(self, parameter_s=''):
2829 """Print your history of visited directories.
2863 """Print your history of visited directories.
2830
2864
2831 %dhist -> print full history\\
2865 %dhist -> print full history\\
2832 %dhist n -> print last n entries only\\
2866 %dhist n -> print last n entries only\\
2833 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2867 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2834
2868
2835 This history is automatically maintained by the %cd command, and
2869 This history is automatically maintained by the %cd command, and
2836 always available as the global list variable _dh. You can use %cd -<n>
2870 always available as the global list variable _dh. You can use %cd -<n>
2837 to go to directory number <n>.
2871 to go to directory number <n>.
2838
2872
2839 Note that most of time, you should view directory history by entering
2873 Note that most of time, you should view directory history by entering
2840 cd -<TAB>.
2874 cd -<TAB>.
2841
2875
2842 """
2876 """
2843
2877
2844 dh = self.shell.user_ns['_dh']
2878 dh = self.shell.user_ns['_dh']
2845 if parameter_s:
2879 if parameter_s:
2846 try:
2880 try:
2847 args = map(int,parameter_s.split())
2881 args = map(int,parameter_s.split())
2848 except:
2882 except:
2849 self.arg_err(Magic.magic_dhist)
2883 self.arg_err(Magic.magic_dhist)
2850 return
2884 return
2851 if len(args) == 1:
2885 if len(args) == 1:
2852 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2886 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2853 elif len(args) == 2:
2887 elif len(args) == 2:
2854 ini,fin = args
2888 ini,fin = args
2855 else:
2889 else:
2856 self.arg_err(Magic.magic_dhist)
2890 self.arg_err(Magic.magic_dhist)
2857 return
2891 return
2858 else:
2892 else:
2859 ini,fin = 0,len(dh)
2893 ini,fin = 0,len(dh)
2860 nlprint(dh,
2894 nlprint(dh,
2861 header = 'Directory history (kept in _dh)',
2895 header = 'Directory history (kept in _dh)',
2862 start=ini,stop=fin)
2896 start=ini,stop=fin)
2863
2897
2864 @testdec.skip_doctest
2898 @testdec.skip_doctest
2865 def magic_sc(self, parameter_s=''):
2899 def magic_sc(self, parameter_s=''):
2866 """Shell capture - execute a shell command and capture its output.
2900 """Shell capture - execute a shell command and capture its output.
2867
2901
2868 DEPRECATED. Suboptimal, retained for backwards compatibility.
2902 DEPRECATED. Suboptimal, retained for backwards compatibility.
2869
2903
2870 You should use the form 'var = !command' instead. Example:
2904 You should use the form 'var = !command' instead. Example:
2871
2905
2872 "%sc -l myfiles = ls ~" should now be written as
2906 "%sc -l myfiles = ls ~" should now be written as
2873
2907
2874 "myfiles = !ls ~"
2908 "myfiles = !ls ~"
2875
2909
2876 myfiles.s, myfiles.l and myfiles.n still apply as documented
2910 myfiles.s, myfiles.l and myfiles.n still apply as documented
2877 below.
2911 below.
2878
2912
2879 --
2913 --
2880 %sc [options] varname=command
2914 %sc [options] varname=command
2881
2915
2882 IPython will run the given command using commands.getoutput(), and
2916 IPython will run the given command using commands.getoutput(), and
2883 will then update the user's interactive namespace with a variable
2917 will then update the user's interactive namespace with a variable
2884 called varname, containing the value of the call. Your command can
2918 called varname, containing the value of the call. Your command can
2885 contain shell wildcards, pipes, etc.
2919 contain shell wildcards, pipes, etc.
2886
2920
2887 The '=' sign in the syntax is mandatory, and the variable name you
2921 The '=' sign in the syntax is mandatory, and the variable name you
2888 supply must follow Python's standard conventions for valid names.
2922 supply must follow Python's standard conventions for valid names.
2889
2923
2890 (A special format without variable name exists for internal use)
2924 (A special format without variable name exists for internal use)
2891
2925
2892 Options:
2926 Options:
2893
2927
2894 -l: list output. Split the output on newlines into a list before
2928 -l: list output. Split the output on newlines into a list before
2895 assigning it to the given variable. By default the output is stored
2929 assigning it to the given variable. By default the output is stored
2896 as a single string.
2930 as a single string.
2897
2931
2898 -v: verbose. Print the contents of the variable.
2932 -v: verbose. Print the contents of the variable.
2899
2933
2900 In most cases you should not need to split as a list, because the
2934 In most cases you should not need to split as a list, because the
2901 returned value is a special type of string which can automatically
2935 returned value is a special type of string which can automatically
2902 provide its contents either as a list (split on newlines) or as a
2936 provide its contents either as a list (split on newlines) or as a
2903 space-separated string. These are convenient, respectively, either
2937 space-separated string. These are convenient, respectively, either
2904 for sequential processing or to be passed to a shell command.
2938 for sequential processing or to be passed to a shell command.
2905
2939
2906 For example:
2940 For example:
2907
2941
2908 # all-random
2942 # all-random
2909
2943
2910 # Capture into variable a
2944 # Capture into variable a
2911 In [1]: sc a=ls *py
2945 In [1]: sc a=ls *py
2912
2946
2913 # a is a string with embedded newlines
2947 # a is a string with embedded newlines
2914 In [2]: a
2948 In [2]: a
2915 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2949 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2916
2950
2917 # which can be seen as a list:
2951 # which can be seen as a list:
2918 In [3]: a.l
2952 In [3]: a.l
2919 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2953 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2920
2954
2921 # or as a whitespace-separated string:
2955 # or as a whitespace-separated string:
2922 In [4]: a.s
2956 In [4]: a.s
2923 Out[4]: 'setup.py win32_manual_post_install.py'
2957 Out[4]: 'setup.py win32_manual_post_install.py'
2924
2958
2925 # a.s is useful to pass as a single command line:
2959 # a.s is useful to pass as a single command line:
2926 In [5]: !wc -l $a.s
2960 In [5]: !wc -l $a.s
2927 146 setup.py
2961 146 setup.py
2928 130 win32_manual_post_install.py
2962 130 win32_manual_post_install.py
2929 276 total
2963 276 total
2930
2964
2931 # while the list form is useful to loop over:
2965 # while the list form is useful to loop over:
2932 In [6]: for f in a.l:
2966 In [6]: for f in a.l:
2933 ...: !wc -l $f
2967 ...: !wc -l $f
2934 ...:
2968 ...:
2935 146 setup.py
2969 146 setup.py
2936 130 win32_manual_post_install.py
2970 130 win32_manual_post_install.py
2937
2971
2938 Similiarly, the lists returned by the -l option are also special, in
2972 Similiarly, the lists returned by the -l option are also special, in
2939 the sense that you can equally invoke the .s attribute on them to
2973 the sense that you can equally invoke the .s attribute on them to
2940 automatically get a whitespace-separated string from their contents:
2974 automatically get a whitespace-separated string from their contents:
2941
2975
2942 In [7]: sc -l b=ls *py
2976 In [7]: sc -l b=ls *py
2943
2977
2944 In [8]: b
2978 In [8]: b
2945 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2979 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2946
2980
2947 In [9]: b.s
2981 In [9]: b.s
2948 Out[9]: 'setup.py win32_manual_post_install.py'
2982 Out[9]: 'setup.py win32_manual_post_install.py'
2949
2983
2950 In summary, both the lists and strings used for ouptut capture have
2984 In summary, both the lists and strings used for ouptut capture have
2951 the following special attributes:
2985 the following special attributes:
2952
2986
2953 .l (or .list) : value as list.
2987 .l (or .list) : value as list.
2954 .n (or .nlstr): value as newline-separated string.
2988 .n (or .nlstr): value as newline-separated string.
2955 .s (or .spstr): value as space-separated string.
2989 .s (or .spstr): value as space-separated string.
2956 """
2990 """
2957
2991
2958 opts,args = self.parse_options(parameter_s,'lv')
2992 opts,args = self.parse_options(parameter_s,'lv')
2959 # Try to get a variable name and command to run
2993 # Try to get a variable name and command to run
2960 try:
2994 try:
2961 # the variable name must be obtained from the parse_options
2995 # the variable name must be obtained from the parse_options
2962 # output, which uses shlex.split to strip options out.
2996 # output, which uses shlex.split to strip options out.
2963 var,_ = args.split('=',1)
2997 var,_ = args.split('=',1)
2964 var = var.strip()
2998 var = var.strip()
2965 # But the the command has to be extracted from the original input
2999 # But the the command has to be extracted from the original input
2966 # parameter_s, not on what parse_options returns, to avoid the
3000 # parameter_s, not on what parse_options returns, to avoid the
2967 # quote stripping which shlex.split performs on it.
3001 # quote stripping which shlex.split performs on it.
2968 _,cmd = parameter_s.split('=',1)
3002 _,cmd = parameter_s.split('=',1)
2969 except ValueError:
3003 except ValueError:
2970 var,cmd = '',''
3004 var,cmd = '',''
2971 # If all looks ok, proceed
3005 # If all looks ok, proceed
2972 split = 'l' in opts
3006 split = 'l' in opts
2973 out = self.shell.getoutput(cmd, split=split)
3007 out = self.shell.getoutput(cmd, split=split)
2974 if opts.has_key('v'):
3008 if opts.has_key('v'):
2975 print '%s ==\n%s' % (var,pformat(out))
3009 print '%s ==\n%s' % (var,pformat(out))
2976 if var:
3010 if var:
2977 self.shell.user_ns.update({var:out})
3011 self.shell.user_ns.update({var:out})
2978 else:
3012 else:
2979 return out
3013 return out
2980
3014
2981 def magic_sx(self, parameter_s=''):
3015 def magic_sx(self, parameter_s=''):
2982 """Shell execute - run a shell command and capture its output.
3016 """Shell execute - run a shell command and capture its output.
2983
3017
2984 %sx command
3018 %sx command
2985
3019
2986 IPython will run the given command using commands.getoutput(), and
3020 IPython will run the given command using commands.getoutput(), and
2987 return the result formatted as a list (split on '\\n'). Since the
3021 return the result formatted as a list (split on '\\n'). Since the
2988 output is _returned_, it will be stored in ipython's regular output
3022 output is _returned_, it will be stored in ipython's regular output
2989 cache Out[N] and in the '_N' automatic variables.
3023 cache Out[N] and in the '_N' automatic variables.
2990
3024
2991 Notes:
3025 Notes:
2992
3026
2993 1) If an input line begins with '!!', then %sx is automatically
3027 1) If an input line begins with '!!', then %sx is automatically
2994 invoked. That is, while:
3028 invoked. That is, while:
2995 !ls
3029 !ls
2996 causes ipython to simply issue system('ls'), typing
3030 causes ipython to simply issue system('ls'), typing
2997 !!ls
3031 !!ls
2998 is a shorthand equivalent to:
3032 is a shorthand equivalent to:
2999 %sx ls
3033 %sx ls
3000
3034
3001 2) %sx differs from %sc in that %sx automatically splits into a list,
3035 2) %sx differs from %sc in that %sx automatically splits into a list,
3002 like '%sc -l'. The reason for this is to make it as easy as possible
3036 like '%sc -l'. The reason for this is to make it as easy as possible
3003 to process line-oriented shell output via further python commands.
3037 to process line-oriented shell output via further python commands.
3004 %sc is meant to provide much finer control, but requires more
3038 %sc is meant to provide much finer control, but requires more
3005 typing.
3039 typing.
3006
3040
3007 3) Just like %sc -l, this is a list with special attributes:
3041 3) Just like %sc -l, this is a list with special attributes:
3008
3042
3009 .l (or .list) : value as list.
3043 .l (or .list) : value as list.
3010 .n (or .nlstr): value as newline-separated string.
3044 .n (or .nlstr): value as newline-separated string.
3011 .s (or .spstr): value as whitespace-separated string.
3045 .s (or .spstr): value as whitespace-separated string.
3012
3046
3013 This is very useful when trying to use such lists as arguments to
3047 This is very useful when trying to use such lists as arguments to
3014 system commands."""
3048 system commands."""
3015
3049
3016 if parameter_s:
3050 if parameter_s:
3017 return self.shell.getoutput(parameter_s)
3051 return self.shell.getoutput(parameter_s)
3018
3052
3019 def magic_r(self, parameter_s=''):
3053 def magic_r(self, parameter_s=''):
3020 """Repeat previous input.
3054 """Repeat previous input.
3021
3055
3022 Note: Consider using the more powerfull %rep instead!
3056 Note: Consider using the more powerfull %rep instead!
3023
3057
3024 If given an argument, repeats the previous command which starts with
3058 If given an argument, repeats the previous command which starts with
3025 the same string, otherwise it just repeats the previous input.
3059 the same string, otherwise it just repeats the previous input.
3026
3060
3027 Shell escaped commands (with ! as first character) are not recognized
3061 Shell escaped commands (with ! as first character) are not recognized
3028 by this system, only pure python code and magic commands.
3062 by this system, only pure python code and magic commands.
3029 """
3063 """
3030
3064
3031 start = parameter_s.strip()
3065 start = parameter_s.strip()
3032 esc_magic = ESC_MAGIC
3066 esc_magic = ESC_MAGIC
3033 # Identify magic commands even if automagic is on (which means
3067 # Identify magic commands even if automagic is on (which means
3034 # the in-memory version is different from that typed by the user).
3068 # the in-memory version is different from that typed by the user).
3035 if self.shell.automagic:
3069 if self.shell.automagic:
3036 start_magic = esc_magic+start
3070 start_magic = esc_magic+start
3037 else:
3071 else:
3038 start_magic = start
3072 start_magic = start
3039 # Look through the input history in reverse
3073 # Look through the input history in reverse
3040 for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1):
3074 for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1):
3041 input = self.shell.history_manager.input_hist_parsed[n]
3075 input = self.shell.history_manager.input_hist_parsed[n]
3042 # skip plain 'r' lines so we don't recurse to infinity
3076 # skip plain 'r' lines so we don't recurse to infinity
3043 if input != '_ip.magic("r")\n' and \
3077 if input != '_ip.magic("r")\n' and \
3044 (input.startswith(start) or input.startswith(start_magic)):
3078 (input.startswith(start) or input.startswith(start_magic)):
3045 #print 'match',`input` # dbg
3079 #print 'match',`input` # dbg
3046 print 'Executing:',input,
3080 print 'Executing:',input,
3047 self.shell.run_cell(input)
3081 self.shell.run_cell(input)
3048 return
3082 return
3049 print 'No previous input matching `%s` found.' % start
3083 print 'No previous input matching `%s` found.' % start
3050
3084
3051
3085
3052 def magic_bookmark(self, parameter_s=''):
3086 def magic_bookmark(self, parameter_s=''):
3053 """Manage IPython's bookmark system.
3087 """Manage IPython's bookmark system.
3054
3088
3055 %bookmark <name> - set bookmark to current dir
3089 %bookmark <name> - set bookmark to current dir
3056 %bookmark <name> <dir> - set bookmark to <dir>
3090 %bookmark <name> <dir> - set bookmark to <dir>
3057 %bookmark -l - list all bookmarks
3091 %bookmark -l - list all bookmarks
3058 %bookmark -d <name> - remove bookmark
3092 %bookmark -d <name> - remove bookmark
3059 %bookmark -r - remove all bookmarks
3093 %bookmark -r - remove all bookmarks
3060
3094
3061 You can later on access a bookmarked folder with:
3095 You can later on access a bookmarked folder with:
3062 %cd -b <name>
3096 %cd -b <name>
3063 or simply '%cd <name>' if there is no directory called <name> AND
3097 or simply '%cd <name>' if there is no directory called <name> AND
3064 there is such a bookmark defined.
3098 there is such a bookmark defined.
3065
3099
3066 Your bookmarks persist through IPython sessions, but they are
3100 Your bookmarks persist through IPython sessions, but they are
3067 associated with each profile."""
3101 associated with each profile."""
3068
3102
3069 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3103 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3070 if len(args) > 2:
3104 if len(args) > 2:
3071 raise UsageError("%bookmark: too many arguments")
3105 raise UsageError("%bookmark: too many arguments")
3072
3106
3073 bkms = self.db.get('bookmarks',{})
3107 bkms = self.db.get('bookmarks',{})
3074
3108
3075 if opts.has_key('d'):
3109 if opts.has_key('d'):
3076 try:
3110 try:
3077 todel = args[0]
3111 todel = args[0]
3078 except IndexError:
3112 except IndexError:
3079 raise UsageError(
3113 raise UsageError(
3080 "%bookmark -d: must provide a bookmark to delete")
3114 "%bookmark -d: must provide a bookmark to delete")
3081 else:
3115 else:
3082 try:
3116 try:
3083 del bkms[todel]
3117 del bkms[todel]
3084 except KeyError:
3118 except KeyError:
3085 raise UsageError(
3119 raise UsageError(
3086 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3120 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3087
3121
3088 elif opts.has_key('r'):
3122 elif opts.has_key('r'):
3089 bkms = {}
3123 bkms = {}
3090 elif opts.has_key('l'):
3124 elif opts.has_key('l'):
3091 bks = bkms.keys()
3125 bks = bkms.keys()
3092 bks.sort()
3126 bks.sort()
3093 if bks:
3127 if bks:
3094 size = max(map(len,bks))
3128 size = max(map(len,bks))
3095 else:
3129 else:
3096 size = 0
3130 size = 0
3097 fmt = '%-'+str(size)+'s -> %s'
3131 fmt = '%-'+str(size)+'s -> %s'
3098 print 'Current bookmarks:'
3132 print 'Current bookmarks:'
3099 for bk in bks:
3133 for bk in bks:
3100 print fmt % (bk,bkms[bk])
3134 print fmt % (bk,bkms[bk])
3101 else:
3135 else:
3102 if not args:
3136 if not args:
3103 raise UsageError("%bookmark: You must specify the bookmark name")
3137 raise UsageError("%bookmark: You must specify the bookmark name")
3104 elif len(args)==1:
3138 elif len(args)==1:
3105 bkms[args[0]] = os.getcwd()
3139 bkms[args[0]] = os.getcwd()
3106 elif len(args)==2:
3140 elif len(args)==2:
3107 bkms[args[0]] = args[1]
3141 bkms[args[0]] = args[1]
3108 self.db['bookmarks'] = bkms
3142 self.db['bookmarks'] = bkms
3109
3143
3110 def magic_pycat(self, parameter_s=''):
3144 def magic_pycat(self, parameter_s=''):
3111 """Show a syntax-highlighted file through a pager.
3145 """Show a syntax-highlighted file through a pager.
3112
3146
3113 This magic is similar to the cat utility, but it will assume the file
3147 This magic is similar to the cat utility, but it will assume the file
3114 to be Python source and will show it with syntax highlighting. """
3148 to be Python source and will show it with syntax highlighting. """
3115
3149
3116 try:
3150 try:
3117 filename = get_py_filename(parameter_s)
3151 filename = get_py_filename(parameter_s)
3118 cont = file_read(filename)
3152 cont = file_read(filename)
3119 except IOError:
3153 except IOError:
3120 try:
3154 try:
3121 cont = eval(parameter_s,self.user_ns)
3155 cont = eval(parameter_s,self.user_ns)
3122 except NameError:
3156 except NameError:
3123 cont = None
3157 cont = None
3124 if cont is None:
3158 if cont is None:
3125 print "Error: no such file or variable"
3159 print "Error: no such file or variable"
3126 return
3160 return
3127
3161
3128 page.page(self.shell.pycolorize(cont))
3162 page.page(self.shell.pycolorize(cont))
3129
3163
3130 def _rerun_pasted(self):
3164 def _rerun_pasted(self):
3131 """ Rerun a previously pasted command.
3165 """ Rerun a previously pasted command.
3132 """
3166 """
3133 b = self.user_ns.get('pasted_block', None)
3167 b = self.user_ns.get('pasted_block', None)
3134 if b is None:
3168 if b is None:
3135 raise UsageError('No previous pasted block available')
3169 raise UsageError('No previous pasted block available')
3136 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3170 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3137 exec b in self.user_ns
3171 exec b in self.user_ns
3138
3172
3139 def _get_pasted_lines(self, sentinel):
3173 def _get_pasted_lines(self, sentinel):
3140 """ Yield pasted lines until the user enters the given sentinel value.
3174 """ Yield pasted lines until the user enters the given sentinel value.
3141 """
3175 """
3142 from IPython.core import interactiveshell
3176 from IPython.core import interactiveshell
3143 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3177 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3144 while True:
3178 while True:
3145 l = interactiveshell.raw_input_original(':')
3179 l = interactiveshell.raw_input_original(':')
3146 if l == sentinel:
3180 if l == sentinel:
3147 return
3181 return
3148 else:
3182 else:
3149 yield l
3183 yield l
3150
3184
3151 def _strip_pasted_lines_for_code(self, raw_lines):
3185 def _strip_pasted_lines_for_code(self, raw_lines):
3152 """ Strip non-code parts of a sequence of lines to return a block of
3186 """ Strip non-code parts of a sequence of lines to return a block of
3153 code.
3187 code.
3154 """
3188 """
3155 # Regular expressions that declare text we strip from the input:
3189 # Regular expressions that declare text we strip from the input:
3156 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3190 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3157 r'^\s*(\s?>)+', # Python input prompt
3191 r'^\s*(\s?>)+', # Python input prompt
3158 r'^\s*\.{3,}', # Continuation prompts
3192 r'^\s*\.{3,}', # Continuation prompts
3159 r'^\++',
3193 r'^\++',
3160 ]
3194 ]
3161
3195
3162 strip_from_start = map(re.compile,strip_re)
3196 strip_from_start = map(re.compile,strip_re)
3163
3197
3164 lines = []
3198 lines = []
3165 for l in raw_lines:
3199 for l in raw_lines:
3166 for pat in strip_from_start:
3200 for pat in strip_from_start:
3167 l = pat.sub('',l)
3201 l = pat.sub('',l)
3168 lines.append(l)
3202 lines.append(l)
3169
3203
3170 block = "\n".join(lines) + '\n'
3204 block = "\n".join(lines) + '\n'
3171 #print "block:\n",block
3205 #print "block:\n",block
3172 return block
3206 return block
3173
3207
3174 def _execute_block(self, block, par):
3208 def _execute_block(self, block, par):
3175 """ Execute a block, or store it in a variable, per the user's request.
3209 """ Execute a block, or store it in a variable, per the user's request.
3176 """
3210 """
3177 if not par:
3211 if not par:
3178 b = textwrap.dedent(block)
3212 b = textwrap.dedent(block)
3179 self.user_ns['pasted_block'] = b
3213 self.user_ns['pasted_block'] = b
3180 exec b in self.user_ns
3214 exec b in self.user_ns
3181 else:
3215 else:
3182 self.user_ns[par] = SList(block.splitlines())
3216 self.user_ns[par] = SList(block.splitlines())
3183 print "Block assigned to '%s'" % par
3217 print "Block assigned to '%s'" % par
3184
3218
3185 def magic_quickref(self,arg):
3219 def magic_quickref(self,arg):
3186 """ Show a quick reference sheet """
3220 """ Show a quick reference sheet """
3187 import IPython.core.usage
3221 import IPython.core.usage
3188 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3222 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3189
3223
3190 page.page(qr)
3224 page.page(qr)
3191
3225
3192 def magic_doctest_mode(self,parameter_s=''):
3226 def magic_doctest_mode(self,parameter_s=''):
3193 """Toggle doctest mode on and off.
3227 """Toggle doctest mode on and off.
3194
3228
3195 This mode is intended to make IPython behave as much as possible like a
3229 This mode is intended to make IPython behave as much as possible like a
3196 plain Python shell, from the perspective of how its prompts, exceptions
3230 plain Python shell, from the perspective of how its prompts, exceptions
3197 and output look. This makes it easy to copy and paste parts of a
3231 and output look. This makes it easy to copy and paste parts of a
3198 session into doctests. It does so by:
3232 session into doctests. It does so by:
3199
3233
3200 - Changing the prompts to the classic ``>>>`` ones.
3234 - Changing the prompts to the classic ``>>>`` ones.
3201 - Changing the exception reporting mode to 'Plain'.
3235 - Changing the exception reporting mode to 'Plain'.
3202 - Disabling pretty-printing of output.
3236 - Disabling pretty-printing of output.
3203
3237
3204 Note that IPython also supports the pasting of code snippets that have
3238 Note that IPython also supports the pasting of code snippets that have
3205 leading '>>>' and '...' prompts in them. This means that you can paste
3239 leading '>>>' and '...' prompts in them. This means that you can paste
3206 doctests from files or docstrings (even if they have leading
3240 doctests from files or docstrings (even if they have leading
3207 whitespace), and the code will execute correctly. You can then use
3241 whitespace), and the code will execute correctly. You can then use
3208 '%history -t' to see the translated history; this will give you the
3242 '%history -t' to see the translated history; this will give you the
3209 input after removal of all the leading prompts and whitespace, which
3243 input after removal of all the leading prompts and whitespace, which
3210 can be pasted back into an editor.
3244 can be pasted back into an editor.
3211
3245
3212 With these features, you can switch into this mode easily whenever you
3246 With these features, you can switch into this mode easily whenever you
3213 need to do testing and changes to doctests, without having to leave
3247 need to do testing and changes to doctests, without having to leave
3214 your existing IPython session.
3248 your existing IPython session.
3215 """
3249 """
3216
3250
3217 from IPython.utils.ipstruct import Struct
3251 from IPython.utils.ipstruct import Struct
3218
3252
3219 # Shorthands
3253 # Shorthands
3220 shell = self.shell
3254 shell = self.shell
3221 oc = shell.displayhook
3255 oc = shell.displayhook
3222 meta = shell.meta
3256 meta = shell.meta
3223 disp_formatter = self.shell.display_formatter
3257 disp_formatter = self.shell.display_formatter
3224 ptformatter = disp_formatter.formatters['text/plain']
3258 ptformatter = disp_formatter.formatters['text/plain']
3225 # dstore is a data store kept in the instance metadata bag to track any
3259 # dstore is a data store kept in the instance metadata bag to track any
3226 # changes we make, so we can undo them later.
3260 # changes we make, so we can undo them later.
3227 dstore = meta.setdefault('doctest_mode',Struct())
3261 dstore = meta.setdefault('doctest_mode',Struct())
3228 save_dstore = dstore.setdefault
3262 save_dstore = dstore.setdefault
3229
3263
3230 # save a few values we'll need to recover later
3264 # save a few values we'll need to recover later
3231 mode = save_dstore('mode',False)
3265 mode = save_dstore('mode',False)
3232 save_dstore('rc_pprint',ptformatter.pprint)
3266 save_dstore('rc_pprint',ptformatter.pprint)
3233 save_dstore('xmode',shell.InteractiveTB.mode)
3267 save_dstore('xmode',shell.InteractiveTB.mode)
3234 save_dstore('rc_separate_out',shell.separate_out)
3268 save_dstore('rc_separate_out',shell.separate_out)
3235 save_dstore('rc_separate_out2',shell.separate_out2)
3269 save_dstore('rc_separate_out2',shell.separate_out2)
3236 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3270 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3237 save_dstore('rc_separate_in',shell.separate_in)
3271 save_dstore('rc_separate_in',shell.separate_in)
3238 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3272 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3239
3273
3240 if mode == False:
3274 if mode == False:
3241 # turn on
3275 # turn on
3242 oc.prompt1.p_template = '>>> '
3276 oc.prompt1.p_template = '>>> '
3243 oc.prompt2.p_template = '... '
3277 oc.prompt2.p_template = '... '
3244 oc.prompt_out.p_template = ''
3278 oc.prompt_out.p_template = ''
3245
3279
3246 # Prompt separators like plain python
3280 # Prompt separators like plain python
3247 oc.input_sep = oc.prompt1.sep = ''
3281 oc.input_sep = oc.prompt1.sep = ''
3248 oc.output_sep = ''
3282 oc.output_sep = ''
3249 oc.output_sep2 = ''
3283 oc.output_sep2 = ''
3250
3284
3251 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3285 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3252 oc.prompt_out.pad_left = False
3286 oc.prompt_out.pad_left = False
3253
3287
3254 ptformatter.pprint = False
3288 ptformatter.pprint = False
3255 disp_formatter.plain_text_only = True
3289 disp_formatter.plain_text_only = True
3256
3290
3257 shell.magic_xmode('Plain')
3291 shell.magic_xmode('Plain')
3258 else:
3292 else:
3259 # turn off
3293 # turn off
3260 oc.prompt1.p_template = shell.prompt_in1
3294 oc.prompt1.p_template = shell.prompt_in1
3261 oc.prompt2.p_template = shell.prompt_in2
3295 oc.prompt2.p_template = shell.prompt_in2
3262 oc.prompt_out.p_template = shell.prompt_out
3296 oc.prompt_out.p_template = shell.prompt_out
3263
3297
3264 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3298 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3265
3299
3266 oc.output_sep = dstore.rc_separate_out
3300 oc.output_sep = dstore.rc_separate_out
3267 oc.output_sep2 = dstore.rc_separate_out2
3301 oc.output_sep2 = dstore.rc_separate_out2
3268
3302
3269 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3303 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3270 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3304 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3271
3305
3272 ptformatter.pprint = dstore.rc_pprint
3306 ptformatter.pprint = dstore.rc_pprint
3273 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3307 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3274
3308
3275 shell.magic_xmode(dstore.xmode)
3309 shell.magic_xmode(dstore.xmode)
3276
3310
3277 # Store new mode and inform
3311 # Store new mode and inform
3278 dstore.mode = bool(1-int(mode))
3312 dstore.mode = bool(1-int(mode))
3279 mode_label = ['OFF','ON'][dstore.mode]
3313 mode_label = ['OFF','ON'][dstore.mode]
3280 print 'Doctest mode is:', mode_label
3314 print 'Doctest mode is:', mode_label
3281
3315
3282 def magic_gui(self, parameter_s=''):
3316 def magic_gui(self, parameter_s=''):
3283 """Enable or disable IPython GUI event loop integration.
3317 """Enable or disable IPython GUI event loop integration.
3284
3318
3285 %gui [GUINAME]
3319 %gui [GUINAME]
3286
3320
3287 This magic replaces IPython's threaded shells that were activated
3321 This magic replaces IPython's threaded shells that were activated
3288 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3322 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3289 can now be enabled, disabled and swtiched at runtime and keyboard
3323 can now be enabled, disabled and swtiched at runtime and keyboard
3290 interrupts should work without any problems. The following toolkits
3324 interrupts should work without any problems. The following toolkits
3291 are supported: wxPython, PyQt4, PyGTK, and Tk::
3325 are supported: wxPython, PyQt4, PyGTK, and Tk::
3292
3326
3293 %gui wx # enable wxPython event loop integration
3327 %gui wx # enable wxPython event loop integration
3294 %gui qt4|qt # enable PyQt4 event loop integration
3328 %gui qt4|qt # enable PyQt4 event loop integration
3295 %gui gtk # enable PyGTK event loop integration
3329 %gui gtk # enable PyGTK event loop integration
3296 %gui tk # enable Tk event loop integration
3330 %gui tk # enable Tk event loop integration
3297 %gui # disable all event loop integration
3331 %gui # disable all event loop integration
3298
3332
3299 WARNING: after any of these has been called you can simply create
3333 WARNING: after any of these has been called you can simply create
3300 an application object, but DO NOT start the event loop yourself, as
3334 an application object, but DO NOT start the event loop yourself, as
3301 we have already handled that.
3335 we have already handled that.
3302 """
3336 """
3303 from IPython.lib.inputhook import enable_gui
3337 from IPython.lib.inputhook import enable_gui
3304 opts, arg = self.parse_options(parameter_s, '')
3338 opts, arg = self.parse_options(parameter_s, '')
3305 if arg=='': arg = None
3339 if arg=='': arg = None
3306 return enable_gui(arg)
3340 return enable_gui(arg)
3307
3341
3308 def magic_load_ext(self, module_str):
3342 def magic_load_ext(self, module_str):
3309 """Load an IPython extension by its module name."""
3343 """Load an IPython extension by its module name."""
3310 return self.extension_manager.load_extension(module_str)
3344 return self.extension_manager.load_extension(module_str)
3311
3345
3312 def magic_unload_ext(self, module_str):
3346 def magic_unload_ext(self, module_str):
3313 """Unload an IPython extension by its module name."""
3347 """Unload an IPython extension by its module name."""
3314 self.extension_manager.unload_extension(module_str)
3348 self.extension_manager.unload_extension(module_str)
3315
3349
3316 def magic_reload_ext(self, module_str):
3350 def magic_reload_ext(self, module_str):
3317 """Reload an IPython extension by its module name."""
3351 """Reload an IPython extension by its module name."""
3318 self.extension_manager.reload_extension(module_str)
3352 self.extension_manager.reload_extension(module_str)
3319
3353
3320 @testdec.skip_doctest
3354 @testdec.skip_doctest
3321 def magic_install_profiles(self, s):
3355 def magic_install_profiles(self, s):
3322 """Install the default IPython profiles into the .ipython dir.
3356 """Install the default IPython profiles into the .ipython dir.
3323
3357
3324 If the default profiles have already been installed, they will not
3358 If the default profiles have already been installed, they will not
3325 be overwritten. You can force overwriting them by using the ``-o``
3359 be overwritten. You can force overwriting them by using the ``-o``
3326 option::
3360 option::
3327
3361
3328 In [1]: %install_profiles -o
3362 In [1]: %install_profiles -o
3329 """
3363 """
3330 if '-o' in s:
3364 if '-o' in s:
3331 overwrite = True
3365 overwrite = True
3332 else:
3366 else:
3333 overwrite = False
3367 overwrite = False
3334 from IPython.config import profile
3368 from IPython.config import profile
3335 profile_dir = os.path.split(profile.__file__)[0]
3369 profile_dir = os.path.split(profile.__file__)[0]
3336 ipython_dir = self.ipython_dir
3370 ipython_dir = self.ipython_dir
3337 files = os.listdir(profile_dir)
3371 files = os.listdir(profile_dir)
3338
3372
3339 to_install = []
3373 to_install = []
3340 for f in files:
3374 for f in files:
3341 if f.startswith('ipython_config'):
3375 if f.startswith('ipython_config'):
3342 src = os.path.join(profile_dir, f)
3376 src = os.path.join(profile_dir, f)
3343 dst = os.path.join(ipython_dir, f)
3377 dst = os.path.join(ipython_dir, f)
3344 if (not os.path.isfile(dst)) or overwrite:
3378 if (not os.path.isfile(dst)) or overwrite:
3345 to_install.append((f, src, dst))
3379 to_install.append((f, src, dst))
3346 if len(to_install)>0:
3380 if len(to_install)>0:
3347 print "Installing profiles to: ", ipython_dir
3381 print "Installing profiles to: ", ipython_dir
3348 for (f, src, dst) in to_install:
3382 for (f, src, dst) in to_install:
3349 shutil.copy(src, dst)
3383 shutil.copy(src, dst)
3350 print " %s" % f
3384 print " %s" % f
3351
3385
3352 def magic_install_default_config(self, s):
3386 def magic_install_default_config(self, s):
3353 """Install IPython's default config file into the .ipython dir.
3387 """Install IPython's default config file into the .ipython dir.
3354
3388
3355 If the default config file (:file:`ipython_config.py`) is already
3389 If the default config file (:file:`ipython_config.py`) is already
3356 installed, it will not be overwritten. You can force overwriting
3390 installed, it will not be overwritten. You can force overwriting
3357 by using the ``-o`` option::
3391 by using the ``-o`` option::
3358
3392
3359 In [1]: %install_default_config
3393 In [1]: %install_default_config
3360 """
3394 """
3361 if '-o' in s:
3395 if '-o' in s:
3362 overwrite = True
3396 overwrite = True
3363 else:
3397 else:
3364 overwrite = False
3398 overwrite = False
3365 from IPython.config import default
3399 from IPython.config import default
3366 config_dir = os.path.split(default.__file__)[0]
3400 config_dir = os.path.split(default.__file__)[0]
3367 ipython_dir = self.ipython_dir
3401 ipython_dir = self.ipython_dir
3368 default_config_file_name = 'ipython_config.py'
3402 default_config_file_name = 'ipython_config.py'
3369 src = os.path.join(config_dir, default_config_file_name)
3403 src = os.path.join(config_dir, default_config_file_name)
3370 dst = os.path.join(ipython_dir, default_config_file_name)
3404 dst = os.path.join(ipython_dir, default_config_file_name)
3371 if (not os.path.isfile(dst)) or overwrite:
3405 if (not os.path.isfile(dst)) or overwrite:
3372 shutil.copy(src, dst)
3406 shutil.copy(src, dst)
3373 print "Installing default config file: %s" % dst
3407 print "Installing default config file: %s" % dst
3374
3408
3375 # Pylab support: simple wrappers that activate pylab, load gui input
3409 # Pylab support: simple wrappers that activate pylab, load gui input
3376 # handling and modify slightly %run
3410 # handling and modify slightly %run
3377
3411
3378 @testdec.skip_doctest
3412 @testdec.skip_doctest
3379 def _pylab_magic_run(self, parameter_s=''):
3413 def _pylab_magic_run(self, parameter_s=''):
3380 Magic.magic_run(self, parameter_s,
3414 Magic.magic_run(self, parameter_s,
3381 runner=mpl_runner(self.shell.safe_execfile))
3415 runner=mpl_runner(self.shell.safe_execfile))
3382
3416
3383 _pylab_magic_run.__doc__ = magic_run.__doc__
3417 _pylab_magic_run.__doc__ = magic_run.__doc__
3384
3418
3385 @testdec.skip_doctest
3419 @testdec.skip_doctest
3386 def magic_pylab(self, s):
3420 def magic_pylab(self, s):
3387 """Load numpy and matplotlib to work interactively.
3421 """Load numpy and matplotlib to work interactively.
3388
3422
3389 %pylab [GUINAME]
3423 %pylab [GUINAME]
3390
3424
3391 This function lets you activate pylab (matplotlib, numpy and
3425 This function lets you activate pylab (matplotlib, numpy and
3392 interactive support) at any point during an IPython session.
3426 interactive support) at any point during an IPython session.
3393
3427
3394 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3428 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3395 pylab and mlab, as well as all names from numpy and pylab.
3429 pylab and mlab, as well as all names from numpy and pylab.
3396
3430
3397 Parameters
3431 Parameters
3398 ----------
3432 ----------
3399 guiname : optional
3433 guiname : optional
3400 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3434 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3401 'tk'). If given, the corresponding Matplotlib backend is used,
3435 'tk'). If given, the corresponding Matplotlib backend is used,
3402 otherwise matplotlib's default (which you can override in your
3436 otherwise matplotlib's default (which you can override in your
3403 matplotlib config file) is used.
3437 matplotlib config file) is used.
3404
3438
3405 Examples
3439 Examples
3406 --------
3440 --------
3407 In this case, where the MPL default is TkAgg:
3441 In this case, where the MPL default is TkAgg:
3408 In [2]: %pylab
3442 In [2]: %pylab
3409
3443
3410 Welcome to pylab, a matplotlib-based Python environment.
3444 Welcome to pylab, a matplotlib-based Python environment.
3411 Backend in use: TkAgg
3445 Backend in use: TkAgg
3412 For more information, type 'help(pylab)'.
3446 For more information, type 'help(pylab)'.
3413
3447
3414 But you can explicitly request a different backend:
3448 But you can explicitly request a different backend:
3415 In [3]: %pylab qt
3449 In [3]: %pylab qt
3416
3450
3417 Welcome to pylab, a matplotlib-based Python environment.
3451 Welcome to pylab, a matplotlib-based Python environment.
3418 Backend in use: Qt4Agg
3452 Backend in use: Qt4Agg
3419 For more information, type 'help(pylab)'.
3453 For more information, type 'help(pylab)'.
3420 """
3454 """
3421 self.shell.enable_pylab(s)
3455 self.shell.enable_pylab(s)
3422
3456
3423 def magic_tb(self, s):
3457 def magic_tb(self, s):
3424 """Print the last traceback with the currently active exception mode.
3458 """Print the last traceback with the currently active exception mode.
3425
3459
3426 See %xmode for changing exception reporting modes."""
3460 See %xmode for changing exception reporting modes."""
3427 self.shell.showtraceback()
3461 self.shell.showtraceback()
3428
3462
3429 # end Magic
3463 # end Magic
@@ -1,614 +1,625 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 from contextlib import nested
19 from contextlib import nested
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23
23
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
26 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.lib.inputhook import enable_gui
27 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.pylabtools import pylab_activate
28 from IPython.lib.pylabtools import pylab_activate
29 from IPython.utils.terminal import toggle_set_term_title, set_term_title
29 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.process import abbrev_cwd
30 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
32 from IPython.utils.text import num_ini_spaces
32 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.traitlets import Int, Str, CBool
33 from IPython.utils.traitlets import Int, Str, CBool
34
34
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Utilities
37 # Utilities
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40
40
41 def get_default_editor():
41 def get_default_editor():
42 try:
42 try:
43 ed = os.environ['EDITOR']
43 ed = os.environ['EDITOR']
44 except KeyError:
44 except KeyError:
45 if os.name == 'posix':
45 if os.name == 'posix':
46 ed = 'vi' # the only one guaranteed to be there!
46 ed = 'vi' # the only one guaranteed to be there!
47 else:
47 else:
48 ed = 'notepad' # same in Windows!
48 ed = 'notepad' # same in Windows!
49 return ed
49 return ed
50
50
51
51
52 # store the builtin raw_input globally, and use this always, in case user code
52 # store the builtin raw_input globally, and use this always, in case user code
53 # overwrites it (like wx.py.PyShell does)
53 # overwrites it (like wx.py.PyShell does)
54 raw_input_original = raw_input
54 raw_input_original = raw_input
55
55
56
56
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58 # Main class
58 # Main class
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60
60
61
61
62 class TerminalInteractiveShell(InteractiveShell):
62 class TerminalInteractiveShell(InteractiveShell):
63
63
64 autoedit_syntax = CBool(False, config=True)
64 autoedit_syntax = CBool(False, config=True)
65 banner = Str('')
65 banner = Str('')
66 banner1 = Str(default_banner, config=True)
66 banner1 = Str(default_banner, config=True)
67 banner2 = Str('', config=True)
67 banner2 = Str('', config=True)
68 confirm_exit = CBool(True, config=True)
68 confirm_exit = CBool(True, config=True)
69 # This display_banner only controls whether or not self.show_banner()
69 # This display_banner only controls whether or not self.show_banner()
70 # is called when mainloop/interact are called. The default is False
70 # is called when mainloop/interact are called. The default is False
71 # because for the terminal based application, the banner behavior
71 # because for the terminal based application, the banner behavior
72 # is controlled by Global.display_banner, which IPythonApp looks at
72 # is controlled by Global.display_banner, which IPythonApp looks at
73 # to determine if *it* should call show_banner() by hand or not.
73 # to determine if *it* should call show_banner() by hand or not.
74 display_banner = CBool(False) # This isn't configurable!
74 display_banner = CBool(False) # This isn't configurable!
75 embedded = CBool(False)
75 embedded = CBool(False)
76 embedded_active = CBool(False)
76 embedded_active = CBool(False)
77 editor = Str(get_default_editor(), config=True)
77 editor = Str(get_default_editor(), config=True)
78 pager = Str('less', config=True)
78 pager = Str('less', config=True)
79
79
80 screen_length = Int(0, config=True)
80 screen_length = Int(0, config=True)
81 term_title = CBool(False, config=True)
81 term_title = CBool(False, config=True)
82
82
83 def __init__(self, config=None, ipython_dir=None, user_ns=None,
83 def __init__(self, config=None, ipython_dir=None, user_ns=None,
84 user_global_ns=None, custom_exceptions=((),None),
84 user_global_ns=None, custom_exceptions=((),None),
85 usage=None, banner1=None, banner2=None,
85 usage=None, banner1=None, banner2=None,
86 display_banner=None):
86 display_banner=None):
87
87
88 super(TerminalInteractiveShell, self).__init__(
88 super(TerminalInteractiveShell, self).__init__(
89 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
89 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
90 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
90 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
91 )
91 )
92 self.init_term_title()
92 self.init_term_title()
93 self.init_usage(usage)
93 self.init_usage(usage)
94 self.init_banner(banner1, banner2, display_banner)
94 self.init_banner(banner1, banner2, display_banner)
95
95
96 #-------------------------------------------------------------------------
96 #-------------------------------------------------------------------------
97 # Things related to the terminal
97 # Things related to the terminal
98 #-------------------------------------------------------------------------
98 #-------------------------------------------------------------------------
99
99
100 @property
100 @property
101 def usable_screen_length(self):
101 def usable_screen_length(self):
102 if self.screen_length == 0:
102 if self.screen_length == 0:
103 return 0
103 return 0
104 else:
104 else:
105 num_lines_bot = self.separate_in.count('\n')+1
105 num_lines_bot = self.separate_in.count('\n')+1
106 return self.screen_length - num_lines_bot
106 return self.screen_length - num_lines_bot
107
107
108 def init_term_title(self):
108 def init_term_title(self):
109 # Enable or disable the terminal title.
109 # Enable or disable the terminal title.
110 if self.term_title:
110 if self.term_title:
111 toggle_set_term_title(True)
111 toggle_set_term_title(True)
112 set_term_title('IPython: ' + abbrev_cwd())
112 set_term_title('IPython: ' + abbrev_cwd())
113 else:
113 else:
114 toggle_set_term_title(False)
114 toggle_set_term_title(False)
115
115
116 #-------------------------------------------------------------------------
116 #-------------------------------------------------------------------------
117 # Things related to aliases
117 # Things related to aliases
118 #-------------------------------------------------------------------------
118 #-------------------------------------------------------------------------
119
119
120 def init_alias(self):
120 def init_alias(self):
121 # The parent class defines aliases that can be safely used with any
121 # The parent class defines aliases that can be safely used with any
122 # frontend.
122 # frontend.
123 super(TerminalInteractiveShell, self).init_alias()
123 super(TerminalInteractiveShell, self).init_alias()
124
124
125 # Now define aliases that only make sense on the terminal, because they
125 # Now define aliases that only make sense on the terminal, because they
126 # need direct access to the console in a way that we can't emulate in
126 # need direct access to the console in a way that we can't emulate in
127 # GUI or web frontend
127 # GUI or web frontend
128 if os.name == 'posix':
128 if os.name == 'posix':
129 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
129 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
130 ('man', 'man')]
130 ('man', 'man')]
131 elif os.name == 'nt':
131 elif os.name == 'nt':
132 aliases = [('cls', 'cls')]
132 aliases = [('cls', 'cls')]
133
133
134
134
135 for name, cmd in aliases:
135 for name, cmd in aliases:
136 self.alias_manager.define_alias(name, cmd)
136 self.alias_manager.define_alias(name, cmd)
137
137
138 #-------------------------------------------------------------------------
138 #-------------------------------------------------------------------------
139 # Things related to the banner and usage
139 # Things related to the banner and usage
140 #-------------------------------------------------------------------------
140 #-------------------------------------------------------------------------
141
141
142 def _banner1_changed(self):
142 def _banner1_changed(self):
143 self.compute_banner()
143 self.compute_banner()
144
144
145 def _banner2_changed(self):
145 def _banner2_changed(self):
146 self.compute_banner()
146 self.compute_banner()
147
147
148 def _term_title_changed(self, name, new_value):
148 def _term_title_changed(self, name, new_value):
149 self.init_term_title()
149 self.init_term_title()
150
150
151 def init_banner(self, banner1, banner2, display_banner):
151 def init_banner(self, banner1, banner2, display_banner):
152 if banner1 is not None:
152 if banner1 is not None:
153 self.banner1 = banner1
153 self.banner1 = banner1
154 if banner2 is not None:
154 if banner2 is not None:
155 self.banner2 = banner2
155 self.banner2 = banner2
156 if display_banner is not None:
156 if display_banner is not None:
157 self.display_banner = display_banner
157 self.display_banner = display_banner
158 self.compute_banner()
158 self.compute_banner()
159
159
160 def show_banner(self, banner=None):
160 def show_banner(self, banner=None):
161 if banner is None:
161 if banner is None:
162 banner = self.banner
162 banner = self.banner
163 self.write(banner)
163 self.write(banner)
164
164
165 def compute_banner(self):
165 def compute_banner(self):
166 self.banner = self.banner1
166 self.banner = self.banner1
167 if self.profile:
167 if self.profile:
168 self.banner += '\nIPython profile: %s\n' % self.profile
168 self.banner += '\nIPython profile: %s\n' % self.profile
169 if self.banner2:
169 if self.banner2:
170 self.banner += '\n' + self.banner2
170 self.banner += '\n' + self.banner2
171
171
172 def init_usage(self, usage=None):
172 def init_usage(self, usage=None):
173 if usage is None:
173 if usage is None:
174 self.usage = interactive_usage
174 self.usage = interactive_usage
175 else:
175 else:
176 self.usage = usage
176 self.usage = usage
177
177
178 #-------------------------------------------------------------------------
178 #-------------------------------------------------------------------------
179 # Mainloop and code execution logic
179 # Mainloop and code execution logic
180 #-------------------------------------------------------------------------
180 #-------------------------------------------------------------------------
181
181
182 def mainloop(self, display_banner=None):
182 def mainloop(self, display_banner=None):
183 """Start the mainloop.
183 """Start the mainloop.
184
184
185 If an optional banner argument is given, it will override the
185 If an optional banner argument is given, it will override the
186 internally created default banner.
186 internally created default banner.
187 """
187 """
188
188
189 with nested(self.builtin_trap, self.display_trap):
189 with nested(self.builtin_trap, self.display_trap):
190
190
191 # if you run stuff with -c <cmd>, raw hist is not updated
191 # if you run stuff with -c <cmd>, raw hist is not updated
192 # ensure that it's in sync
192 # ensure that it's in sync
193 self.history_manager.sync_inputs()
193 self.history_manager.sync_inputs()
194
194
195 while 1:
195 while 1:
196 try:
196 try:
197 self.interact(display_banner=display_banner)
197 self.interact(display_banner=display_banner)
198 #self.interact_with_readline()
198 #self.interact_with_readline()
199 # XXX for testing of a readline-decoupled repl loop, call
199 # XXX for testing of a readline-decoupled repl loop, call
200 # interact_with_readline above
200 # interact_with_readline above
201 break
201 break
202 except KeyboardInterrupt:
202 except KeyboardInterrupt:
203 # this should not be necessary, but KeyboardInterrupt
203 # this should not be necessary, but KeyboardInterrupt
204 # handling seems rather unpredictable...
204 # handling seems rather unpredictable...
205 self.write("\nKeyboardInterrupt in interact()\n")
205 self.write("\nKeyboardInterrupt in interact()\n")
206
206
207 def interact(self, display_banner=None):
207 def interact(self, display_banner=None):
208 """Closely emulate the interactive Python console."""
208 """Closely emulate the interactive Python console."""
209
209
210 # batch run -> do not interact
210 # batch run -> do not interact
211 if self.exit_now:
211 if self.exit_now:
212 return
212 return
213
213
214 if display_banner is None:
214 if display_banner is None:
215 display_banner = self.display_banner
215 display_banner = self.display_banner
216 if display_banner:
216 if display_banner:
217 self.show_banner()
217 self.show_banner()
218
218
219 more = False
219 more = False
220
220
221 # Mark activity in the builtins
221 # Mark activity in the builtins
222 __builtin__.__dict__['__IPYTHON__active'] += 1
222 __builtin__.__dict__['__IPYTHON__active'] += 1
223
223
224 if self.has_readline:
224 if self.has_readline:
225 self.readline_startup_hook(self.pre_readline)
225 self.readline_startup_hook(self.pre_readline)
226 # exit_now is set by a call to %Exit or %Quit, through the
226 # exit_now is set by a call to %Exit or %Quit, through the
227 # ask_exit callback.
227 # ask_exit callback.
228
228
229 while not self.exit_now:
229 while not self.exit_now:
230 self.hooks.pre_prompt_hook()
230 self.hooks.pre_prompt_hook()
231 if more:
231 if more:
232 try:
232 try:
233 prompt = self.hooks.generate_prompt(True)
233 prompt = self.hooks.generate_prompt(True)
234 except:
234 except:
235 self.showtraceback()
235 self.showtraceback()
236 if self.autoindent:
236 if self.autoindent:
237 self.rl_do_indent = True
237 self.rl_do_indent = True
238
238
239 else:
239 else:
240 try:
240 try:
241 prompt = self.hooks.generate_prompt(False)
241 prompt = self.hooks.generate_prompt(False)
242 except:
242 except:
243 self.showtraceback()
243 self.showtraceback()
244 try:
244 try:
245 line = self.raw_input(prompt)
245 line = self.raw_input(prompt)
246 if self.exit_now:
246 if self.exit_now:
247 # quick exit on sys.std[in|out] close
247 # quick exit on sys.std[in|out] close
248 break
248 break
249 if self.autoindent:
249 if self.autoindent:
250 self.rl_do_indent = False
250 self.rl_do_indent = False
251
251
252 except KeyboardInterrupt:
252 except KeyboardInterrupt:
253 #double-guard against keyboardinterrupts during kbdint handling
253 #double-guard against keyboardinterrupts during kbdint handling
254 try:
254 try:
255 self.write('\nKeyboardInterrupt\n')
255 self.write('\nKeyboardInterrupt\n')
256 self.resetbuffer()
256 self.resetbuffer()
257 more = False
257 more = False
258 except KeyboardInterrupt:
258 except KeyboardInterrupt:
259 pass
259 pass
260 except EOFError:
260 except EOFError:
261 if self.autoindent:
261 if self.autoindent:
262 self.rl_do_indent = False
262 self.rl_do_indent = False
263 if self.has_readline:
263 if self.has_readline:
264 self.readline_startup_hook(None)
264 self.readline_startup_hook(None)
265 self.write('\n')
265 self.write('\n')
266 self.exit()
266 self.exit()
267 except bdb.BdbQuit:
267 except bdb.BdbQuit:
268 warn('The Python debugger has exited with a BdbQuit exception.\n'
268 warn('The Python debugger has exited with a BdbQuit exception.\n'
269 'Because of how pdb handles the stack, it is impossible\n'
269 'Because of how pdb handles the stack, it is impossible\n'
270 'for IPython to properly format this particular exception.\n'
270 'for IPython to properly format this particular exception.\n'
271 'IPython will resume normal operation.')
271 'IPython will resume normal operation.')
272 except:
272 except:
273 # exceptions here are VERY RARE, but they can be triggered
273 # exceptions here are VERY RARE, but they can be triggered
274 # asynchronously by signal handlers, for example.
274 # asynchronously by signal handlers, for example.
275 self.showtraceback()
275 self.showtraceback()
276 else:
276 else:
277 self.input_splitter.push(line)
277 self.input_splitter.push(line)
278 more = self.input_splitter.push_accepts_more()
278 more = self.input_splitter.push_accepts_more()
279 if (self.SyntaxTB.last_syntax_error and
279 if (self.SyntaxTB.last_syntax_error and
280 self.autoedit_syntax):
280 self.autoedit_syntax):
281 self.edit_syntax_error()
281 self.edit_syntax_error()
282 if not more:
282 if not more:
283 source_raw = self.input_splitter.source_raw_reset()[1]
283 source_raw = self.input_splitter.source_raw_reset()[1]
284 self.run_cell(source_raw)
284 self.run_cell(source_raw)
285
285
286 # We are off again...
286 # We are off again...
287 __builtin__.__dict__['__IPYTHON__active'] -= 1
287 __builtin__.__dict__['__IPYTHON__active'] -= 1
288
288
289 # Turn off the exit flag, so the mainloop can be restarted if desired
289 # Turn off the exit flag, so the mainloop can be restarted if desired
290 self.exit_now = False
290 self.exit_now = False
291
291
292 def raw_input(self, prompt='', continue_prompt=False):
292 def raw_input(self, prompt='', continue_prompt=False):
293 """Write a prompt and read a line.
293 """Write a prompt and read a line.
294
294
295 The returned line does not include the trailing newline.
295 The returned line does not include the trailing newline.
296 When the user enters the EOF key sequence, EOFError is raised.
296 When the user enters the EOF key sequence, EOFError is raised.
297
297
298 Optional inputs:
298 Optional inputs:
299
299
300 - prompt(''): a string to be printed to prompt the user.
300 - prompt(''): a string to be printed to prompt the user.
301
301
302 - continue_prompt(False): whether this line is the first one or a
302 - continue_prompt(False): whether this line is the first one or a
303 continuation in a sequence of inputs.
303 continuation in a sequence of inputs.
304 """
304 """
305 # Code run by the user may have modified the readline completer state.
305 # Code run by the user may have modified the readline completer state.
306 # We must ensure that our completer is back in place.
306 # We must ensure that our completer is back in place.
307
307
308 if self.has_readline:
308 if self.has_readline:
309 self.set_readline_completer()
309 self.set_readline_completer()
310
310
311 try:
311 try:
312 line = raw_input_original(prompt).decode(self.stdin_encoding)
312 line = raw_input_original(prompt).decode(self.stdin_encoding)
313 except ValueError:
313 except ValueError:
314 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
314 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
315 " or sys.stdout.close()!\nExiting IPython!")
315 " or sys.stdout.close()!\nExiting IPython!")
316 self.ask_exit()
316 self.ask_exit()
317 return ""
317 return ""
318
318
319 # Try to be reasonably smart about not re-indenting pasted input more
319 # Try to be reasonably smart about not re-indenting pasted input more
320 # than necessary. We do this by trimming out the auto-indent initial
320 # than necessary. We do this by trimming out the auto-indent initial
321 # spaces, if the user's actual input started itself with whitespace.
321 # spaces, if the user's actual input started itself with whitespace.
322 if self.autoindent:
322 if self.autoindent:
323 if num_ini_spaces(line) > self.indent_current_nsp:
323 if num_ini_spaces(line) > self.indent_current_nsp:
324 line = line[self.indent_current_nsp:]
324 line = line[self.indent_current_nsp:]
325 self.indent_current_nsp = 0
325 self.indent_current_nsp = 0
326
326
327 # store the unfiltered input before the user has any chance to modify
327 # store the unfiltered input before the user has any chance to modify
328 # it.
328 # it.
329 if line.strip():
329 if line.strip():
330 if continue_prompt:
330 if continue_prompt:
331 if self.has_readline and self.readline_use:
331 if self.has_readline and self.readline_use:
332 histlen = self.readline.get_current_history_length()
332 histlen = self.readline.get_current_history_length()
333 if histlen > 1:
333 if histlen > 1:
334 newhist = self.history_manager.input_hist_raw[-1].rstrip()
334 newhist = self.history_manager.input_hist_raw[-1].rstrip()
335 self.readline.remove_history_item(histlen-1)
335 self.readline.remove_history_item(histlen-1)
336 self.readline.replace_history_item(histlen-2,
336 self.readline.replace_history_item(histlen-2,
337 newhist.encode(self.stdin_encoding))
337 newhist.encode(self.stdin_encoding))
338 else:
338 else:
339 self.history_manager.input_hist_raw.append('%s\n' % line)
339 self.history_manager.input_hist_raw.append('%s\n' % line)
340 elif not continue_prompt:
340 elif not continue_prompt:
341 self.history_manager.input_hist_raw.append('\n')
341 self.history_manager.input_hist_raw.append('\n')
342 try:
342 try:
343 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
343 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
344 except:
344 except:
345 # blanket except, in case a user-defined prefilter crashes, so it
345 # blanket except, in case a user-defined prefilter crashes, so it
346 # can't take all of ipython with it.
346 # can't take all of ipython with it.
347 self.showtraceback()
347 self.showtraceback()
348 return ''
348 return ''
349 else:
349 else:
350 return lineout
350 return lineout
351
351
352
352
353 def raw_input(self, prompt=''):
353 def raw_input(self, prompt=''):
354 """Write a prompt and read a line.
354 """Write a prompt and read a line.
355
355
356 The returned line does not include the trailing newline.
356 The returned line does not include the trailing newline.
357 When the user enters the EOF key sequence, EOFError is raised.
357 When the user enters the EOF key sequence, EOFError is raised.
358
358
359 Optional inputs:
359 Optional inputs:
360
360
361 - prompt(''): a string to be printed to prompt the user.
361 - prompt(''): a string to be printed to prompt the user.
362
362
363 - continue_prompt(False): whether this line is the first one or a
363 - continue_prompt(False): whether this line is the first one or a
364 continuation in a sequence of inputs.
364 continuation in a sequence of inputs.
365 """
365 """
366 # Code run by the user may have modified the readline completer state.
366 # Code run by the user may have modified the readline completer state.
367 # We must ensure that our completer is back in place.
367 # We must ensure that our completer is back in place.
368
368
369 if self.has_readline:
369 if self.has_readline:
370 self.set_readline_completer()
370 self.set_readline_completer()
371
371
372 try:
372 try:
373 line = raw_input_original(prompt).decode(self.stdin_encoding)
373 line = raw_input_original(prompt).decode(self.stdin_encoding)
374 except ValueError:
374 except ValueError:
375 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
375 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
376 " or sys.stdout.close()!\nExiting IPython!")
376 " or sys.stdout.close()!\nExiting IPython!")
377 self.ask_exit()
377 self.ask_exit()
378 return ""
378 return ""
379
379
380 # Try to be reasonably smart about not re-indenting pasted input more
380 # Try to be reasonably smart about not re-indenting pasted input more
381 # than necessary. We do this by trimming out the auto-indent initial
381 # than necessary. We do this by trimming out the auto-indent initial
382 # spaces, if the user's actual input started itself with whitespace.
382 # spaces, if the user's actual input started itself with whitespace.
383 if self.autoindent:
383 if self.autoindent:
384 if num_ini_spaces(line) > self.indent_current_nsp:
384 if num_ini_spaces(line) > self.indent_current_nsp:
385 line = line[self.indent_current_nsp:]
385 line = line[self.indent_current_nsp:]
386 self.indent_current_nsp = 0
386 self.indent_current_nsp = 0
387
387
388 return line
388 return line
389
389
390 #-------------------------------------------------------------------------
390 #-------------------------------------------------------------------------
391 # Methods to support auto-editing of SyntaxErrors.
391 # Methods to support auto-editing of SyntaxErrors.
392 #-------------------------------------------------------------------------
392 #-------------------------------------------------------------------------
393
393
394 def edit_syntax_error(self):
394 def edit_syntax_error(self):
395 """The bottom half of the syntax error handler called in the main loop.
395 """The bottom half of the syntax error handler called in the main loop.
396
396
397 Loop until syntax error is fixed or user cancels.
397 Loop until syntax error is fixed or user cancels.
398 """
398 """
399
399
400 while self.SyntaxTB.last_syntax_error:
400 while self.SyntaxTB.last_syntax_error:
401 # copy and clear last_syntax_error
401 # copy and clear last_syntax_error
402 err = self.SyntaxTB.clear_err_state()
402 err = self.SyntaxTB.clear_err_state()
403 if not self._should_recompile(err):
403 if not self._should_recompile(err):
404 return
404 return
405 try:
405 try:
406 # may set last_syntax_error again if a SyntaxError is raised
406 # may set last_syntax_error again if a SyntaxError is raised
407 self.safe_execfile(err.filename,self.user_ns)
407 self.safe_execfile(err.filename,self.user_ns)
408 except:
408 except:
409 self.showtraceback()
409 self.showtraceback()
410 else:
410 else:
411 try:
411 try:
412 f = file(err.filename)
412 f = file(err.filename)
413 try:
413 try:
414 # This should be inside a display_trap block and I
414 # This should be inside a display_trap block and I
415 # think it is.
415 # think it is.
416 sys.displayhook(f.read())
416 sys.displayhook(f.read())
417 finally:
417 finally:
418 f.close()
418 f.close()
419 except:
419 except:
420 self.showtraceback()
420 self.showtraceback()
421
421
422 def _should_recompile(self,e):
422 def _should_recompile(self,e):
423 """Utility routine for edit_syntax_error"""
423 """Utility routine for edit_syntax_error"""
424
424
425 if e.filename in ('<ipython console>','<input>','<string>',
425 if e.filename in ('<ipython console>','<input>','<string>',
426 '<console>','<BackgroundJob compilation>',
426 '<console>','<BackgroundJob compilation>',
427 None):
427 None):
428
428
429 return False
429 return False
430 try:
430 try:
431 if (self.autoedit_syntax and
431 if (self.autoedit_syntax and
432 not self.ask_yes_no('Return to editor to correct syntax error? '
432 not self.ask_yes_no('Return to editor to correct syntax error? '
433 '[Y/n] ','y')):
433 '[Y/n] ','y')):
434 return False
434 return False
435 except EOFError:
435 except EOFError:
436 return False
436 return False
437
437
438 def int0(x):
438 def int0(x):
439 try:
439 try:
440 return int(x)
440 return int(x)
441 except TypeError:
441 except TypeError:
442 return 0
442 return 0
443 # always pass integer line and offset values to editor hook
443 # always pass integer line and offset values to editor hook
444 try:
444 try:
445 self.hooks.fix_error_editor(e.filename,
445 self.hooks.fix_error_editor(e.filename,
446 int0(e.lineno),int0(e.offset),e.msg)
446 int0(e.lineno),int0(e.offset),e.msg)
447 except TryNext:
447 except TryNext:
448 warn('Could not open editor')
448 warn('Could not open editor')
449 return False
449 return False
450 return True
450 return True
451
451
452 #-------------------------------------------------------------------------
452 #-------------------------------------------------------------------------
453 # Things related to GUI support and pylab
453 # Things related to GUI support and pylab
454 #-------------------------------------------------------------------------
454 #-------------------------------------------------------------------------
455
455
456 def enable_pylab(self, gui=None):
456 def enable_pylab(self, gui=None):
457 """Activate pylab support at runtime.
457 """Activate pylab support at runtime.
458
458
459 This turns on support for matplotlib, preloads into the interactive
459 This turns on support for matplotlib, preloads into the interactive
460 namespace all of numpy and pylab, and configures IPython to correcdtly
460 namespace all of numpy and pylab, and configures IPython to correcdtly
461 interact with the GUI event loop. The GUI backend to be used can be
461 interact with the GUI event loop. The GUI backend to be used can be
462 optionally selected with the optional :param:`gui` argument.
462 optionally selected with the optional :param:`gui` argument.
463
463
464 Parameters
464 Parameters
465 ----------
465 ----------
466 gui : optional, string
466 gui : optional, string
467
467
468 If given, dictates the choice of matplotlib GUI backend to use
468 If given, dictates the choice of matplotlib GUI backend to use
469 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
469 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
470 'gtk'), otherwise we use the default chosen by matplotlib (as
470 'gtk'), otherwise we use the default chosen by matplotlib (as
471 dictated by the matplotlib build-time options plus the user's
471 dictated by the matplotlib build-time options plus the user's
472 matplotlibrc configuration file).
472 matplotlibrc configuration file).
473 """
473 """
474 # We want to prevent the loading of pylab to pollute the user's
474 # We want to prevent the loading of pylab to pollute the user's
475 # namespace as shown by the %who* magics, so we execute the activation
475 # namespace as shown by the %who* magics, so we execute the activation
476 # code in an empty namespace, and we update *both* user_ns and
476 # code in an empty namespace, and we update *both* user_ns and
477 # user_ns_hidden with this information.
477 # user_ns_hidden with this information.
478 ns = {}
478 ns = {}
479 gui = pylab_activate(ns, gui)
479 gui = pylab_activate(ns, gui)
480 self.user_ns.update(ns)
480 self.user_ns.update(ns)
481 self.user_ns_hidden.update(ns)
481 self.user_ns_hidden.update(ns)
482 # Now we must activate the gui pylab wants to use, and fix %run to take
482 # Now we must activate the gui pylab wants to use, and fix %run to take
483 # plot updates into account
483 # plot updates into account
484 enable_gui(gui)
484 enable_gui(gui)
485 self.magic_run = self._pylab_magic_run
485 self.magic_run = self._pylab_magic_run
486
486
487 #-------------------------------------------------------------------------
487 #-------------------------------------------------------------------------
488 # Things related to exiting
488 # Things related to exiting
489 #-------------------------------------------------------------------------
489 #-------------------------------------------------------------------------
490
490
491 def ask_exit(self):
491 def ask_exit(self):
492 """ Ask the shell to exit. Can be overiden and used as a callback. """
492 """ Ask the shell to exit. Can be overiden and used as a callback. """
493 self.exit_now = True
493 self.exit_now = True
494
494
495 def exit(self):
495 def exit(self):
496 """Handle interactive exit.
496 """Handle interactive exit.
497
497
498 This method calls the ask_exit callback."""
498 This method calls the ask_exit callback."""
499 if self.confirm_exit:
499 if self.confirm_exit:
500 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
500 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
501 self.ask_exit()
501 self.ask_exit()
502 else:
502 else:
503 self.ask_exit()
503 self.ask_exit()
504
504
505 #------------------------------------------------------------------------
505 #------------------------------------------------------------------------
506 # Magic overrides
506 # Magic overrides
507 #------------------------------------------------------------------------
507 #------------------------------------------------------------------------
508 # Once the base class stops inheriting from magic, this code needs to be
508 # Once the base class stops inheriting from magic, this code needs to be
509 # moved into a separate machinery as well. For now, at least isolate here
509 # moved into a separate machinery as well. For now, at least isolate here
510 # the magics which this class needs to implement differently from the base
510 # the magics which this class needs to implement differently from the base
511 # class, or that are unique to it.
511 # class, or that are unique to it.
512
512
513 def magic_autoindent(self, parameter_s = ''):
513 def magic_autoindent(self, parameter_s = ''):
514 """Toggle autoindent on/off (if available)."""
514 """Toggle autoindent on/off (if available)."""
515
515
516 self.shell.set_autoindent()
516 self.shell.set_autoindent()
517 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
517 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
518
518
519 def magic_cpaste(self, parameter_s=''):
519 def magic_cpaste(self, parameter_s=''):
520 """Paste & execute a pre-formatted code block from clipboard.
520 """Paste & execute a pre-formatted code block from clipboard.
521
521
522 You must terminate the block with '--' (two minus-signs) alone on the
522 You must terminate the block with '--' (two minus-signs) alone on the
523 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
523 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
524 is the new sentinel for this operation)
524 is the new sentinel for this operation)
525
525
526 The block is dedented prior to execution to enable execution of method
526 The block is dedented prior to execution to enable execution of method
527 definitions. '>' and '+' characters at the beginning of a line are
527 definitions. '>' and '+' characters at the beginning of a line are
528 ignored, to allow pasting directly from e-mails, diff files and
528 ignored, to allow pasting directly from e-mails, diff files and
529 doctests (the '...' continuation prompt is also stripped). The
529 doctests (the '...' continuation prompt is also stripped). The
530 executed block is also assigned to variable named 'pasted_block' for
530 executed block is also assigned to variable named 'pasted_block' for
531 later editing with '%edit pasted_block'.
531 later editing with '%edit pasted_block'.
532
532
533 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
533 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
534 This assigns the pasted block to variable 'foo' as string, without
534 This assigns the pasted block to variable 'foo' as string, without
535 dedenting or executing it (preceding >>> and + is still stripped)
535 dedenting or executing it (preceding >>> and + is still stripped)
536
536
537 '%cpaste -r' re-executes the block previously entered by cpaste.
537 '%cpaste -r' re-executes the block previously entered by cpaste.
538
538
539 Do not be alarmed by garbled output on Windows (it's a readline bug).
539 Do not be alarmed by garbled output on Windows (it's a readline bug).
540 Just press enter and type -- (and press enter again) and the block
540 Just press enter and type -- (and press enter again) and the block
541 will be what was just pasted.
541 will be what was just pasted.
542
542
543 IPython statements (magics, shell escapes) are not supported (yet).
543 IPython statements (magics, shell escapes) are not supported (yet).
544
544
545 See also
545 See also
546 --------
546 --------
547 paste: automatically pull code from clipboard.
547 paste: automatically pull code from clipboard.
548
549 Examples
550 --------
551 ::
552
553 In [8]: %cpaste
554 Pasting code; enter '--' alone on the line to stop.
555 :>>> a = ["world!", "Hello"]
556 :>>> print " ".join(sorted(a))
557 :--
558 Hello world!
548 """
559 """
549
560
550 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
561 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
551 par = args.strip()
562 par = args.strip()
552 if opts.has_key('r'):
563 if opts.has_key('r'):
553 self._rerun_pasted()
564 self._rerun_pasted()
554 return
565 return
555
566
556 sentinel = opts.get('s','--')
567 sentinel = opts.get('s','--')
557
568
558 block = self._strip_pasted_lines_for_code(
569 block = self._strip_pasted_lines_for_code(
559 self._get_pasted_lines(sentinel))
570 self._get_pasted_lines(sentinel))
560
571
561 self._execute_block(block, par)
572 self._execute_block(block, par)
562
573
563 def magic_paste(self, parameter_s=''):
574 def magic_paste(self, parameter_s=''):
564 """Paste & execute a pre-formatted code block from clipboard.
575 """Paste & execute a pre-formatted code block from clipboard.
565
576
566 The text is pulled directly from the clipboard without user
577 The text is pulled directly from the clipboard without user
567 intervention and printed back on the screen before execution (unless
578 intervention and printed back on the screen before execution (unless
568 the -q flag is given to force quiet mode).
579 the -q flag is given to force quiet mode).
569
580
570 The block is dedented prior to execution to enable execution of method
581 The block is dedented prior to execution to enable execution of method
571 definitions. '>' and '+' characters at the beginning of a line are
582 definitions. '>' and '+' characters at the beginning of a line are
572 ignored, to allow pasting directly from e-mails, diff files and
583 ignored, to allow pasting directly from e-mails, diff files and
573 doctests (the '...' continuation prompt is also stripped). The
584 doctests (the '...' continuation prompt is also stripped). The
574 executed block is also assigned to variable named 'pasted_block' for
585 executed block is also assigned to variable named 'pasted_block' for
575 later editing with '%edit pasted_block'.
586 later editing with '%edit pasted_block'.
576
587
577 You can also pass a variable name as an argument, e.g. '%paste foo'.
588 You can also pass a variable name as an argument, e.g. '%paste foo'.
578 This assigns the pasted block to variable 'foo' as string, without
589 This assigns the pasted block to variable 'foo' as string, without
579 dedenting or executing it (preceding >>> and + is still stripped)
590 dedenting or executing it (preceding >>> and + is still stripped)
580
591
581 Options
592 Options
582 -------
593 -------
583
594
584 -r: re-executes the block previously entered by cpaste.
595 -r: re-executes the block previously entered by cpaste.
585
596
586 -q: quiet mode: do not echo the pasted text back to the terminal.
597 -q: quiet mode: do not echo the pasted text back to the terminal.
587
598
588 IPython statements (magics, shell escapes) are not supported (yet).
599 IPython statements (magics, shell escapes) are not supported (yet).
589
600
590 See also
601 See also
591 --------
602 --------
592 cpaste: manually paste code into terminal until you mark its end.
603 cpaste: manually paste code into terminal until you mark its end.
593 """
604 """
594 opts,args = self.parse_options(parameter_s,'rq',mode='string')
605 opts,args = self.parse_options(parameter_s,'rq',mode='string')
595 par = args.strip()
606 par = args.strip()
596 if opts.has_key('r'):
607 if opts.has_key('r'):
597 self._rerun_pasted()
608 self._rerun_pasted()
598 return
609 return
599
610
600 text = self.shell.hooks.clipboard_get()
611 text = self.shell.hooks.clipboard_get()
601 block = self._strip_pasted_lines_for_code(text.splitlines())
612 block = self._strip_pasted_lines_for_code(text.splitlines())
602
613
603 # By default, echo back to terminal unless quiet mode is requested
614 # By default, echo back to terminal unless quiet mode is requested
604 if not opts.has_key('q'):
615 if not opts.has_key('q'):
605 write = self.shell.write
616 write = self.shell.write
606 write(self.shell.pycolorize(block))
617 write(self.shell.pycolorize(block))
607 if not block.endswith('\n'):
618 if not block.endswith('\n'):
608 write('\n')
619 write('\n')
609 write("## -- End pasted text --\n")
620 write("## -- End pasted text --\n")
610
621
611 self._execute_block(block, par)
622 self._execute_block(block, par)
612
623
613
624
614 InteractiveShellABC.register(TerminalInteractiveShell)
625 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now