##// END OF EJS Templates
Complete reorganization of InteractiveShell....
Brian Granger -
Show More
@@ -0,0 +1,14 b''
1 class InputList(list):
2 """Class to store user input.
3
4 It's basically a list, but slices return a string instead of a list, thus
5 allowing things like (assuming 'In' is an instance):
6
7 exec In[4:7]
8
9 or
10
11 exec In[5:9] + In[14] + In[21:25]"""
12
13 def __getslice__(self,i,j):
14 return ''.join(list.__getslice__(self,i,j))
This diff has been collapsed as it changes many lines, (541 lines changed) Show them Hide them
@@ -0,0 +1,541 b''
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
3
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
12
13 #-----------------------------------------------------------------------------
14 # Imports
15 #-----------------------------------------------------------------------------
16
17 import __builtin__
18 import bdb
19 from contextlib import nested
20 import os
21 import re
22 import sys
23
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.inputlist import InputList
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 from IPython.lib.inputhook import enable_gui
29 from IPython.lib.pylabtools import pylab_activate
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
35
36
37 #-----------------------------------------------------------------------------
38 # Utilities
39 #-----------------------------------------------------------------------------
40
41
42 def get_default_editor():
43 try:
44 ed = os.environ['EDITOR']
45 except KeyError:
46 if os.name == 'posix':
47 ed = 'vi' # the only one guaranteed to be there!
48 else:
49 ed = 'notepad' # same in Windows!
50 return ed
51
52
53 # store the builtin raw_input globally, and use this always, in case user code
54 # overwrites it (like wx.py.PyShell does)
55 raw_input_original = raw_input
56
57
58 class SeparateStr(Str):
59 """A Str subclass to validate separate_in, separate_out, etc.
60
61 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
62 """
63
64 def validate(self, obj, value):
65 if value == '0': value = ''
66 value = value.replace('\\n','\n')
67 return super(SeparateStr, self).validate(obj, value)
68
69
70 #-----------------------------------------------------------------------------
71 # Main class
72 #-----------------------------------------------------------------------------
73
74
75 class TerminalInteractiveShell(InteractiveShell):
76
77 autoedit_syntax = CBool(False, config=True)
78 autoindent = CBool(True, config=True)
79 banner = Str('')
80 banner1 = Str(default_banner, config=True)
81 banner2 = Str('', config=True)
82 confirm_exit = CBool(True, config=True)
83 # This display_banner only controls whether or not self.show_banner()
84 # is called when mainloop/interact are called. The default is False
85 # because for the terminal based application, the banner behavior
86 # is controlled by Global.display_banner, which IPythonApp looks at
87 # to determine if *it* should call show_banner() by hand or not.
88 display_banner = CBool(False) # This isn't configurable!
89 embedded = CBool(False)
90 embedded_active = CBool(False)
91 editor = Str(get_default_editor(), config=True)
92 exit_now = CBool(False)
93 pager = Str('less', config=True)
94
95 screen_length = Int(0, config=True)
96
97 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
98 separate_in = SeparateStr('\n', config=True)
99 separate_out = SeparateStr('', config=True)
100 separate_out2 = SeparateStr('', config=True)
101 term_title = CBool(False, config=True)
102
103 def __init__(self, config=None, ipython_dir=None, user_ns=None,
104 user_global_ns=None, custom_exceptions=((),None),
105 usage=None, banner1=None, banner2=None,
106 display_banner=None):
107
108 super(TerminalInteractiveShell, self).__init__(
109 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
110 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
111 )
112 self.init_term_title()
113 self.init_usage(usage)
114 self.init_banner(banner1, banner2, display_banner)
115
116 #-------------------------------------------------------------------------
117 # Things related to the terminal
118 #-------------------------------------------------------------------------
119
120 @property
121 def usable_screen_length(self):
122 if self.screen_length == 0:
123 return 0
124 else:
125 num_lines_bot = self.separate_in.count('\n')+1
126 return self.screen_length - num_lines_bot
127
128 def init_term_title(self):
129 # Enable or disable the terminal title.
130 if self.term_title:
131 toggle_set_term_title(True)
132 set_term_title('IPython: ' + abbrev_cwd())
133 else:
134 toggle_set_term_title(False)
135
136 #-------------------------------------------------------------------------
137 # Things related to the banner and usage
138 #-------------------------------------------------------------------------
139
140 def _banner1_changed(self):
141 self.compute_banner()
142
143 def _banner2_changed(self):
144 self.compute_banner()
145
146 def _term_title_changed(self, name, new_value):
147 self.init_term_title()
148
149 def init_banner(self, banner1, banner2, display_banner):
150 if banner1 is not None:
151 self.banner1 = banner1
152 if banner2 is not None:
153 self.banner2 = banner2
154 if display_banner is not None:
155 self.display_banner = display_banner
156 self.compute_banner()
157
158 def show_banner(self, banner=None):
159 if banner is None:
160 banner = self.banner
161 self.write(banner)
162
163 def compute_banner(self):
164 self.banner = self.banner1 + '\n'
165 if self.profile:
166 self.banner += '\nIPython profile: %s\n' % self.profile
167 if self.banner2:
168 self.banner += '\n' + self.banner2 + '\n'
169
170 def init_usage(self, usage=None):
171 if usage is None:
172 self.usage = interactive_usage
173 else:
174 self.usage = usage
175
176 #-------------------------------------------------------------------------
177 # Mainloop and code execution logic
178 #-------------------------------------------------------------------------
179
180 def mainloop(self, display_banner=None):
181 """Start the mainloop.
182
183 If an optional banner argument is given, it will override the
184 internally created default banner.
185 """
186
187 with nested(self.builtin_trap, self.display_trap):
188
189 # if you run stuff with -c <cmd>, raw hist is not updated
190 # ensure that it's in sync
191 if len(self.input_hist) != len (self.input_hist_raw):
192 self.input_hist_raw = InputList(self.input_hist)
193
194 while 1:
195 try:
196 self.interact(display_banner=display_banner)
197 #self.interact_with_readline()
198 # XXX for testing of a readline-decoupled repl loop, call
199 # interact_with_readline above
200 break
201 except KeyboardInterrupt:
202 # this should not be necessary, but KeyboardInterrupt
203 # handling seems rather unpredictable...
204 self.write("\nKeyboardInterrupt in interact()\n")
205
206 def interact(self, display_banner=None):
207 """Closely emulate the interactive Python console."""
208
209 # batch run -> do not interact
210 if self.exit_now:
211 return
212
213 if display_banner is None:
214 display_banner = self.display_banner
215 if display_banner:
216 self.show_banner()
217
218 more = 0
219
220 # Mark activity in the builtins
221 __builtin__.__dict__['__IPYTHON__active'] += 1
222
223 if self.has_readline:
224 self.readline_startup_hook(self.pre_readline)
225 # exit_now is set by a call to %Exit or %Quit, through the
226 # ask_exit callback.
227
228 while not self.exit_now:
229 self.hooks.pre_prompt_hook()
230 if more:
231 try:
232 prompt = self.hooks.generate_prompt(True)
233 except:
234 self.showtraceback()
235 if self.autoindent:
236 self.rl_do_indent = True
237
238 else:
239 try:
240 prompt = self.hooks.generate_prompt(False)
241 except:
242 self.showtraceback()
243 try:
244 line = self.raw_input(prompt, more)
245 if self.exit_now:
246 # quick exit on sys.std[in|out] close
247 break
248 if self.autoindent:
249 self.rl_do_indent = False
250
251 except KeyboardInterrupt:
252 #double-guard against keyboardinterrupts during kbdint handling
253 try:
254 self.write('\nKeyboardInterrupt\n')
255 self.resetbuffer()
256 # keep cache in sync with the prompt counter:
257 self.outputcache.prompt_count -= 1
258
259 if self.autoindent:
260 self.indent_current_nsp = 0
261 more = 0
262 except KeyboardInterrupt:
263 pass
264 except EOFError:
265 if self.autoindent:
266 self.rl_do_indent = False
267 if self.has_readline:
268 self.readline_startup_hook(None)
269 self.write('\n')
270 self.exit()
271 except bdb.BdbQuit:
272 warn('The Python debugger has exited with a BdbQuit exception.\n'
273 'Because of how pdb handles the stack, it is impossible\n'
274 'for IPython to properly format this particular exception.\n'
275 'IPython will resume normal operation.')
276 except:
277 # exceptions here are VERY RARE, but they can be triggered
278 # asynchronously by signal handlers, for example.
279 self.showtraceback()
280 else:
281 more = self.push_line(line)
282 if (self.SyntaxTB.last_syntax_error and
283 self.autoedit_syntax):
284 self.edit_syntax_error()
285
286 # We are off again...
287 __builtin__.__dict__['__IPYTHON__active'] -= 1
288
289 # Turn off the exit flag, so the mainloop can be restarted if desired
290 self.exit_now = False
291
292 def raw_input(self,prompt='',continue_prompt=False):
293 """Write a prompt and read a line.
294
295 The returned line does not include the trailing newline.
296 When the user enters the EOF key sequence, EOFError is raised.
297
298 Optional inputs:
299
300 - prompt(''): a string to be printed to prompt the user.
301
302 - continue_prompt(False): whether this line is the first one or a
303 continuation in a sequence of inputs.
304 """
305 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
306
307 # Code run by the user may have modified the readline completer state.
308 # We must ensure that our completer is back in place.
309
310 if self.has_readline:
311 self.set_completer()
312
313 try:
314 line = raw_input_original(prompt).decode(self.stdin_encoding)
315 except ValueError:
316 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
317 " or sys.stdout.close()!\nExiting IPython!")
318 self.ask_exit()
319 return ""
320
321 # Try to be reasonably smart about not re-indenting pasted input more
322 # than necessary. We do this by trimming out the auto-indent initial
323 # spaces, if the user's actual input started itself with whitespace.
324 #debugx('self.buffer[-1]')
325
326 if self.autoindent:
327 if num_ini_spaces(line) > self.indent_current_nsp:
328 line = line[self.indent_current_nsp:]
329 self.indent_current_nsp = 0
330
331 # store the unfiltered input before the user has any chance to modify
332 # it.
333 if line.strip():
334 if continue_prompt:
335 self.input_hist_raw[-1] += '%s\n' % line
336 if self.has_readline and self.readline_use:
337 try:
338 histlen = self.readline.get_current_history_length()
339 if histlen > 1:
340 newhist = self.input_hist_raw[-1].rstrip()
341 self.readline.remove_history_item(histlen-1)
342 self.readline.replace_history_item(histlen-2,
343 newhist.encode(self.stdin_encoding))
344 except AttributeError:
345 pass # re{move,place}_history_item are new in 2.4.
346 else:
347 self.input_hist_raw.append('%s\n' % line)
348 # only entries starting at first column go to shadow history
349 if line.lstrip() == line:
350 self.shadowhist.add(line.strip())
351 elif not continue_prompt:
352 self.input_hist_raw.append('\n')
353 try:
354 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
355 except:
356 # blanket except, in case a user-defined prefilter crashes, so it
357 # can't take all of ipython with it.
358 self.showtraceback()
359 return ''
360 else:
361 return lineout
362
363 # TODO: The following three methods are an early attempt to refactor
364 # the main code execution logic. We don't use them, but they may be
365 # helpful when we refactor the code execution logic further.
366 # def interact_prompt(self):
367 # """ Print the prompt (in read-eval-print loop)
368 #
369 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
370 # used in standard IPython flow.
371 # """
372 # if self.more:
373 # try:
374 # prompt = self.hooks.generate_prompt(True)
375 # except:
376 # self.showtraceback()
377 # if self.autoindent:
378 # self.rl_do_indent = True
379 #
380 # else:
381 # try:
382 # prompt = self.hooks.generate_prompt(False)
383 # except:
384 # self.showtraceback()
385 # self.write(prompt)
386 #
387 # def interact_handle_input(self,line):
388 # """ Handle the input line (in read-eval-print loop)
389 #
390 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
391 # used in standard IPython flow.
392 # """
393 # if line.lstrip() == line:
394 # self.shadowhist.add(line.strip())
395 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
396 #
397 # if line.strip():
398 # if self.more:
399 # self.input_hist_raw[-1] += '%s\n' % line
400 # else:
401 # self.input_hist_raw.append('%s\n' % line)
402 #
403 #
404 # self.more = self.push_line(lineout)
405 # if (self.SyntaxTB.last_syntax_error and
406 # self.autoedit_syntax):
407 # self.edit_syntax_error()
408 #
409 # def interact_with_readline(self):
410 # """ Demo of using interact_handle_input, interact_prompt
411 #
412 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
413 # it should work like this.
414 # """
415 # self.readline_startup_hook(self.pre_readline)
416 # while not self.exit_now:
417 # self.interact_prompt()
418 # if self.more:
419 # self.rl_do_indent = True
420 # else:
421 # self.rl_do_indent = False
422 # line = raw_input_original().decode(self.stdin_encoding)
423 # self.interact_handle_input(line)
424
425 #-------------------------------------------------------------------------
426 # Methods to support auto-editing of SyntaxErrors.
427 #-------------------------------------------------------------------------
428
429 def edit_syntax_error(self):
430 """The bottom half of the syntax error handler called in the main loop.
431
432 Loop until syntax error is fixed or user cancels.
433 """
434
435 while self.SyntaxTB.last_syntax_error:
436 # copy and clear last_syntax_error
437 err = self.SyntaxTB.clear_err_state()
438 if not self._should_recompile(err):
439 return
440 try:
441 # may set last_syntax_error again if a SyntaxError is raised
442 self.safe_execfile(err.filename,self.user_ns)
443 except:
444 self.showtraceback()
445 else:
446 try:
447 f = file(err.filename)
448 try:
449 # This should be inside a display_trap block and I
450 # think it is.
451 sys.displayhook(f.read())
452 finally:
453 f.close()
454 except:
455 self.showtraceback()
456
457 def _should_recompile(self,e):
458 """Utility routine for edit_syntax_error"""
459
460 if e.filename in ('<ipython console>','<input>','<string>',
461 '<console>','<BackgroundJob compilation>',
462 None):
463
464 return False
465 try:
466 if (self.autoedit_syntax and
467 not self.ask_yes_no('Return to editor to correct syntax error? '
468 '[Y/n] ','y')):
469 return False
470 except EOFError:
471 return False
472
473 def int0(x):
474 try:
475 return int(x)
476 except TypeError:
477 return 0
478 # always pass integer line and offset values to editor hook
479 try:
480 self.hooks.fix_error_editor(e.filename,
481 int0(e.lineno),int0(e.offset),e.msg)
482 except TryNext:
483 warn('Could not open editor')
484 return False
485 return True
486
487 #-------------------------------------------------------------------------
488 # Things related to GUI support and pylab
489 #-------------------------------------------------------------------------
490
491 def enable_pylab(self, gui=None):
492 """Activate pylab support at runtime.
493
494 This turns on support for matplotlib, preloads into the interactive
495 namespace all of numpy and pylab, and configures IPython to correcdtly
496 interact with the GUI event loop. The GUI backend to be used can be
497 optionally selected with the optional :param:`gui` argument.
498
499 Parameters
500 ----------
501 gui : optional, string
502
503 If given, dictates the choice of matplotlib GUI backend to use
504 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
505 'gtk'), otherwise we use the default chosen by matplotlib (as
506 dictated by the matplotlib build-time options plus the user's
507 matplotlibrc configuration file).
508 """
509 # We want to prevent the loading of pylab to pollute the user's
510 # namespace as shown by the %who* magics, so we execute the activation
511 # code in an empty namespace, and we update *both* user_ns and
512 # user_ns_hidden with this information.
513 ns = {}
514 gui = pylab_activate(ns, gui)
515 self.user_ns.update(ns)
516 self.user_ns_hidden.update(ns)
517 # Now we must activate the gui pylab wants to use, and fix %run to take
518 # plot updates into account
519 enable_gui(gui)
520 self.magic_run = self._pylab_magic_run
521
522 #-------------------------------------------------------------------------
523 # Things related to exiting
524 #-------------------------------------------------------------------------
525
526 def ask_exit(self):
527 """ Ask the shell to exit. Can be overiden and used as a callback. """
528 self.exit_now = True
529
530 def exit(self):
531 """Handle interactive exit.
532
533 This method calls the ask_exit callback."""
534 if self.confirm_exit:
535 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
536 self.ask_exit()
537 else:
538 self.ask_exit()
539
540
541 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,148 +1,148 b''
1 1 # Get the config being loaded so we can set attributes on it
2 2 c = get_config()
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Global options
6 6 #-----------------------------------------------------------------------------
7 7
8 8 # c.Global.display_banner = True
9 9
10 10 # c.Global.classic = False
11 11
12 12 # c.Global.nosep = True
13 13
14 14 # Set this to determine the detail of what is logged at startup.
15 15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 16 # c.Global.log_level = 20
17 17
18 18 # This should be a list of importable Python modules that have an
19 19 # load_in_ipython(ip) method. This method gets called when the extension
20 20 # is loaded. You can put your extensions anywhere they can be imported
21 21 # but we add the extensions subdir of the ipython directory to sys.path
22 22 # during extension loading, so you can put them there as well.
23 23 # c.Global.extensions = [
24 24 # 'myextension'
25 25 # ]
26 26
27 27 # These lines are run in IPython in the user's namespace after extensions
28 28 # are loaded. They can contain full IPython syntax with magics etc.
29 29 # c.Global.exec_lines = [
30 30 # 'import numpy',
31 31 # 'a = 10; b = 20',
32 32 # '1/0'
33 33 # ]
34 34
35 35 # These files are run in IPython in the user's namespace. Files with a .py
36 36 # extension need to be pure Python. Files with a .ipy extension can have
37 37 # custom IPython syntax (like magics, etc.).
38 38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 39 # c.Global.exec_files = [
40 40 # 'mycode.py',
41 41 # 'fancy.ipy'
42 42 # ]
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # InteractiveShell options
46 46 #-----------------------------------------------------------------------------
47 47
48 48 # c.InteractiveShell.autocall = 1
49 49
50 # c.InteractiveShell.autoedit_syntax = False
50 # c.TerminalInteractiveShell.autoedit_syntax = False
51 51
52 # c.InteractiveShell.autoindent = True
52 # c.TerminalInteractiveShell.autoindent = True
53 53
54 54 # c.InteractiveShell.automagic = False
55 55
56 # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner'
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57 57
58 # c.InteractiveShell.banner2 = "This is for extra banner text"
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59 59
60 60 # c.InteractiveShell.cache_size = 1000
61 61
62 62 # c.InteractiveShell.colors = 'LightBG'
63 63
64 64 # c.InteractiveShell.color_info = True
65 65
66 # c.InteractiveShell.confirm_exit = True
66 # c.TerminalInteractiveShell.confirm_exit = True
67 67
68 68 # c.InteractiveShell.deep_reload = False
69 69
70 # c.InteractiveShell.editor = 'nano'
70 # c.TerminalInteractiveShell.editor = 'nano'
71 71
72 72 # c.InteractiveShell.logstart = True
73 73
74 74 # c.InteractiveShell.logfile = u'ipython_log.py'
75 75
76 76 # c.InteractiveShell.logappend = u'mylog.py'
77 77
78 78 # c.InteractiveShell.object_info_string_level = 0
79 79
80 # c.InteractiveShell.pager = 'less'
80 # c.TerminalInteractiveShell.pager = 'less'
81 81
82 82 # c.InteractiveShell.pdb = False
83 83
84 84 # c.InteractiveShell.pprint = True
85 85
86 86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
87 87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
88 88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
89 89 # c.InteractiveShell.prompts_pad_left = True
90 90
91 91 # c.InteractiveShell.quiet = False
92 92
93 93 # Readline
94 94 # c.InteractiveShell.readline_use = True
95 95
96 96 # c.InteractiveShell.readline_parse_and_bind = [
97 97 # 'tab: complete',
98 98 # '"\C-l": possible-completions',
99 99 # 'set show-all-if-ambiguous on',
100 100 # '"\C-o": tab-insert',
101 101 # '"\M-i": " "',
102 102 # '"\M-o": "\d\d\d\d"',
103 103 # '"\M-I": "\d\d\d\d"',
104 104 # '"\C-r": reverse-search-history',
105 105 # '"\C-s": forward-search-history',
106 106 # '"\C-p": history-search-backward',
107 107 # '"\C-n": history-search-forward',
108 108 # '"\e[A": history-search-backward',
109 109 # '"\e[B": history-search-forward',
110 110 # '"\C-k": kill-line',
111 111 # '"\C-u": unix-line-discard',
112 112 # ]
113 113 # c.InteractiveShell.readline_remove_delims = '-/~'
114 114 # c.InteractiveShell.readline_merge_completions = True
115 115 # c.InteractiveShell.readline_omit__names = 0
116 116
117 # c.InteractiveShell.screen_length = 0
117 # c.TerminalInteractiveShell.screen_length = 0
118 118
119 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
119 # c.TerminalInteractiveShell.separate_in = '\n'
120 # c.TerminalInteractiveShell.separate_out = ''
121 # c.TerminalInteractiveShell.separate_out2 = ''
122 122
123 123 # c.InteractiveShell.system_header = "IPython system call: "
124 124
125 125 # c.InteractiveShell.system_verbose = True
126 126
127 # c.InteractiveShell.term_title = False
127 # c.TerminalInteractiveShell.term_title = False
128 128
129 129 # c.InteractiveShell.wildcards_case_sensitive = True
130 130
131 131 # c.InteractiveShell.xmode = 'Context'
132 132
133 133 #-----------------------------------------------------------------------------
134 134 # PrefilterManager options
135 135 #-----------------------------------------------------------------------------
136 136
137 137 # c.PrefilterManager.multi_line_specials = True
138 138
139 139 #-----------------------------------------------------------------------------
140 140 # AliasManager options
141 141 #-----------------------------------------------------------------------------
142 142
143 143 # Do this to disable all defaults
144 144 # c.AliasManager.default_aliases = []
145 145
146 146 # c.AliasManager.user_aliases = [
147 147 # ('foo', 'echo Hi')
148 148 # ]
@@ -1,29 +1,29 b''
1 1 c = get_config()
2 2
3 3 # This can be used at any point in a config file to load a sub config
4 4 # and merge it into the current one.
5 5 load_subconfig('ipython_config.py')
6 6
7 7 c.InteractiveShell.prompt_in1 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
8 8 c.InteractiveShell.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> '
9 9 c.InteractiveShell.prompt_out = '<\#> '
10 10
11 11 c.InteractiveShell.prompts_pad_left = True
12 12
13 c.InteractiveShell.separate_in = ''
14 c.InteractiveShell.separate_out = ''
15 c.InteractiveShell.separate_out2 = ''
13 c.TerminalInteractiveShell.separate_in = ''
14 c.TerminalInteractiveShell.separate_out = ''
15 c.TerminalInteractiveShell.separate_out2 = ''
16 16
17 17 c.PrefilterManager.multi_line_specials = True
18 18
19 19 lines = """
20 20 %rehashx
21 21 """
22 22
23 23 # You have to make sure that attributes that are containers already
24 24 # exist before using them. Simple assigning a new list will override
25 25 # all previous values.
26 26 if hasattr(c.Global, 'exec_lines'):
27 27 c.Global.exec_lines.append(lines)
28 28 else:
29 29 c.Global.exec_lines = [lines] No newline at end of file
This diff has been collapsed as it changes many lines, (637 lines changed) Show them Hide them
@@ -1,2523 +1,2024 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import abc
22 import bdb
23 22 import codeop
24 23 import exceptions
25 24 import new
26 25 import os
27 26 import re
28 27 import string
29 28 import sys
30 29 import tempfile
31 30 from contextlib import nested
32 31
33 32 from IPython.core import debugger, oinspect
34 33 from IPython.core import history as ipcorehist
35 34 from IPython.core import prefilter
36 35 from IPython.core import shadowns
37 36 from IPython.core import ultratb
38 37 from IPython.core.alias import AliasManager
39 38 from IPython.core.builtin_trap import BuiltinTrap
40 39 from IPython.config.configurable import Configurable
41 40 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.error import TryNext, UsageError
41 from IPython.core.error import UsageError
43 42 from IPython.core.extensions import ExtensionManager
44 43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.inputlist import InputList
45 45 from IPython.core.logger import Logger
46 46 from IPython.core.magic import Magic
47 47 from IPython.core.plugin import PluginManager
48 48 from IPython.core.prefilter import PrefilterManager
49 49 from IPython.core.prompts import CachedOutput
50 from IPython.core.usage import interactive_usage, default_banner
51 50 import IPython.core.hooks
52 51 from IPython.external.Itpl import ItplNS
53 from IPython.lib.inputhook import enable_gui
54 from IPython.lib.backgroundjobs import BackgroundJobManager
55 from IPython.lib.pylabtools import pylab_activate
56 52 from IPython.utils import PyColorize
57 53 from IPython.utils import pickleshare
58 54 from IPython.utils.doctestreload import doctest_reload
59 55 from IPython.utils.ipstruct import Struct
60 56 from IPython.utils.io import Term, ask_yes_no
61 57 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.process import (
63 abbrev_cwd,
64 getoutput,
65 getoutputerror
66 )
67 # import IPython.utils.rlineimpl as readline
58 from IPython.utils.process import getoutput, getoutputerror
68 59 from IPython.utils.strdispatch import StrDispatch
69 60 from IPython.utils.syspathcontext import prepended_to_syspath
70 from IPython.utils.terminal import toggle_set_term_title, set_term_title
61 from IPython.utils.text import num_ini_spaces
71 62 from IPython.utils.warn import warn, error, fatal
72 63 from IPython.utils.traitlets import (
73 64 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
74 65 )
75 66
76 67 # from IPython.utils import growl
77 68 # growl.start("IPython")
78 69
79 70 #-----------------------------------------------------------------------------
80 71 # Globals
81 72 #-----------------------------------------------------------------------------
82 73
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
86
87 74 # compiled regexps for autoindent management
88 75 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89 76
90 77 #-----------------------------------------------------------------------------
91 78 # Utilities
92 79 #-----------------------------------------------------------------------------
93 80
94 ini_spaces_re = re.compile(r'^(\s+)')
95
96
97 def num_ini_spaces(strng):
98 """Return the number of initial spaces in a string"""
99
100 ini_spaces = ini_spaces_re.match(strng)
101 if ini_spaces:
102 return ini_spaces.end()
103 else:
104 return 0
105
81 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
106 84
107 85 def softspace(file, newvalue):
108 86 """Copied from code.py, to remove the dependency"""
109 87
110 88 oldvalue = 0
111 89 try:
112 90 oldvalue = file.softspace
113 91 except AttributeError:
114 92 pass
115 93 try:
116 94 file.softspace = newvalue
117 95 except (AttributeError, TypeError):
118 96 # "attribute-less object" or "read-only attributes"
119 97 pass
120 98 return oldvalue
121 99
122 100
123 101 def no_op(*a, **kw): pass
124 102
125 103 class SpaceInInput(exceptions.Exception): pass
126 104
127 105 class Bunch: pass
128 106
129 class InputList(list):
130 """Class to store user input.
131
132 It's basically a list, but slices return a string instead of a list, thus
133 allowing things like (assuming 'In' is an instance):
134
135 exec In[4:7]
136
137 or
138
139 exec In[5:9] + In[14] + In[21:25]"""
140
141 def __getslice__(self,i,j):
142 return ''.join(list.__getslice__(self,i,j))
143
144
145 107 class SyntaxTB(ultratb.ListTB):
146 108 """Extension which holds some state: the last exception value"""
147 109
148 110 def __init__(self,color_scheme = 'NoColor'):
149 111 ultratb.ListTB.__init__(self,color_scheme)
150 112 self.last_syntax_error = None
151 113
152 114 def __call__(self, etype, value, elist):
153 115 self.last_syntax_error = value
154 116 ultratb.ListTB.__call__(self,etype,value,elist)
155 117
156 118 def clear_err_state(self):
157 119 """Return the current error state and clear it"""
158 120 e = self.last_syntax_error
159 121 self.last_syntax_error = None
160 122 return e
161 123
162 124
163 def get_default_editor():
164 try:
165 ed = os.environ['EDITOR']
166 except KeyError:
167 if os.name == 'posix':
168 ed = 'vi' # the only one guaranteed to be there!
169 else:
170 ed = 'notepad' # same in Windows!
171 return ed
172
173
174 125 def get_default_colors():
175 126 if sys.platform=='darwin':
176 127 return "LightBG"
177 128 elif os.name=='nt':
178 129 return 'Linux'
179 130 else:
180 131 return 'Linux'
181 132
182 133
183 class SeparateStr(Str):
184 """A Str subclass to validate separate_in, separate_out, etc.
185
186 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
187 """
188
189 def validate(self, obj, value):
190 if value == '0': value = ''
191 value = value.replace('\\n','\n')
192 return super(SeparateStr, self).validate(obj, value)
193
194
195 134 #-----------------------------------------------------------------------------
196 135 # Main IPython class
197 136 #-----------------------------------------------------------------------------
198 137
199 138
200 139 class InteractiveShell(Configurable, Magic):
201 140 """An enhanced, interactive shell for Python."""
202 141
203 142 autocall = Enum((0,1,2), default_value=1, config=True)
204 autoedit_syntax = CBool(False, config=True)
205 autoindent = CBool(True, config=True)
206 143 automagic = CBool(True, config=True)
207 banner = Str('')
208 banner1 = Str(default_banner, config=True)
209 banner2 = Str('', config=True)
210 144 cache_size = Int(1000, config=True)
211 145 color_info = CBool(True, config=True)
212 146 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
213 147 default_value=get_default_colors(), config=True)
214 confirm_exit = CBool(True, config=True)
215 148 debug = CBool(False, config=True)
216 149 deep_reload = CBool(False, config=True)
217 # This display_banner only controls whether or not self.show_banner()
218 # is called when mainloop/interact are called. The default is False
219 # because for the terminal based application, the banner behavior
220 # is controlled by Global.display_banner, which IPythonApp looks at
221 # to determine if *it* should call show_banner() by hand or not.
222 display_banner = CBool(False) # This isn't configurable!
223 embedded = CBool(False)
224 embedded_active = CBool(False)
225 editor = Str(get_default_editor(), config=True)
226 150 filename = Str("<ipython console>")
227 151 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
228 152 logstart = CBool(False, config=True)
229 153 logfile = Str('', config=True)
230 154 logappend = Str('', config=True)
231 155 object_info_string_level = Enum((0,1,2), default_value=0,
232 156 config=True)
233 pager = Str('less', config=True)
234 157 pdb = CBool(False, config=True)
235 158 pprint = CBool(True, config=True)
236 159 profile = Str('', config=True)
237 160 prompt_in1 = Str('In [\\#]: ', config=True)
238 161 prompt_in2 = Str(' .\\D.: ', config=True)
239 162 prompt_out = Str('Out[\\#]: ', config=True)
240 163 prompts_pad_left = CBool(True, config=True)
241 164 quiet = CBool(False, config=True)
242 165
166 # The readline stuff will eventually be moved to the terminal subclass
167 # but for now, we can't do that as readline is welded in everywhere.
243 168 readline_use = CBool(True, config=True)
244 169 readline_merge_completions = CBool(True, config=True)
245 170 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
246 171 readline_remove_delims = Str('-/~', config=True)
247 172 readline_parse_and_bind = List([
248 173 'tab: complete',
249 174 '"\C-l": clear-screen',
250 175 'set show-all-if-ambiguous on',
251 176 '"\C-o": tab-insert',
252 177 '"\M-i": " "',
253 178 '"\M-o": "\d\d\d\d"',
254 179 '"\M-I": "\d\d\d\d"',
255 180 '"\C-r": reverse-search-history',
256 181 '"\C-s": forward-search-history',
257 182 '"\C-p": history-search-backward',
258 183 '"\C-n": history-search-forward',
259 184 '"\e[A": history-search-backward',
260 185 '"\e[B": history-search-forward',
261 186 '"\C-k": kill-line',
262 187 '"\C-u": unix-line-discard',
263 188 ], allow_none=False, config=True)
264 189
265 screen_length = Int(0, config=True)
266
267 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
268 separate_in = SeparateStr('\n', config=True)
269 separate_out = SeparateStr('', config=True)
270 separate_out2 = SeparateStr('', config=True)
271
272 190 system_header = Str('IPython system call: ', config=True)
273 191 system_verbose = CBool(False, config=True)
274 term_title = CBool(False, config=True)
275 192 wildcards_case_sensitive = CBool(True, config=True)
276 193 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
277 194 default_value='Context', config=True)
278 195
279 autoexec = List(allow_none=False)
280
281 # class attribute to indicate whether the class supports threads or not.
282 # Subclasses with thread support should override this as needed.
283 isthreaded = False
284
285 196 # Subcomponents of InteractiveShell
286 197 alias_manager = Instance('IPython.core.alias.AliasManager')
287 198 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
288 199 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
289 200 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
290 201 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
291 202 plugin_manager = Instance('IPython.core.plugin.PluginManager')
292 203
293 def __init__(self, config=None, ipython_dir=None, usage=None,
204 def __init__(self, config=None, ipython_dir=None,
294 205 user_ns=None, user_global_ns=None,
295 banner1=None, banner2=None, display_banner=None,
296 206 custom_exceptions=((),None)):
297 207
298 208 # This is where traits with a config_key argument are updated
299 209 # from the values on config.
300 210 super(InteractiveShell, self).__init__(config=config)
301 211
302 212 # These are relatively independent and stateless
303 213 self.init_ipython_dir(ipython_dir)
304 214 self.init_instance_attrs()
305 self.init_term_title()
306 self.init_usage(usage)
307 self.init_banner(banner1, banner2, display_banner)
308 215
309 216 # Create namespaces (user_ns, user_global_ns, etc.)
310 217 self.init_create_namespaces(user_ns, user_global_ns)
311 218 # This has to be done after init_create_namespaces because it uses
312 219 # something in self.user_ns, but before init_sys_modules, which
313 220 # is the first thing to modify sys.
314 221 self.save_sys_module_state()
315 222 self.init_sys_modules()
316 223
317 224 self.init_history()
318 225 self.init_encoding()
319 226 self.init_prefilter()
320 227
321 228 Magic.__init__(self, self)
322 229
323 230 self.init_syntax_highlighting()
324 231 self.init_hooks()
325 232 self.init_pushd_popd_magic()
326 233 self.init_traceback_handlers(custom_exceptions)
327 234 self.init_user_ns()
328 235 self.init_logger()
329 236 self.init_alias()
330 237 self.init_builtins()
331 238
332 239 # pre_config_initialization
333 240 self.init_shadow_hist()
334 241
335 242 # The next section should contain averything that was in ipmaker.
336 243 self.init_logstart()
337 244
338 245 # The following was in post_config_initialization
339 246 self.init_inspector()
340 247 self.init_readline()
341 248 self.init_prompts()
342 249 self.init_displayhook()
343 250 self.init_reload_doctest()
344 251 self.init_magics()
345 252 self.init_pdb()
346 253 self.init_extension_manager()
347 254 self.init_plugin_manager()
348 255 self.hooks.late_startup_hook()
349 256
350 257 @classmethod
351 258 def instance(cls, *args, **kwargs):
352 259 """Returns a global InteractiveShell instance."""
353 260 if not hasattr(cls, "_instance"):
354 261 cls._instance = cls(*args, **kwargs)
355 262 return cls._instance
356 263
357 264 @classmethod
358 265 def initialized(cls):
359 266 return hasattr(cls, "_instance")
360 267
361 268 def get_ipython(self):
362 269 """Return the currently running IPython instance."""
363 270 return self
364 271
365 272 #-------------------------------------------------------------------------
366 273 # Trait changed handlers
367 274 #-------------------------------------------------------------------------
368 275
369 def _banner1_changed(self):
370 self.compute_banner()
371
372 def _banner2_changed(self):
373 self.compute_banner()
374
375 276 def _ipython_dir_changed(self, name, new):
376 277 if not os.path.isdir(new):
377 278 os.makedirs(new, mode = 0777)
378 279
379 @property
380 def usable_screen_length(self):
381 if self.screen_length == 0:
382 return 0
383 else:
384 num_lines_bot = self.separate_in.count('\n')+1
385 return self.screen_length - num_lines_bot
386
387 def _term_title_changed(self, name, new_value):
388 self.init_term_title()
389
390 280 def set_autoindent(self,value=None):
391 281 """Set the autoindent flag, checking for readline support.
392 282
393 283 If called with no arguments, it acts as a toggle."""
394 284
395 285 if not self.has_readline:
396 286 if os.name == 'posix':
397 287 warn("The auto-indent feature requires the readline library")
398 288 self.autoindent = 0
399 289 return
400 290 if value is None:
401 291 self.autoindent = not self.autoindent
402 292 else:
403 293 self.autoindent = value
404 294
405 295 #-------------------------------------------------------------------------
406 296 # init_* methods called by __init__
407 297 #-------------------------------------------------------------------------
408 298
409 299 def init_ipython_dir(self, ipython_dir):
410 300 if ipython_dir is not None:
411 301 self.ipython_dir = ipython_dir
412 302 self.config.Global.ipython_dir = self.ipython_dir
413 303 return
414 304
415 305 if hasattr(self.config.Global, 'ipython_dir'):
416 306 self.ipython_dir = self.config.Global.ipython_dir
417 307 else:
418 308 self.ipython_dir = get_ipython_dir()
419 309
420 310 # All children can just read this
421 311 self.config.Global.ipython_dir = self.ipython_dir
422 312
423 313 def init_instance_attrs(self):
424 self.jobs = BackgroundJobManager()
425 314 self.more = False
426 315
427 316 # command compiler
428 317 self.compile = codeop.CommandCompiler()
429 318
430 319 # User input buffer
431 320 self.buffer = []
432 321
433 322 # Make an empty namespace, which extension writers can rely on both
434 323 # existing and NEVER being used by ipython itself. This gives them a
435 324 # convenient location for storing additional information and state
436 325 # their extensions may require, without fear of collisions with other
437 326 # ipython names that may develop later.
438 327 self.meta = Struct()
439 328
440 329 # Object variable to store code object waiting execution. This is
441 330 # used mainly by the multithreaded shells, but it can come in handy in
442 331 # other situations. No need to use a Queue here, since it's a single
443 332 # item which gets cleared once run.
444 333 self.code_to_run = None
445 334
446 # Flag to mark unconditional exit
447 self.exit_now = False
448
449 335 # Temporary files used for various purposes. Deleted at exit.
450 336 self.tempfiles = []
451 337
452 338 # Keep track of readline usage (later set by init_readline)
453 339 self.has_readline = False
454 340
455 341 # keep track of where we started running (mainly for crash post-mortem)
456 342 # This is not being used anywhere currently.
457 343 self.starting_dir = os.getcwd()
458 344
459 345 # Indentation management
460 346 self.indent_current_nsp = 0
461 347
462 def init_term_title(self):
463 # Enable or disable the terminal title.
464 if self.term_title:
465 toggle_set_term_title(True)
466 set_term_title('IPython: ' + abbrev_cwd())
467 else:
468 toggle_set_term_title(False)
469
470 def init_usage(self, usage=None):
471 if usage is None:
472 self.usage = interactive_usage
473 else:
474 self.usage = usage
475
476 348 def init_encoding(self):
477 349 # Get system encoding at startup time. Certain terminals (like Emacs
478 350 # under Win32 have it set to None, and we need to have a known valid
479 351 # encoding to use in the raw_input() method
480 352 try:
481 353 self.stdin_encoding = sys.stdin.encoding or 'ascii'
482 354 except AttributeError:
483 355 self.stdin_encoding = 'ascii'
484 356
485 357 def init_syntax_highlighting(self):
486 358 # Python source parser/formatter for syntax highlighting
487 359 pyformat = PyColorize.Parser().format
488 360 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
489 361
490 362 def init_pushd_popd_magic(self):
491 363 # for pushd/popd management
492 364 try:
493 365 self.home_dir = get_home_dir()
494 366 except HomeDirError, msg:
495 367 fatal(msg)
496 368
497 369 self.dir_stack = []
498 370
499 371 def init_logger(self):
500 372 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
501 373 # local shortcut, this is used a LOT
502 374 self.log = self.logger.log
503 375
504 376 def init_logstart(self):
505 377 if self.logappend:
506 378 self.magic_logstart(self.logappend + ' append')
507 379 elif self.logfile:
508 380 self.magic_logstart(self.logfile)
509 381 elif self.logstart:
510 382 self.magic_logstart()
511 383
512 384 def init_builtins(self):
513 385 self.builtin_trap = BuiltinTrap(shell=self)
514 386
515 387 def init_inspector(self):
516 388 # Object inspector
517 389 self.inspector = oinspect.Inspector(oinspect.InspectColors,
518 390 PyColorize.ANSICodeColors,
519 391 'NoColor',
520 392 self.object_info_string_level)
521 393
522 394 def init_prompts(self):
523 395 # Initialize cache, set in/out prompts and printing system
524 396 self.outputcache = CachedOutput(self,
525 397 self.cache_size,
526 398 self.pprint,
527 399 input_sep = self.separate_in,
528 400 output_sep = self.separate_out,
529 401 output_sep2 = self.separate_out2,
530 402 ps1 = self.prompt_in1,
531 403 ps2 = self.prompt_in2,
532 404 ps_out = self.prompt_out,
533 405 pad_left = self.prompts_pad_left)
534 406
535 407 # user may have over-ridden the default print hook:
536 408 try:
537 409 self.outputcache.__class__.display = self.hooks.display
538 410 except AttributeError:
539 411 pass
540 412
541 413 def init_displayhook(self):
542 414 self.display_trap = DisplayTrap(hook=self.outputcache)
543 415
544 416 def init_reload_doctest(self):
545 417 # Do a proper resetting of doctest, including the necessary displayhook
546 418 # monkeypatching
547 419 try:
548 420 doctest_reload()
549 421 except ImportError:
550 422 warn("doctest module does not exist.")
551 423
552 424 #-------------------------------------------------------------------------
553 # Things related to the banner
554 #-------------------------------------------------------------------------
555
556 def init_banner(self, banner1, banner2, display_banner):
557 if banner1 is not None:
558 self.banner1 = banner1
559 if banner2 is not None:
560 self.banner2 = banner2
561 if display_banner is not None:
562 self.display_banner = display_banner
563 self.compute_banner()
564
565 def show_banner(self, banner=None):
566 if banner is None:
567 banner = self.banner
568 self.write(banner)
569
570 def compute_banner(self):
571 self.banner = self.banner1 + '\n'
572 if self.profile:
573 self.banner += '\nIPython profile: %s\n' % self.profile
574 if self.banner2:
575 self.banner += '\n' + self.banner2 + '\n'
576
577 #-------------------------------------------------------------------------
578 425 # Things related to injections into the sys module
579 426 #-------------------------------------------------------------------------
580 427
581 428 def save_sys_module_state(self):
582 429 """Save the state of hooks in the sys module.
583 430
584 431 This has to be called after self.user_ns is created.
585 432 """
586 433 self._orig_sys_module_state = {}
587 434 self._orig_sys_module_state['stdin'] = sys.stdin
588 435 self._orig_sys_module_state['stdout'] = sys.stdout
589 436 self._orig_sys_module_state['stderr'] = sys.stderr
590 437 self._orig_sys_module_state['excepthook'] = sys.excepthook
591 438 try:
592 439 self._orig_sys_modules_main_name = self.user_ns['__name__']
593 440 except KeyError:
594 441 pass
595 442
596 443 def restore_sys_module_state(self):
597 444 """Restore the state of the sys module."""
598 445 try:
599 446 for k, v in self._orig_sys_module_state.items():
600 447 setattr(sys, k, v)
601 448 except AttributeError:
602 449 pass
603 450 try:
604 451 delattr(sys, 'ipcompleter')
605 452 except AttributeError:
606 453 pass
607 454 # Reset what what done in self.init_sys_modules
608 455 try:
609 456 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
610 457 except (AttributeError, KeyError):
611 458 pass
612 459
613 460 #-------------------------------------------------------------------------
614 461 # Things related to hooks
615 462 #-------------------------------------------------------------------------
616 463
617 464 def init_hooks(self):
618 465 # hooks holds pointers used for user-side customizations
619 466 self.hooks = Struct()
620 467
621 468 self.strdispatchers = {}
622 469
623 470 # Set all default hooks, defined in the IPython.hooks module.
624 471 hooks = IPython.core.hooks
625 472 for hook_name in hooks.__all__:
626 473 # default hooks have priority 100, i.e. low; user hooks should have
627 474 # 0-100 priority
628 475 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
629 476
630 477 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
631 478 """set_hook(name,hook) -> sets an internal IPython hook.
632 479
633 480 IPython exposes some of its internal API as user-modifiable hooks. By
634 481 adding your function to one of these hooks, you can modify IPython's
635 482 behavior to call at runtime your own routines."""
636 483
637 484 # At some point in the future, this should validate the hook before it
638 485 # accepts it. Probably at least check that the hook takes the number
639 486 # of args it's supposed to.
640 487
641 488 f = new.instancemethod(hook,self,self.__class__)
642 489
643 490 # check if the hook is for strdispatcher first
644 491 if str_key is not None:
645 492 sdp = self.strdispatchers.get(name, StrDispatch())
646 493 sdp.add_s(str_key, f, priority )
647 494 self.strdispatchers[name] = sdp
648 495 return
649 496 if re_key is not None:
650 497 sdp = self.strdispatchers.get(name, StrDispatch())
651 498 sdp.add_re(re.compile(re_key), f, priority )
652 499 self.strdispatchers[name] = sdp
653 500 return
654 501
655 502 dp = getattr(self.hooks, name, None)
656 503 if name not in IPython.core.hooks.__all__:
657 504 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
658 505 if not dp:
659 506 dp = IPython.core.hooks.CommandChainDispatcher()
660 507
661 508 try:
662 509 dp.add(f,priority)
663 510 except AttributeError:
664 511 # it was not commandchain, plain old func - replace
665 512 dp = f
666 513
667 514 setattr(self.hooks,name, dp)
668 515
669 516 #-------------------------------------------------------------------------
670 517 # Things related to the "main" module
671 518 #-------------------------------------------------------------------------
672 519
673 520 def new_main_mod(self,ns=None):
674 521 """Return a new 'main' module object for user code execution.
675 522 """
676 523 main_mod = self._user_main_module
677 524 init_fakemod_dict(main_mod,ns)
678 525 return main_mod
679 526
680 527 def cache_main_mod(self,ns,fname):
681 528 """Cache a main module's namespace.
682 529
683 530 When scripts are executed via %run, we must keep a reference to the
684 531 namespace of their __main__ module (a FakeModule instance) around so
685 532 that Python doesn't clear it, rendering objects defined therein
686 533 useless.
687 534
688 535 This method keeps said reference in a private dict, keyed by the
689 536 absolute path of the module object (which corresponds to the script
690 537 path). This way, for multiple executions of the same script we only
691 538 keep one copy of the namespace (the last one), thus preventing memory
692 539 leaks from old references while allowing the objects from the last
693 540 execution to be accessible.
694 541
695 542 Note: we can not allow the actual FakeModule instances to be deleted,
696 543 because of how Python tears down modules (it hard-sets all their
697 544 references to None without regard for reference counts). This method
698 545 must therefore make a *copy* of the given namespace, to allow the
699 546 original module's __dict__ to be cleared and reused.
700 547
701 548
702 549 Parameters
703 550 ----------
704 551 ns : a namespace (a dict, typically)
705 552
706 553 fname : str
707 554 Filename associated with the namespace.
708 555
709 556 Examples
710 557 --------
711 558
712 559 In [10]: import IPython
713 560
714 561 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
715 562
716 563 In [12]: IPython.__file__ in _ip._main_ns_cache
717 564 Out[12]: True
718 565 """
719 566 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
720 567
721 568 def clear_main_mod_cache(self):
722 569 """Clear the cache of main modules.
723 570
724 571 Mainly for use by utilities like %reset.
725 572
726 573 Examples
727 574 --------
728 575
729 576 In [15]: import IPython
730 577
731 578 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
732 579
733 580 In [17]: len(_ip._main_ns_cache) > 0
734 581 Out[17]: True
735 582
736 583 In [18]: _ip.clear_main_mod_cache()
737 584
738 585 In [19]: len(_ip._main_ns_cache) == 0
739 586 Out[19]: True
740 587 """
741 588 self._main_ns_cache.clear()
742 589
743 590 #-------------------------------------------------------------------------
744 591 # Things related to debugging
745 592 #-------------------------------------------------------------------------
746 593
747 594 def init_pdb(self):
748 595 # Set calling of pdb on exceptions
749 596 # self.call_pdb is a property
750 597 self.call_pdb = self.pdb
751 598
752 599 def _get_call_pdb(self):
753 600 return self._call_pdb
754 601
755 602 def _set_call_pdb(self,val):
756 603
757 604 if val not in (0,1,False,True):
758 605 raise ValueError,'new call_pdb value must be boolean'
759 606
760 607 # store value in instance
761 608 self._call_pdb = val
762 609
763 610 # notify the actual exception handlers
764 611 self.InteractiveTB.call_pdb = val
765 if self.isthreaded:
766 try:
767 self.sys_excepthook.call_pdb = val
768 except:
769 warn('Failed to activate pdb for threaded exception handler')
770 612
771 613 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
772 614 'Control auto-activation of pdb at exceptions')
773 615
774 616 def debugger(self,force=False):
775 617 """Call the pydb/pdb debugger.
776 618
777 619 Keywords:
778 620
779 621 - force(False): by default, this routine checks the instance call_pdb
780 622 flag and does not actually invoke the debugger if the flag is false.
781 623 The 'force' option forces the debugger to activate even if the flag
782 624 is false.
783 625 """
784 626
785 627 if not (force or self.call_pdb):
786 628 return
787 629
788 630 if not hasattr(sys,'last_traceback'):
789 631 error('No traceback has been produced, nothing to debug.')
790 632 return
791 633
792 634 # use pydb if available
793 635 if debugger.has_pydb:
794 636 from pydb import pm
795 637 else:
796 638 # fallback to our internal debugger
797 639 pm = lambda : self.InteractiveTB.debugger(force=True)
798 640 self.history_saving_wrapper(pm)()
799 641
800 642 #-------------------------------------------------------------------------
801 643 # Things related to IPython's various namespaces
802 644 #-------------------------------------------------------------------------
803 645
804 646 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
805 647 # Create the namespace where the user will operate. user_ns is
806 648 # normally the only one used, and it is passed to the exec calls as
807 649 # the locals argument. But we do carry a user_global_ns namespace
808 650 # given as the exec 'globals' argument, This is useful in embedding
809 651 # situations where the ipython shell opens in a context where the
810 652 # distinction between locals and globals is meaningful. For
811 653 # non-embedded contexts, it is just the same object as the user_ns dict.
812 654
813 655 # FIXME. For some strange reason, __builtins__ is showing up at user
814 656 # level as a dict instead of a module. This is a manual fix, but I
815 657 # should really track down where the problem is coming from. Alex
816 658 # Schmolck reported this problem first.
817 659
818 660 # A useful post by Alex Martelli on this topic:
819 661 # Re: inconsistent value from __builtins__
820 662 # Von: Alex Martelli <aleaxit@yahoo.com>
821 663 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
822 664 # Gruppen: comp.lang.python
823 665
824 666 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
825 667 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
826 668 # > <type 'dict'>
827 669 # > >>> print type(__builtins__)
828 670 # > <type 'module'>
829 671 # > Is this difference in return value intentional?
830 672
831 673 # Well, it's documented that '__builtins__' can be either a dictionary
832 674 # or a module, and it's been that way for a long time. Whether it's
833 675 # intentional (or sensible), I don't know. In any case, the idea is
834 676 # that if you need to access the built-in namespace directly, you
835 677 # should start with "import __builtin__" (note, no 's') which will
836 678 # definitely give you a module. Yeah, it's somewhat confusing:-(.
837 679
838 680 # These routines return properly built dicts as needed by the rest of
839 681 # the code, and can also be used by extension writers to generate
840 682 # properly initialized namespaces.
841 683 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
842 684
843 685 # Assign namespaces
844 686 # This is the namespace where all normal user variables live
845 687 self.user_ns = user_ns
846 688 self.user_global_ns = user_global_ns
847 689
848 690 # An auxiliary namespace that checks what parts of the user_ns were
849 691 # loaded at startup, so we can list later only variables defined in
850 692 # actual interactive use. Since it is always a subset of user_ns, it
851 693 # doesn't need to be separately tracked in the ns_table.
852 694 self.user_ns_hidden = {}
853 695
854 696 # A namespace to keep track of internal data structures to prevent
855 697 # them from cluttering user-visible stuff. Will be updated later
856 698 self.internal_ns = {}
857 699
858 700 # Now that FakeModule produces a real module, we've run into a nasty
859 701 # problem: after script execution (via %run), the module where the user
860 702 # code ran is deleted. Now that this object is a true module (needed
861 703 # so docetst and other tools work correctly), the Python module
862 704 # teardown mechanism runs over it, and sets to None every variable
863 705 # present in that module. Top-level references to objects from the
864 706 # script survive, because the user_ns is updated with them. However,
865 707 # calling functions defined in the script that use other things from
866 708 # the script will fail, because the function's closure had references
867 709 # to the original objects, which are now all None. So we must protect
868 710 # these modules from deletion by keeping a cache.
869 711 #
870 712 # To avoid keeping stale modules around (we only need the one from the
871 713 # last run), we use a dict keyed with the full path to the script, so
872 714 # only the last version of the module is held in the cache. Note,
873 715 # however, that we must cache the module *namespace contents* (their
874 716 # __dict__). Because if we try to cache the actual modules, old ones
875 717 # (uncached) could be destroyed while still holding references (such as
876 718 # those held by GUI objects that tend to be long-lived)>
877 719 #
878 720 # The %reset command will flush this cache. See the cache_main_mod()
879 721 # and clear_main_mod_cache() methods for details on use.
880 722
881 723 # This is the cache used for 'main' namespaces
882 724 self._main_ns_cache = {}
883 725 # And this is the single instance of FakeModule whose __dict__ we keep
884 726 # copying and clearing for reuse on each %run
885 727 self._user_main_module = FakeModule()
886 728
887 729 # A table holding all the namespaces IPython deals with, so that
888 730 # introspection facilities can search easily.
889 731 self.ns_table = {'user':user_ns,
890 732 'user_global':user_global_ns,
891 733 'internal':self.internal_ns,
892 734 'builtin':__builtin__.__dict__
893 735 }
894 736
895 737 # Similarly, track all namespaces where references can be held and that
896 738 # we can safely clear (so it can NOT include builtin). This one can be
897 739 # a simple list.
898 740 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
899 741 self.internal_ns, self._main_ns_cache ]
900 742
901 743 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
902 744 """Return a valid local and global user interactive namespaces.
903 745
904 746 This builds a dict with the minimal information needed to operate as a
905 747 valid IPython user namespace, which you can pass to the various
906 748 embedding classes in ipython. The default implementation returns the
907 749 same dict for both the locals and the globals to allow functions to
908 750 refer to variables in the namespace. Customized implementations can
909 751 return different dicts. The locals dictionary can actually be anything
910 752 following the basic mapping protocol of a dict, but the globals dict
911 753 must be a true dict, not even a subclass. It is recommended that any
912 754 custom object for the locals namespace synchronize with the globals
913 755 dict somehow.
914 756
915 757 Raises TypeError if the provided globals namespace is not a true dict.
916 758
917 759 Parameters
918 760 ----------
919 761 user_ns : dict-like, optional
920 762 The current user namespace. The items in this namespace should
921 763 be included in the output. If None, an appropriate blank
922 764 namespace should be created.
923 765 user_global_ns : dict, optional
924 766 The current user global namespace. The items in this namespace
925 767 should be included in the output. If None, an appropriate
926 768 blank namespace should be created.
927 769
928 770 Returns
929 771 -------
930 772 A pair of dictionary-like object to be used as the local namespace
931 773 of the interpreter and a dict to be used as the global namespace.
932 774 """
933 775
934 776
935 777 # We must ensure that __builtin__ (without the final 's') is always
936 778 # available and pointing to the __builtin__ *module*. For more details:
937 779 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
938 780
939 781 if user_ns is None:
940 782 # Set __name__ to __main__ to better match the behavior of the
941 783 # normal interpreter.
942 784 user_ns = {'__name__' :'__main__',
943 785 '__builtin__' : __builtin__,
944 786 '__builtins__' : __builtin__,
945 787 }
946 788 else:
947 789 user_ns.setdefault('__name__','__main__')
948 790 user_ns.setdefault('__builtin__',__builtin__)
949 791 user_ns.setdefault('__builtins__',__builtin__)
950 792
951 793 if user_global_ns is None:
952 794 user_global_ns = user_ns
953 795 if type(user_global_ns) is not dict:
954 796 raise TypeError("user_global_ns must be a true dict; got %r"
955 797 % type(user_global_ns))
956 798
957 799 return user_ns, user_global_ns
958 800
959 801 def init_sys_modules(self):
960 802 # We need to insert into sys.modules something that looks like a
961 803 # module but which accesses the IPython namespace, for shelve and
962 804 # pickle to work interactively. Normally they rely on getting
963 805 # everything out of __main__, but for embedding purposes each IPython
964 806 # instance has its own private namespace, so we can't go shoving
965 807 # everything into __main__.
966 808
967 809 # note, however, that we should only do this for non-embedded
968 810 # ipythons, which really mimic the __main__.__dict__ with their own
969 811 # namespace. Embedded instances, on the other hand, should not do
970 812 # this because they need to manage the user local/global namespaces
971 813 # only, but they live within a 'normal' __main__ (meaning, they
972 814 # shouldn't overtake the execution environment of the script they're
973 815 # embedded in).
974 816
975 817 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
976 818
977 819 try:
978 820 main_name = self.user_ns['__name__']
979 821 except KeyError:
980 822 raise KeyError('user_ns dictionary MUST have a "__name__" key')
981 823 else:
982 824 sys.modules[main_name] = FakeModule(self.user_ns)
983 825
984 826 def init_user_ns(self):
985 827 """Initialize all user-visible namespaces to their minimum defaults.
986 828
987 829 Certain history lists are also initialized here, as they effectively
988 830 act as user namespaces.
989 831
990 832 Notes
991 833 -----
992 834 All data structures here are only filled in, they are NOT reset by this
993 835 method. If they were not empty before, data will simply be added to
994 836 therm.
995 837 """
996 838 # This function works in two parts: first we put a few things in
997 839 # user_ns, and we sync that contents into user_ns_hidden so that these
998 840 # initial variables aren't shown by %who. After the sync, we add the
999 841 # rest of what we *do* want the user to see with %who even on a new
1000 842 # session (probably nothing, so theye really only see their own stuff)
1001 843
1002 844 # The user dict must *always* have a __builtin__ reference to the
1003 845 # Python standard __builtin__ namespace, which must be imported.
1004 846 # This is so that certain operations in prompt evaluation can be
1005 847 # reliably executed with builtins. Note that we can NOT use
1006 848 # __builtins__ (note the 's'), because that can either be a dict or a
1007 849 # module, and can even mutate at runtime, depending on the context
1008 850 # (Python makes no guarantees on it). In contrast, __builtin__ is
1009 851 # always a module object, though it must be explicitly imported.
1010 852
1011 853 # For more details:
1012 854 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1013 855 ns = dict(__builtin__ = __builtin__)
1014 856
1015 857 # Put 'help' in the user namespace
1016 858 try:
1017 859 from site import _Helper
1018 860 ns['help'] = _Helper()
1019 861 except ImportError:
1020 862 warn('help() not available - check site.py')
1021 863
1022 864 # make global variables for user access to the histories
1023 865 ns['_ih'] = self.input_hist
1024 866 ns['_oh'] = self.output_hist
1025 867 ns['_dh'] = self.dir_hist
1026 868
1027 869 ns['_sh'] = shadowns
1028 870
1029 871 # user aliases to input and output histories. These shouldn't show up
1030 872 # in %who, as they can have very large reprs.
1031 873 ns['In'] = self.input_hist
1032 874 ns['Out'] = self.output_hist
1033 875
1034 876 # Store myself as the public api!!!
1035 877 ns['get_ipython'] = self.get_ipython
1036 878
1037 879 # Sync what we've added so far to user_ns_hidden so these aren't seen
1038 880 # by %who
1039 881 self.user_ns_hidden.update(ns)
1040 882
1041 883 # Anything put into ns now would show up in %who. Think twice before
1042 884 # putting anything here, as we really want %who to show the user their
1043 885 # stuff, not our variables.
1044 886
1045 887 # Finally, update the real user's namespace
1046 888 self.user_ns.update(ns)
1047 889
1048 890
1049 891 def reset(self):
1050 892 """Clear all internal namespaces.
1051 893
1052 894 Note that this is much more aggressive than %reset, since it clears
1053 895 fully all namespaces, as well as all input/output lists.
1054 896 """
1055 897 for ns in self.ns_refs_table:
1056 898 ns.clear()
1057 899
1058 900 self.alias_manager.clear_aliases()
1059 901
1060 902 # Clear input and output histories
1061 903 self.input_hist[:] = []
1062 904 self.input_hist_raw[:] = []
1063 905 self.output_hist.clear()
1064 906
1065 907 # Restore the user namespaces to minimal usability
1066 908 self.init_user_ns()
1067 909
1068 910 # Restore the default and user aliases
1069 911 self.alias_manager.init_aliases()
1070 912
1071 913 def reset_selective(self, regex=None):
1072 914 """Clear selective variables from internal namespaces based on a specified regular expression.
1073 915
1074 916 Parameters
1075 917 ----------
1076 918 regex : string or compiled pattern, optional
1077 919 A regular expression pattern that will be used in searching variable names in the users
1078 920 namespaces.
1079 921 """
1080 922 if regex is not None:
1081 923 try:
1082 924 m = re.compile(regex)
1083 925 except TypeError:
1084 926 raise TypeError('regex must be a string or compiled pattern')
1085 927 # Search for keys in each namespace that match the given regex
1086 928 # If a match is found, delete the key/value pair.
1087 929 for ns in self.ns_refs_table:
1088 930 for var in ns:
1089 931 if m.search(var):
1090 932 del ns[var]
1091 933
1092 934 def push(self, variables, interactive=True):
1093 935 """Inject a group of variables into the IPython user namespace.
1094 936
1095 937 Parameters
1096 938 ----------
1097 939 variables : dict, str or list/tuple of str
1098 940 The variables to inject into the user's namespace. If a dict,
1099 941 a simple update is done. If a str, the string is assumed to
1100 942 have variable names separated by spaces. A list/tuple of str
1101 943 can also be used to give the variable names. If just the variable
1102 944 names are give (list/tuple/str) then the variable values looked
1103 945 up in the callers frame.
1104 946 interactive : bool
1105 947 If True (default), the variables will be listed with the ``who``
1106 948 magic.
1107 949 """
1108 950 vdict = None
1109 951
1110 952 # We need a dict of name/value pairs to do namespace updates.
1111 953 if isinstance(variables, dict):
1112 954 vdict = variables
1113 955 elif isinstance(variables, (basestring, list, tuple)):
1114 956 if isinstance(variables, basestring):
1115 957 vlist = variables.split()
1116 958 else:
1117 959 vlist = variables
1118 960 vdict = {}
1119 961 cf = sys._getframe(1)
1120 962 for name in vlist:
1121 963 try:
1122 964 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1123 965 except:
1124 966 print ('Could not get variable %s from %s' %
1125 967 (name,cf.f_code.co_name))
1126 968 else:
1127 969 raise ValueError('variables must be a dict/str/list/tuple')
1128 970
1129 971 # Propagate variables to user namespace
1130 972 self.user_ns.update(vdict)
1131 973
1132 974 # And configure interactive visibility
1133 975 config_ns = self.user_ns_hidden
1134 976 if interactive:
1135 977 for name, val in vdict.iteritems():
1136 978 config_ns.pop(name, None)
1137 979 else:
1138 980 for name,val in vdict.iteritems():
1139 981 config_ns[name] = val
1140 982
1141 983 #-------------------------------------------------------------------------
1142 984 # Things related to history management
1143 985 #-------------------------------------------------------------------------
1144 986
1145 987 def init_history(self):
1146 988 # List of input with multi-line handling.
1147 989 self.input_hist = InputList()
1148 990 # This one will hold the 'raw' input history, without any
1149 991 # pre-processing. This will allow users to retrieve the input just as
1150 992 # it was exactly typed in by the user, with %hist -r.
1151 993 self.input_hist_raw = InputList()
1152 994
1153 995 # list of visited directories
1154 996 try:
1155 997 self.dir_hist = [os.getcwd()]
1156 998 except OSError:
1157 999 self.dir_hist = []
1158 1000
1159 1001 # dict of output history
1160 1002 self.output_hist = {}
1161 1003
1162 1004 # Now the history file
1163 1005 if self.profile:
1164 1006 histfname = 'history-%s' % self.profile
1165 1007 else:
1166 1008 histfname = 'history'
1167 1009 self.histfile = os.path.join(self.ipython_dir, histfname)
1168 1010
1169 1011 # Fill the history zero entry, user counter starts at 1
1170 1012 self.input_hist.append('\n')
1171 1013 self.input_hist_raw.append('\n')
1172 1014
1173 1015 def init_shadow_hist(self):
1174 1016 try:
1175 1017 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1176 1018 except exceptions.UnicodeDecodeError:
1177 1019 print "Your ipython_dir can't be decoded to unicode!"
1178 1020 print "Please set HOME environment variable to something that"
1179 1021 print r"only has ASCII characters, e.g. c:\home"
1180 1022 print "Now it is", self.ipython_dir
1181 1023 sys.exit()
1182 1024 self.shadowhist = ipcorehist.ShadowHist(self.db)
1183 1025
1184 1026 def savehist(self):
1185 1027 """Save input history to a file (via readline library)."""
1186 1028
1187 1029 try:
1188 1030 self.readline.write_history_file(self.histfile)
1189 1031 except:
1190 1032 print 'Unable to save IPython command history to file: ' + \
1191 1033 `self.histfile`
1192 1034
1193 1035 def reloadhist(self):
1194 1036 """Reload the input history from disk file."""
1195 1037
1196 1038 try:
1197 1039 self.readline.clear_history()
1198 1040 self.readline.read_history_file(self.shell.histfile)
1199 1041 except AttributeError:
1200 1042 pass
1201 1043
1202 1044 def history_saving_wrapper(self, func):
1203 1045 """ Wrap func for readline history saving
1204 1046
1205 1047 Convert func into callable that saves & restores
1206 1048 history around the call """
1207 1049
1208 1050 if self.has_readline:
1209 1051 from IPython.utils import rlineimpl as readline
1210 1052 else:
1211 1053 return func
1212 1054
1213 1055 def wrapper():
1214 1056 self.savehist()
1215 1057 try:
1216 1058 func()
1217 1059 finally:
1218 1060 readline.read_history_file(self.histfile)
1219 1061 return wrapper
1220 1062
1221 1063 #-------------------------------------------------------------------------
1222 1064 # Things related to exception handling and tracebacks (not debugging)
1223 1065 #-------------------------------------------------------------------------
1224 1066
1225 1067 def init_traceback_handlers(self, custom_exceptions):
1226 1068 # Syntax error handler.
1227 1069 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1228 1070
1229 1071 # The interactive one is initialized with an offset, meaning we always
1230 1072 # want to remove the topmost item in the traceback, which is our own
1231 1073 # internal code. Valid modes: ['Plain','Context','Verbose']
1232 1074 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1233 1075 color_scheme='NoColor',
1234 1076 tb_offset = 1)
1235 1077
1236 1078 # The instance will store a pointer to the system-wide exception hook,
1237 1079 # so that runtime code (such as magics) can access it. This is because
1238 1080 # during the read-eval loop, it may get temporarily overwritten.
1239 1081 self.sys_excepthook = sys.excepthook
1240 1082
1241 1083 # and add any custom exception handlers the user may have specified
1242 1084 self.set_custom_exc(*custom_exceptions)
1243 1085
1244 1086 # Set the exception mode
1245 1087 self.InteractiveTB.set_mode(mode=self.xmode)
1246 1088
1247 1089 def set_custom_exc(self,exc_tuple,handler):
1248 1090 """set_custom_exc(exc_tuple,handler)
1249 1091
1250 1092 Set a custom exception handler, which will be called if any of the
1251 1093 exceptions in exc_tuple occur in the mainloop (specifically, in the
1252 1094 runcode() method.
1253 1095
1254 1096 Inputs:
1255 1097
1256 1098 - exc_tuple: a *tuple* of valid exceptions to call the defined
1257 1099 handler for. It is very important that you use a tuple, and NOT A
1258 1100 LIST here, because of the way Python's except statement works. If
1259 1101 you only want to trap a single exception, use a singleton tuple:
1260 1102
1261 1103 exc_tuple == (MyCustomException,)
1262 1104
1263 1105 - handler: this must be defined as a function with the following
1264 1106 basic interface: def my_handler(self,etype,value,tb).
1265 1107
1266 1108 This will be made into an instance method (via new.instancemethod)
1267 1109 of IPython itself, and it will be called if any of the exceptions
1268 1110 listed in the exc_tuple are caught. If the handler is None, an
1269 1111 internal basic one is used, which just prints basic info.
1270 1112
1271 1113 WARNING: by putting in your own exception handler into IPython's main
1272 1114 execution loop, you run a very good chance of nasty crashes. This
1273 1115 facility should only be used if you really know what you are doing."""
1274 1116
1275 1117 assert type(exc_tuple)==type(()) , \
1276 1118 "The custom exceptions must be given AS A TUPLE."
1277 1119
1278 1120 def dummy_handler(self,etype,value,tb):
1279 1121 print '*** Simple custom exception handler ***'
1280 1122 print 'Exception type :',etype
1281 1123 print 'Exception value:',value
1282 1124 print 'Traceback :',tb
1283 1125 print 'Source code :','\n'.join(self.buffer)
1284 1126
1285 1127 if handler is None: handler = dummy_handler
1286 1128
1287 1129 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1288 1130 self.custom_exceptions = exc_tuple
1289 1131
1290 1132 def excepthook(self, etype, value, tb):
1291 1133 """One more defense for GUI apps that call sys.excepthook.
1292 1134
1293 1135 GUI frameworks like wxPython trap exceptions and call
1294 1136 sys.excepthook themselves. I guess this is a feature that
1295 1137 enables them to keep running after exceptions that would
1296 1138 otherwise kill their mainloop. This is a bother for IPython
1297 1139 which excepts to catch all of the program exceptions with a try:
1298 1140 except: statement.
1299 1141
1300 1142 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1301 1143 any app directly invokes sys.excepthook, it will look to the user like
1302 1144 IPython crashed. In order to work around this, we can disable the
1303 1145 CrashHandler and replace it with this excepthook instead, which prints a
1304 1146 regular traceback using our InteractiveTB. In this fashion, apps which
1305 1147 call sys.excepthook will generate a regular-looking exception from
1306 1148 IPython, and the CrashHandler will only be triggered by real IPython
1307 1149 crashes.
1308 1150
1309 1151 This hook should be used sparingly, only in places which are not likely
1310 1152 to be true IPython errors.
1311 1153 """
1312 1154 self.showtraceback((etype,value,tb),tb_offset=0)
1313 1155
1314 1156 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1315 1157 exception_only=False):
1316 1158 """Display the exception that just occurred.
1317 1159
1318 1160 If nothing is known about the exception, this is the method which
1319 1161 should be used throughout the code for presenting user tracebacks,
1320 1162 rather than directly invoking the InteractiveTB object.
1321 1163
1322 1164 A specific showsyntaxerror() also exists, but this method can take
1323 1165 care of calling it if needed, so unless you are explicitly catching a
1324 1166 SyntaxError exception, don't try to analyze the stack manually and
1325 1167 simply call this method."""
1326 1168
1327 1169 try:
1328 1170 if exc_tuple is None:
1329 1171 etype, value, tb = sys.exc_info()
1330 1172 else:
1331 1173 etype, value, tb = exc_tuple
1332 1174
1333 1175 if etype is None:
1334 1176 if hasattr(sys, 'last_type'):
1335 1177 etype, value, tb = sys.last_type, sys.last_value, \
1336 1178 sys.last_traceback
1337 1179 else:
1338 1180 self.write('No traceback available to show.\n')
1339 1181 return
1340 1182
1341 1183 if etype is SyntaxError:
1342 1184 # Though this won't be called by syntax errors in the input
1343 1185 # line, there may be SyntaxError cases whith imported code.
1344 1186 self.showsyntaxerror(filename)
1345 1187 elif etype is UsageError:
1346 1188 print "UsageError:", value
1347 1189 else:
1348 1190 # WARNING: these variables are somewhat deprecated and not
1349 1191 # necessarily safe to use in a threaded environment, but tools
1350 1192 # like pdb depend on their existence, so let's set them. If we
1351 1193 # find problems in the field, we'll need to revisit their use.
1352 1194 sys.last_type = etype
1353 1195 sys.last_value = value
1354 1196 sys.last_traceback = tb
1355 1197
1356 1198 if etype in self.custom_exceptions:
1357 1199 self.CustomTB(etype,value,tb)
1358 1200 else:
1359 1201 if exception_only:
1360 1202 m = ('An exception has occurred, use %tb to see the '
1361 1203 'full traceback.')
1362 1204 print m
1363 1205 self.InteractiveTB.show_exception_only(etype, value)
1364 1206 else:
1365 1207 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1366 1208 if self.InteractiveTB.call_pdb:
1367 1209 # pdb mucks up readline, fix it back
1368 1210 self.set_completer()
1369 1211
1370 1212 except KeyboardInterrupt:
1371 1213 self.write("\nKeyboardInterrupt\n")
1372 1214
1373 1215
1374 1216 def showsyntaxerror(self, filename=None):
1375 1217 """Display the syntax error that just occurred.
1376 1218
1377 1219 This doesn't display a stack trace because there isn't one.
1378 1220
1379 1221 If a filename is given, it is stuffed in the exception instead
1380 1222 of what was there before (because Python's parser always uses
1381 1223 "<string>" when reading from a string).
1382 1224 """
1383 1225 etype, value, last_traceback = sys.exc_info()
1384 1226
1385 1227 # See note about these variables in showtraceback() above
1386 1228 sys.last_type = etype
1387 1229 sys.last_value = value
1388 1230 sys.last_traceback = last_traceback
1389 1231
1390 1232 if filename and etype is SyntaxError:
1391 1233 # Work hard to stuff the correct filename in the exception
1392 1234 try:
1393 1235 msg, (dummy_filename, lineno, offset, line) = value
1394 1236 except:
1395 1237 # Not the format we expect; leave it alone
1396 1238 pass
1397 1239 else:
1398 1240 # Stuff in the right filename
1399 1241 try:
1400 1242 # Assume SyntaxError is a class exception
1401 1243 value = SyntaxError(msg, (filename, lineno, offset, line))
1402 1244 except:
1403 1245 # If that failed, assume SyntaxError is a string
1404 1246 value = msg, (filename, lineno, offset, line)
1405 1247 self.SyntaxTB(etype,value,[])
1406 1248
1407 def edit_syntax_error(self):
1408 """The bottom half of the syntax error handler called in the main loop.
1409
1410 Loop until syntax error is fixed or user cancels.
1411 """
1412
1413 while self.SyntaxTB.last_syntax_error:
1414 # copy and clear last_syntax_error
1415 err = self.SyntaxTB.clear_err_state()
1416 if not self._should_recompile(err):
1417 return
1418 try:
1419 # may set last_syntax_error again if a SyntaxError is raised
1420 self.safe_execfile(err.filename,self.user_ns)
1421 except:
1422 self.showtraceback()
1423 else:
1424 try:
1425 f = file(err.filename)
1426 try:
1427 # This should be inside a display_trap block and I
1428 # think it is.
1429 sys.displayhook(f.read())
1430 finally:
1431 f.close()
1432 except:
1433 self.showtraceback()
1434
1435 def _should_recompile(self,e):
1436 """Utility routine for edit_syntax_error"""
1437
1438 if e.filename in ('<ipython console>','<input>','<string>',
1439 '<console>','<BackgroundJob compilation>',
1440 None):
1441
1442 return False
1443 try:
1444 if (self.autoedit_syntax and
1445 not self.ask_yes_no('Return to editor to correct syntax error? '
1446 '[Y/n] ','y')):
1447 return False
1448 except EOFError:
1449 return False
1450
1451 def int0(x):
1452 try:
1453 return int(x)
1454 except TypeError:
1455 return 0
1456 # always pass integer line and offset values to editor hook
1457 try:
1458 self.hooks.fix_error_editor(e.filename,
1459 int0(e.lineno),int0(e.offset),e.msg)
1460 except TryNext:
1461 warn('Could not open editor')
1462 return False
1463 return True
1464
1465 1249 #-------------------------------------------------------------------------
1466 1250 # Things related to tab completion
1467 1251 #-------------------------------------------------------------------------
1468 1252
1469 1253 def complete(self, text):
1470 1254 """Return a sorted list of all possible completions on text.
1471 1255
1472 1256 Inputs:
1473 1257
1474 1258 - text: a string of text to be completed on.
1475 1259
1476 1260 This is a wrapper around the completion mechanism, similar to what
1477 1261 readline does at the command line when the TAB key is hit. By
1478 1262 exposing it as a method, it can be used by other non-readline
1479 1263 environments (such as GUIs) for text completion.
1480 1264
1481 1265 Simple usage example:
1482 1266
1483 1267 In [7]: x = 'hello'
1484 1268
1485 1269 In [8]: x
1486 1270 Out[8]: 'hello'
1487 1271
1488 1272 In [9]: print x
1489 1273 hello
1490 1274
1491 1275 In [10]: _ip.complete('x.l')
1492 1276 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1493 1277 """
1494 1278
1495 1279 # Inject names into __builtin__ so we can complete on the added names.
1496 1280 with self.builtin_trap:
1497 1281 complete = self.Completer.complete
1498 1282 state = 0
1499 1283 # use a dict so we get unique keys, since ipyhton's multiple
1500 1284 # completers can return duplicates. When we make 2.4 a requirement,
1501 1285 # start using sets instead, which are faster.
1502 1286 comps = {}
1503 1287 while True:
1504 1288 newcomp = complete(text,state,line_buffer=text)
1505 1289 if newcomp is None:
1506 1290 break
1507 1291 comps[newcomp] = 1
1508 1292 state += 1
1509 1293 outcomps = comps.keys()
1510 1294 outcomps.sort()
1511 1295 #print "T:",text,"OC:",outcomps # dbg
1512 1296 #print "vars:",self.user_ns.keys()
1513 1297 return outcomps
1514 1298
1515 1299 def set_custom_completer(self,completer,pos=0):
1516 1300 """Adds a new custom completer function.
1517 1301
1518 1302 The position argument (defaults to 0) is the index in the completers
1519 1303 list where you want the completer to be inserted."""
1520 1304
1521 1305 newcomp = new.instancemethod(completer,self.Completer,
1522 1306 self.Completer.__class__)
1523 1307 self.Completer.matchers.insert(pos,newcomp)
1524 1308
1525 1309 def set_completer(self):
1526 1310 """Reset readline's completer to be our own."""
1527 1311 self.readline.set_completer(self.Completer.complete)
1528 1312
1529 1313 def set_completer_frame(self, frame=None):
1530 1314 """Set the frame of the completer."""
1531 1315 if frame:
1532 1316 self.Completer.namespace = frame.f_locals
1533 1317 self.Completer.global_namespace = frame.f_globals
1534 1318 else:
1535 1319 self.Completer.namespace = self.user_ns
1536 1320 self.Completer.global_namespace = self.user_global_ns
1537 1321
1538 1322 #-------------------------------------------------------------------------
1539 1323 # Things related to readline
1540 1324 #-------------------------------------------------------------------------
1541 1325
1542 1326 def init_readline(self):
1543 1327 """Command history completion/saving/reloading."""
1544 1328
1545 1329 if self.readline_use:
1546 1330 import IPython.utils.rlineimpl as readline
1547 1331
1548 1332 self.rl_next_input = None
1549 1333 self.rl_do_indent = False
1550 1334
1551 1335 if not self.readline_use or not readline.have_readline:
1552 1336 self.has_readline = False
1553 1337 self.readline = None
1554 1338 # Set a number of methods that depend on readline to be no-op
1555 1339 self.savehist = no_op
1556 1340 self.reloadhist = no_op
1557 1341 self.set_completer = no_op
1558 1342 self.set_custom_completer = no_op
1559 1343 self.set_completer_frame = no_op
1560 1344 warn('Readline services not available or not loaded.')
1561 1345 else:
1562 1346 self.has_readline = True
1563 1347 self.readline = readline
1564 1348 sys.modules['readline'] = readline
1565 1349 import atexit
1566 1350 from IPython.core.completer import IPCompleter
1567 1351 self.Completer = IPCompleter(self,
1568 1352 self.user_ns,
1569 1353 self.user_global_ns,
1570 1354 self.readline_omit__names,
1571 1355 self.alias_manager.alias_table)
1572 1356 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1573 1357 self.strdispatchers['complete_command'] = sdisp
1574 1358 self.Completer.custom_completers = sdisp
1575 1359 # Platform-specific configuration
1576 1360 if os.name == 'nt':
1577 1361 self.readline_startup_hook = readline.set_pre_input_hook
1578 1362 else:
1579 1363 self.readline_startup_hook = readline.set_startup_hook
1580 1364
1581 1365 # Load user's initrc file (readline config)
1582 1366 # Or if libedit is used, load editrc.
1583 1367 inputrc_name = os.environ.get('INPUTRC')
1584 1368 if inputrc_name is None:
1585 1369 home_dir = get_home_dir()
1586 1370 if home_dir is not None:
1587 1371 inputrc_name = '.inputrc'
1588 1372 if readline.uses_libedit:
1589 1373 inputrc_name = '.editrc'
1590 1374 inputrc_name = os.path.join(home_dir, inputrc_name)
1591 1375 if os.path.isfile(inputrc_name):
1592 1376 try:
1593 1377 readline.read_init_file(inputrc_name)
1594 1378 except:
1595 1379 warn('Problems reading readline initialization file <%s>'
1596 1380 % inputrc_name)
1597 1381
1598 1382 # save this in sys so embedded copies can restore it properly
1599 1383 sys.ipcompleter = self.Completer.complete
1600 1384 self.set_completer()
1601 1385
1602 1386 # Configure readline according to user's prefs
1603 1387 # This is only done if GNU readline is being used. If libedit
1604 1388 # is being used (as on Leopard) the readline config is
1605 1389 # not run as the syntax for libedit is different.
1606 1390 if not readline.uses_libedit:
1607 1391 for rlcommand in self.readline_parse_and_bind:
1608 1392 #print "loading rl:",rlcommand # dbg
1609 1393 readline.parse_and_bind(rlcommand)
1610 1394
1611 1395 # Remove some chars from the delimiters list. If we encounter
1612 1396 # unicode chars, discard them.
1613 1397 delims = readline.get_completer_delims().encode("ascii", "ignore")
1614 1398 delims = delims.translate(string._idmap,
1615 1399 self.readline_remove_delims)
1616 1400 readline.set_completer_delims(delims)
1617 1401 # otherwise we end up with a monster history after a while:
1618 1402 readline.set_history_length(1000)
1619 1403 try:
1620 1404 #print '*** Reading readline history' # dbg
1621 1405 readline.read_history_file(self.histfile)
1622 1406 except IOError:
1623 1407 pass # It doesn't exist yet.
1624 1408
1625 1409 atexit.register(self.atexit_operations)
1626 1410 del atexit
1627 1411
1628 1412 # Configure auto-indent for all platforms
1629 1413 self.set_autoindent(self.autoindent)
1630 1414
1631 1415 def set_next_input(self, s):
1632 1416 """ Sets the 'default' input string for the next command line.
1633 1417
1634 1418 Requires readline.
1635 1419
1636 1420 Example:
1637 1421
1638 1422 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1639 1423 [D:\ipython]|2> Hello Word_ # cursor is here
1640 1424 """
1641 1425
1642 1426 self.rl_next_input = s
1643 1427
1428 # Maybe move this to the terminal subclass?
1644 1429 def pre_readline(self):
1645 1430 """readline hook to be used at the start of each line.
1646 1431
1647 1432 Currently it handles auto-indent only."""
1648 1433
1649 #debugx('self.indent_current_nsp','pre_readline:')
1650
1651 1434 if self.rl_do_indent:
1652 1435 self.readline.insert_text(self._indent_current_str())
1653 1436 if self.rl_next_input is not None:
1654 1437 self.readline.insert_text(self.rl_next_input)
1655 1438 self.rl_next_input = None
1656 1439
1657 1440 def _indent_current_str(self):
1658 1441 """return the current level of indentation as a string"""
1659 1442 return self.indent_current_nsp * ' '
1660 1443
1661 1444 #-------------------------------------------------------------------------
1662 1445 # Things related to magics
1663 1446 #-------------------------------------------------------------------------
1664 1447
1665 1448 def init_magics(self):
1666 1449 # Set user colors (don't do it in the constructor above so that it
1667 1450 # doesn't crash if colors option is invalid)
1668 1451 self.magic_colors(self.colors)
1669 1452 # History was moved to a separate module
1670 1453 from . import history
1671 1454 history.init_ipython(self)
1672 1455
1673 1456 def magic(self,arg_s):
1674 1457 """Call a magic function by name.
1675 1458
1676 1459 Input: a string containing the name of the magic function to call and any
1677 1460 additional arguments to be passed to the magic.
1678 1461
1679 1462 magic('name -opt foo bar') is equivalent to typing at the ipython
1680 1463 prompt:
1681 1464
1682 1465 In[1]: %name -opt foo bar
1683 1466
1684 1467 To call a magic without arguments, simply use magic('name').
1685 1468
1686 1469 This provides a proper Python function to call IPython's magics in any
1687 1470 valid Python code you can type at the interpreter, including loops and
1688 1471 compound statements.
1689 1472 """
1690 1473 args = arg_s.split(' ',1)
1691 1474 magic_name = args[0]
1692 1475 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1693 1476
1694 1477 try:
1695 1478 magic_args = args[1]
1696 1479 except IndexError:
1697 1480 magic_args = ''
1698 1481 fn = getattr(self,'magic_'+magic_name,None)
1699 1482 if fn is None:
1700 1483 error("Magic function `%s` not found." % magic_name)
1701 1484 else:
1702 1485 magic_args = self.var_expand(magic_args,1)
1703 1486 with nested(self.builtin_trap,):
1704 1487 result = fn(magic_args)
1705 1488 return result
1706 1489
1707 1490 def define_magic(self, magicname, func):
1708 1491 """Expose own function as magic function for ipython
1709 1492
1710 1493 def foo_impl(self,parameter_s=''):
1711 1494 'My very own magic!. (Use docstrings, IPython reads them).'
1712 1495 print 'Magic function. Passed parameter is between < >:'
1713 1496 print '<%s>' % parameter_s
1714 1497 print 'The self object is:',self
1715 1498
1716 1499 self.define_magic('foo',foo_impl)
1717 1500 """
1718 1501
1719 1502 import new
1720 1503 im = new.instancemethod(func,self, self.__class__)
1721 1504 old = getattr(self, "magic_" + magicname, None)
1722 1505 setattr(self, "magic_" + magicname, im)
1723 1506 return old
1724 1507
1725 1508 #-------------------------------------------------------------------------
1726 1509 # Things related to macros
1727 1510 #-------------------------------------------------------------------------
1728 1511
1729 1512 def define_macro(self, name, themacro):
1730 1513 """Define a new macro
1731 1514
1732 1515 Parameters
1733 1516 ----------
1734 1517 name : str
1735 1518 The name of the macro.
1736 1519 themacro : str or Macro
1737 1520 The action to do upon invoking the macro. If a string, a new
1738 1521 Macro object is created by passing the string to it.
1739 1522 """
1740 1523
1741 1524 from IPython.core import macro
1742 1525
1743 1526 if isinstance(themacro, basestring):
1744 1527 themacro = macro.Macro(themacro)
1745 1528 if not isinstance(themacro, macro.Macro):
1746 1529 raise ValueError('A macro must be a string or a Macro instance.')
1747 1530 self.user_ns[name] = themacro
1748 1531
1749 1532 #-------------------------------------------------------------------------
1750 1533 # Things related to the running of system commands
1751 1534 #-------------------------------------------------------------------------
1752 1535
1753 1536 def system(self, cmd):
1754 1537 """Make a system call, using IPython."""
1755 1538 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1756 1539
1757 1540 #-------------------------------------------------------------------------
1758 1541 # Things related to aliases
1759 1542 #-------------------------------------------------------------------------
1760 1543
1761 1544 def init_alias(self):
1762 1545 self.alias_manager = AliasManager(shell=self, config=self.config)
1763 1546 self.ns_table['alias'] = self.alias_manager.alias_table,
1764 1547
1765 1548 #-------------------------------------------------------------------------
1766 1549 # Things related to extensions and plugins
1767 1550 #-------------------------------------------------------------------------
1768 1551
1769 1552 def init_extension_manager(self):
1770 1553 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1771 1554
1772 1555 def init_plugin_manager(self):
1773 1556 self.plugin_manager = PluginManager(config=self.config)
1774 1557
1775 1558 #-------------------------------------------------------------------------
1559 # Things related to the prefilter
1560 #-------------------------------------------------------------------------
1561
1562 def init_prefilter(self):
1563 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1564 # Ultimately this will be refactored in the new interpreter code, but
1565 # for now, we should expose the main prefilter method (there's legacy
1566 # code out there that may rely on this).
1567 self.prefilter = self.prefilter_manager.prefilter_lines
1568
1569 #-------------------------------------------------------------------------
1776 1570 # Things related to the running of code
1777 1571 #-------------------------------------------------------------------------
1778 1572
1779 1573 def ex(self, cmd):
1780 1574 """Execute a normal python statement in user namespace."""
1781 1575 with nested(self.builtin_trap,):
1782 1576 exec cmd in self.user_global_ns, self.user_ns
1783 1577
1784 1578 def ev(self, expr):
1785 1579 """Evaluate python expression expr in user namespace.
1786 1580
1787 1581 Returns the result of evaluation
1788 1582 """
1789 1583 with nested(self.builtin_trap,):
1790 1584 return eval(expr, self.user_global_ns, self.user_ns)
1791 1585
1792 def mainloop(self, display_banner=None):
1793 """Start the mainloop.
1794
1795 If an optional banner argument is given, it will override the
1796 internally created default banner.
1797 """
1798
1799 with nested(self.builtin_trap, self.display_trap):
1800
1801 # if you run stuff with -c <cmd>, raw hist is not updated
1802 # ensure that it's in sync
1803 if len(self.input_hist) != len (self.input_hist_raw):
1804 self.input_hist_raw = InputList(self.input_hist)
1805
1806 while 1:
1807 try:
1808 self.interact(display_banner=display_banner)
1809 #self.interact_with_readline()
1810 # XXX for testing of a readline-decoupled repl loop, call
1811 # interact_with_readline above
1812 break
1813 except KeyboardInterrupt:
1814 # this should not be necessary, but KeyboardInterrupt
1815 # handling seems rather unpredictable...
1816 self.write("\nKeyboardInterrupt in interact()\n")
1817
1818 def interact_prompt(self):
1819 """ Print the prompt (in read-eval-print loop)
1820
1821 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1822 used in standard IPython flow.
1823 """
1824 if self.more:
1825 try:
1826 prompt = self.hooks.generate_prompt(True)
1827 except:
1828 self.showtraceback()
1829 if self.autoindent:
1830 self.rl_do_indent = True
1831
1832 else:
1833 try:
1834 prompt = self.hooks.generate_prompt(False)
1835 except:
1836 self.showtraceback()
1837 self.write(prompt)
1838
1839 def interact_handle_input(self,line):
1840 """ Handle the input line (in read-eval-print loop)
1841
1842 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1843 used in standard IPython flow.
1844 """
1845 if line.lstrip() == line:
1846 self.shadowhist.add(line.strip())
1847 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1848
1849 if line.strip():
1850 if self.more:
1851 self.input_hist_raw[-1] += '%s\n' % line
1852 else:
1853 self.input_hist_raw.append('%s\n' % line)
1854
1855
1856 self.more = self.push_line(lineout)
1857 if (self.SyntaxTB.last_syntax_error and
1858 self.autoedit_syntax):
1859 self.edit_syntax_error()
1860
1861 def interact_with_readline(self):
1862 """ Demo of using interact_handle_input, interact_prompt
1863
1864 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1865 it should work like this.
1866 """
1867 self.readline_startup_hook(self.pre_readline)
1868 while not self.exit_now:
1869 self.interact_prompt()
1870 if self.more:
1871 self.rl_do_indent = True
1872 else:
1873 self.rl_do_indent = False
1874 line = raw_input_original().decode(self.stdin_encoding)
1875 self.interact_handle_input(line)
1876
1877 def interact(self, display_banner=None):
1878 """Closely emulate the interactive Python console."""
1879
1880 # batch run -> do not interact
1881 if self.exit_now:
1882 return
1883
1884 if display_banner is None:
1885 display_banner = self.display_banner
1886 if display_banner:
1887 self.show_banner()
1888
1889 more = 0
1890
1891 # Mark activity in the builtins
1892 __builtin__.__dict__['__IPYTHON__active'] += 1
1893
1894 if self.has_readline:
1895 self.readline_startup_hook(self.pre_readline)
1896 # exit_now is set by a call to %Exit or %Quit, through the
1897 # ask_exit callback.
1898
1899 while not self.exit_now:
1900 self.hooks.pre_prompt_hook()
1901 if more:
1902 try:
1903 prompt = self.hooks.generate_prompt(True)
1904 except:
1905 self.showtraceback()
1906 if self.autoindent:
1907 self.rl_do_indent = True
1908
1909 else:
1910 try:
1911 prompt = self.hooks.generate_prompt(False)
1912 except:
1913 self.showtraceback()
1914 try:
1915 line = self.raw_input(prompt, more)
1916 if self.exit_now:
1917 # quick exit on sys.std[in|out] close
1918 break
1919 if self.autoindent:
1920 self.rl_do_indent = False
1921
1922 except KeyboardInterrupt:
1923 #double-guard against keyboardinterrupts during kbdint handling
1924 try:
1925 self.write('\nKeyboardInterrupt\n')
1926 self.resetbuffer()
1927 # keep cache in sync with the prompt counter:
1928 self.outputcache.prompt_count -= 1
1929
1930 if self.autoindent:
1931 self.indent_current_nsp = 0
1932 more = 0
1933 except KeyboardInterrupt:
1934 pass
1935 except EOFError:
1936 if self.autoindent:
1937 self.rl_do_indent = False
1938 if self.has_readline:
1939 self.readline_startup_hook(None)
1940 self.write('\n')
1941 self.exit()
1942 except bdb.BdbQuit:
1943 warn('The Python debugger has exited with a BdbQuit exception.\n'
1944 'Because of how pdb handles the stack, it is impossible\n'
1945 'for IPython to properly format this particular exception.\n'
1946 'IPython will resume normal operation.')
1947 except:
1948 # exceptions here are VERY RARE, but they can be triggered
1949 # asynchronously by signal handlers, for example.
1950 self.showtraceback()
1951 else:
1952 more = self.push_line(line)
1953 if (self.SyntaxTB.last_syntax_error and
1954 self.autoedit_syntax):
1955 self.edit_syntax_error()
1956
1957 # We are off again...
1958 __builtin__.__dict__['__IPYTHON__active'] -= 1
1959
1960 # Turn off the exit flag, so the mainloop can be restarted if desired
1961 self.exit_now = False
1962
1963 1586 def safe_execfile(self, fname, *where, **kw):
1964 1587 """A safe version of the builtin execfile().
1965 1588
1966 1589 This version will never throw an exception, but instead print
1967 1590 helpful error messages to the screen. This only works on pure
1968 1591 Python files with the .py extension.
1969 1592
1970 1593 Parameters
1971 1594 ----------
1972 1595 fname : string
1973 1596 The name of the file to be executed.
1974 1597 where : tuple
1975 1598 One or two namespaces, passed to execfile() as (globals,locals).
1976 1599 If only one is given, it is passed as both.
1977 1600 exit_ignore : bool (False)
1978 1601 If True, then silence SystemExit for non-zero status (it is always
1979 1602 silenced for zero status, as it is so common).
1980 1603 """
1981 1604 kw.setdefault('exit_ignore', False)
1982 1605
1983 1606 fname = os.path.abspath(os.path.expanduser(fname))
1984 1607
1985 1608 # Make sure we have a .py file
1986 1609 if not fname.endswith('.py'):
1987 1610 warn('File must end with .py to be run using execfile: <%s>' % fname)
1988 1611
1989 1612 # Make sure we can open the file
1990 1613 try:
1991 1614 with open(fname) as thefile:
1992 1615 pass
1993 1616 except:
1994 1617 warn('Could not open file <%s> for safe execution.' % fname)
1995 1618 return
1996 1619
1997 1620 # Find things also in current directory. This is needed to mimic the
1998 1621 # behavior of running a script from the system command line, where
1999 1622 # Python inserts the script's directory into sys.path
2000 1623 dname = os.path.dirname(fname)
2001 1624
2002 1625 with prepended_to_syspath(dname):
2003 1626 try:
2004 1627 execfile(fname,*where)
2005 1628 except SystemExit, status:
2006 1629 # If the call was made with 0 or None exit status (sys.exit(0)
2007 1630 # or sys.exit() ), don't bother showing a traceback, as both of
2008 1631 # these are considered normal by the OS:
2009 1632 # > python -c'import sys;sys.exit(0)'; echo $?
2010 1633 # 0
2011 1634 # > python -c'import sys;sys.exit()'; echo $?
2012 1635 # 0
2013 1636 # For other exit status, we show the exception unless
2014 1637 # explicitly silenced, but only in short form.
2015 1638 if status.code not in (0, None) and not kw['exit_ignore']:
2016 1639 self.showtraceback(exception_only=True)
2017 1640 except:
2018 1641 self.showtraceback()
2019 1642
2020 1643 def safe_execfile_ipy(self, fname):
2021 1644 """Like safe_execfile, but for .ipy files with IPython syntax.
2022 1645
2023 1646 Parameters
2024 1647 ----------
2025 1648 fname : str
2026 1649 The name of the file to execute. The filename must have a
2027 1650 .ipy extension.
2028 1651 """
2029 1652 fname = os.path.abspath(os.path.expanduser(fname))
2030 1653
2031 1654 # Make sure we have a .py file
2032 1655 if not fname.endswith('.ipy'):
2033 1656 warn('File must end with .py to be run using execfile: <%s>' % fname)
2034 1657
2035 1658 # Make sure we can open the file
2036 1659 try:
2037 1660 with open(fname) as thefile:
2038 1661 pass
2039 1662 except:
2040 1663 warn('Could not open file <%s> for safe execution.' % fname)
2041 1664 return
2042 1665
2043 1666 # Find things also in current directory. This is needed to mimic the
2044 1667 # behavior of running a script from the system command line, where
2045 1668 # Python inserts the script's directory into sys.path
2046 1669 dname = os.path.dirname(fname)
2047 1670
2048 1671 with prepended_to_syspath(dname):
2049 1672 try:
2050 1673 with open(fname) as thefile:
2051 1674 script = thefile.read()
2052 1675 # self.runlines currently captures all exceptions
2053 1676 # raise in user code. It would be nice if there were
2054 1677 # versions of runlines, execfile that did raise, so
2055 1678 # we could catch the errors.
2056 1679 self.runlines(script, clean=True)
2057 1680 except:
2058 1681 self.showtraceback()
2059 1682 warn('Unknown failure executing file: <%s>' % fname)
2060 1683
2061 def _is_secondary_block_start(self, s):
2062 if not s.endswith(':'):
2063 return False
2064 if (s.startswith('elif') or
2065 s.startswith('else') or
2066 s.startswith('except') or
2067 s.startswith('finally')):
2068 return True
2069
2070 def cleanup_ipy_script(self, script):
2071 """Make a script safe for self.runlines()
2072
2073 Currently, IPython is lines based, with blocks being detected by
2074 empty lines. This is a problem for block based scripts that may
2075 not have empty lines after blocks. This script adds those empty
2076 lines to make scripts safe for running in the current line based
2077 IPython.
2078 """
2079 res = []
2080 lines = script.splitlines()
2081 level = 0
2082
2083 for l in lines:
2084 lstripped = l.lstrip()
2085 stripped = l.strip()
2086 if not stripped:
2087 continue
2088 newlevel = len(l) - len(lstripped)
2089 if level > 0 and newlevel == 0 and \
2090 not self._is_secondary_block_start(stripped):
2091 # add empty line
2092 res.append('')
2093 res.append(l)
2094 level = newlevel
2095
2096 return '\n'.join(res) + '\n'
2097
2098 1684 def runlines(self, lines, clean=False):
2099 1685 """Run a string of one or more lines of source.
2100 1686
2101 1687 This method is capable of running a string containing multiple source
2102 1688 lines, as if they had been entered at the IPython prompt. Since it
2103 1689 exposes IPython's processing machinery, the given strings can contain
2104 1690 magic calls (%magic), special shell access (!cmd), etc.
2105 1691 """
2106 1692
2107 1693 if isinstance(lines, (list, tuple)):
2108 1694 lines = '\n'.join(lines)
2109 1695
2110 1696 if clean:
2111 lines = self.cleanup_ipy_script(lines)
1697 lines = self._cleanup_ipy_script(lines)
2112 1698
2113 1699 # We must start with a clean buffer, in case this is run from an
2114 1700 # interactive IPython session (via a magic, for example).
2115 1701 self.resetbuffer()
2116 1702 lines = lines.splitlines()
2117 1703 more = 0
2118 1704
2119 1705 with nested(self.builtin_trap, self.display_trap):
2120 1706 for line in lines:
2121 1707 # skip blank lines so we don't mess up the prompt counter, but do
2122 1708 # NOT skip even a blank line if we are in a code block (more is
2123 1709 # true)
2124 1710
2125 1711 if line or more:
2126 1712 # push to raw history, so hist line numbers stay in sync
2127 1713 self.input_hist_raw.append("# " + line + "\n")
2128 1714 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2129 1715 more = self.push_line(prefiltered)
2130 1716 # IPython's runsource returns None if there was an error
2131 1717 # compiling the code. This allows us to stop processing right
2132 1718 # away, so the user gets the error message at the right place.
2133 1719 if more is None:
2134 1720 break
2135 1721 else:
2136 1722 self.input_hist_raw.append("\n")
2137 1723 # final newline in case the input didn't have it, so that the code
2138 1724 # actually does get executed
2139 1725 if more:
2140 1726 self.push_line('\n')
2141 1727
2142 1728 def runsource(self, source, filename='<input>', symbol='single'):
2143 1729 """Compile and run some source in the interpreter.
2144 1730
2145 1731 Arguments are as for compile_command().
2146 1732
2147 1733 One several things can happen:
2148 1734
2149 1735 1) The input is incorrect; compile_command() raised an
2150 1736 exception (SyntaxError or OverflowError). A syntax traceback
2151 1737 will be printed by calling the showsyntaxerror() method.
2152 1738
2153 1739 2) The input is incomplete, and more input is required;
2154 1740 compile_command() returned None. Nothing happens.
2155 1741
2156 1742 3) The input is complete; compile_command() returned a code
2157 1743 object. The code is executed by calling self.runcode() (which
2158 1744 also handles run-time exceptions, except for SystemExit).
2159 1745
2160 1746 The return value is:
2161 1747
2162 1748 - True in case 2
2163 1749
2164 1750 - False in the other cases, unless an exception is raised, where
2165 1751 None is returned instead. This can be used by external callers to
2166 1752 know whether to continue feeding input or not.
2167 1753
2168 1754 The return value can be used to decide whether to use sys.ps1 or
2169 1755 sys.ps2 to prompt the next line."""
2170 1756
2171 1757 # if the source code has leading blanks, add 'if 1:\n' to it
2172 1758 # this allows execution of indented pasted code. It is tempting
2173 1759 # to add '\n' at the end of source to run commands like ' a=1'
2174 1760 # directly, but this fails for more complicated scenarios
2175 1761 source=source.encode(self.stdin_encoding)
2176 1762 if source[:1] in [' ', '\t']:
2177 1763 source = 'if 1:\n%s' % source
2178 1764
2179 1765 try:
2180 1766 code = self.compile(source,filename,symbol)
2181 1767 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2182 1768 # Case 1
2183 1769 self.showsyntaxerror(filename)
2184 1770 return None
2185 1771
2186 1772 if code is None:
2187 1773 # Case 2
2188 1774 return True
2189 1775
2190 1776 # Case 3
2191 1777 # We store the code object so that threaded shells and
2192 1778 # custom exception handlers can access all this info if needed.
2193 1779 # The source corresponding to this can be obtained from the
2194 1780 # buffer attribute as '\n'.join(self.buffer).
2195 1781 self.code_to_run = code
2196 1782 # now actually execute the code object
2197 1783 if self.runcode(code) == 0:
2198 1784 return False
2199 1785 else:
2200 1786 return None
2201 1787
2202 1788 def runcode(self,code_obj):
2203 1789 """Execute a code object.
2204 1790
2205 1791 When an exception occurs, self.showtraceback() is called to display a
2206 1792 traceback.
2207 1793
2208 1794 Return value: a flag indicating whether the code to be run completed
2209 1795 successfully:
2210 1796
2211 1797 - 0: successful execution.
2212 1798 - 1: an error occurred.
2213 1799 """
2214 1800
2215 1801 # Set our own excepthook in case the user code tries to call it
2216 1802 # directly, so that the IPython crash handler doesn't get triggered
2217 1803 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2218 1804
2219 1805 # we save the original sys.excepthook in the instance, in case config
2220 1806 # code (such as magics) needs access to it.
2221 1807 self.sys_excepthook = old_excepthook
2222 1808 outflag = 1 # happens in more places, so it's easier as default
2223 1809 try:
2224 1810 try:
2225 1811 self.hooks.pre_runcode_hook()
2226 1812 exec code_obj in self.user_global_ns, self.user_ns
2227 1813 finally:
2228 1814 # Reset our crash handler in place
2229 1815 sys.excepthook = old_excepthook
2230 1816 except SystemExit:
2231 1817 self.resetbuffer()
2232 1818 self.showtraceback(exception_only=True)
2233 1819 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2234 1820 except self.custom_exceptions:
2235 1821 etype,value,tb = sys.exc_info()
2236 1822 self.CustomTB(etype,value,tb)
2237 1823 except:
2238 1824 self.showtraceback()
2239 1825 else:
2240 1826 outflag = 0
2241 1827 if softspace(sys.stdout, 0):
2242 1828 print
2243 1829 # Flush out code object which has been run (and source)
2244 1830 self.code_to_run = None
2245 1831 return outflag
2246 1832
2247 1833 def push_line(self, line):
2248 1834 """Push a line to the interpreter.
2249 1835
2250 1836 The line should not have a trailing newline; it may have
2251 1837 internal newlines. The line is appended to a buffer and the
2252 1838 interpreter's runsource() method is called with the
2253 1839 concatenated contents of the buffer as source. If this
2254 1840 indicates that the command was executed or invalid, the buffer
2255 1841 is reset; otherwise, the command is incomplete, and the buffer
2256 1842 is left as it was after the line was appended. The return
2257 1843 value is 1 if more input is required, 0 if the line was dealt
2258 1844 with in some way (this is the same as runsource()).
2259 1845 """
2260 1846
2261 1847 # autoindent management should be done here, and not in the
2262 1848 # interactive loop, since that one is only seen by keyboard input. We
2263 1849 # need this done correctly even for code run via runlines (which uses
2264 1850 # push).
2265 1851
2266 1852 #print 'push line: <%s>' % line # dbg
2267 1853 for subline in line.splitlines():
2268 1854 self._autoindent_update(subline)
2269 1855 self.buffer.append(line)
2270 1856 more = self.runsource('\n'.join(self.buffer), self.filename)
2271 1857 if not more:
2272 1858 self.resetbuffer()
2273 1859 return more
2274 1860
1861 def resetbuffer(self):
1862 """Reset the input buffer."""
1863 self.buffer[:] = []
1864
1865 def _is_secondary_block_start(self, s):
1866 if not s.endswith(':'):
1867 return False
1868 if (s.startswith('elif') or
1869 s.startswith('else') or
1870 s.startswith('except') or
1871 s.startswith('finally')):
1872 return True
1873
1874 def _cleanup_ipy_script(self, script):
1875 """Make a script safe for self.runlines()
1876
1877 Currently, IPython is lines based, with blocks being detected by
1878 empty lines. This is a problem for block based scripts that may
1879 not have empty lines after blocks. This script adds those empty
1880 lines to make scripts safe for running in the current line based
1881 IPython.
1882 """
1883 res = []
1884 lines = script.splitlines()
1885 level = 0
1886
1887 for l in lines:
1888 lstripped = l.lstrip()
1889 stripped = l.strip()
1890 if not stripped:
1891 continue
1892 newlevel = len(l) - len(lstripped)
1893 if level > 0 and newlevel == 0 and \
1894 not self._is_secondary_block_start(stripped):
1895 # add empty line
1896 res.append('')
1897 res.append(l)
1898 level = newlevel
1899
1900 return '\n'.join(res) + '\n'
1901
2275 1902 def _autoindent_update(self,line):
2276 1903 """Keep track of the indent level."""
2277 1904
2278 1905 #debugx('line')
2279 1906 #debugx('self.indent_current_nsp')
2280 1907 if self.autoindent:
2281 1908 if line:
2282 1909 inisp = num_ini_spaces(line)
2283 1910 if inisp < self.indent_current_nsp:
2284 1911 self.indent_current_nsp = inisp
2285 1912
2286 1913 if line[-1] == ':':
2287 1914 self.indent_current_nsp += 4
2288 1915 elif dedent_re.match(line):
2289 1916 self.indent_current_nsp -= 4
2290 1917 else:
2291 1918 self.indent_current_nsp = 0
2292 1919
2293 def resetbuffer(self):
2294 """Reset the input buffer."""
2295 self.buffer[:] = []
2296
2297 def raw_input(self,prompt='',continue_prompt=False):
2298 """Write a prompt and read a line.
2299
2300 The returned line does not include the trailing newline.
2301 When the user enters the EOF key sequence, EOFError is raised.
2302
2303 Optional inputs:
2304
2305 - prompt(''): a string to be printed to prompt the user.
2306
2307 - continue_prompt(False): whether this line is the first one or a
2308 continuation in a sequence of inputs.
2309 """
2310 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2311
2312 # Code run by the user may have modified the readline completer state.
2313 # We must ensure that our completer is back in place.
2314
2315 if self.has_readline:
2316 self.set_completer()
2317
2318 try:
2319 line = raw_input_original(prompt).decode(self.stdin_encoding)
2320 except ValueError:
2321 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2322 " or sys.stdout.close()!\nExiting IPython!")
2323 self.ask_exit()
2324 return ""
2325
2326 # Try to be reasonably smart about not re-indenting pasted input more
2327 # than necessary. We do this by trimming out the auto-indent initial
2328 # spaces, if the user's actual input started itself with whitespace.
2329 #debugx('self.buffer[-1]')
2330
2331 if self.autoindent:
2332 if num_ini_spaces(line) > self.indent_current_nsp:
2333 line = line[self.indent_current_nsp:]
2334 self.indent_current_nsp = 0
2335
2336 # store the unfiltered input before the user has any chance to modify
2337 # it.
2338 if line.strip():
2339 if continue_prompt:
2340 self.input_hist_raw[-1] += '%s\n' % line
2341 if self.has_readline and self.readline_use:
2342 try:
2343 histlen = self.readline.get_current_history_length()
2344 if histlen > 1:
2345 newhist = self.input_hist_raw[-1].rstrip()
2346 self.readline.remove_history_item(histlen-1)
2347 self.readline.replace_history_item(histlen-2,
2348 newhist.encode(self.stdin_encoding))
2349 except AttributeError:
2350 pass # re{move,place}_history_item are new in 2.4.
2351 else:
2352 self.input_hist_raw.append('%s\n' % line)
2353 # only entries starting at first column go to shadow history
2354 if line.lstrip() == line:
2355 self.shadowhist.add(line.strip())
2356 elif not continue_prompt:
2357 self.input_hist_raw.append('\n')
2358 try:
2359 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2360 except:
2361 # blanket except, in case a user-defined prefilter crashes, so it
2362 # can't take all of ipython with it.
2363 self.showtraceback()
2364 return ''
2365 else:
2366 return lineout
2367
2368 1920 #-------------------------------------------------------------------------
2369 # Things related to the prefilter
1921 # Things related to GUI support and pylab
2370 1922 #-------------------------------------------------------------------------
2371 1923
2372 def init_prefilter(self):
2373 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2374 # Ultimately this will be refactored in the new interpreter code, but
2375 # for now, we should expose the main prefilter method (there's legacy
2376 # code out there that may rely on this).
2377 self.prefilter = self.prefilter_manager.prefilter_lines
1924 def enable_pylab(self, gui=None):
1925 raise NotImplementedError('Implement enable_pylab in a subclass')
2378 1926
2379 1927 #-------------------------------------------------------------------------
2380 1928 # Utilities
2381 1929 #-------------------------------------------------------------------------
2382 1930
2383 1931 def getoutput(self, cmd):
2384 1932 return getoutput(self.var_expand(cmd,depth=2),
2385 1933 header=self.system_header,
2386 1934 verbose=self.system_verbose)
2387 1935
2388 1936 def getoutputerror(self, cmd):
2389 1937 return getoutputerror(self.var_expand(cmd,depth=2),
2390 1938 header=self.system_header,
2391 1939 verbose=self.system_verbose)
2392 1940
2393 1941 def var_expand(self,cmd,depth=0):
2394 1942 """Expand python variables in a string.
2395 1943
2396 1944 The depth argument indicates how many frames above the caller should
2397 1945 be walked to look for the local namespace where to expand variables.
2398 1946
2399 1947 The global namespace for expansion is always the user's interactive
2400 1948 namespace.
2401 1949 """
2402 1950
2403 1951 return str(ItplNS(cmd,
2404 1952 self.user_ns, # globals
2405 1953 # Skip our own frame in searching for locals:
2406 1954 sys._getframe(depth+1).f_locals # locals
2407 1955 ))
2408 1956
2409 1957 def mktempfile(self,data=None):
2410 1958 """Make a new tempfile and return its filename.
2411 1959
2412 1960 This makes a call to tempfile.mktemp, but it registers the created
2413 1961 filename internally so ipython cleans it up at exit time.
2414 1962
2415 1963 Optional inputs:
2416 1964
2417 1965 - data(None): if data is given, it gets written out to the temp file
2418 1966 immediately, and the file is closed again."""
2419 1967
2420 1968 filename = tempfile.mktemp('.py','ipython_edit_')
2421 1969 self.tempfiles.append(filename)
2422 1970
2423 1971 if data:
2424 1972 tmp_file = open(filename,'w')
2425 1973 tmp_file.write(data)
2426 1974 tmp_file.close()
2427 1975 return filename
2428 1976
1977 # TODO: This should be removed when Term is refactored.
2429 1978 def write(self,data):
2430 1979 """Write a string to the default output"""
2431 1980 Term.cout.write(data)
2432 1981
1982 # TODO: This should be removed when Term is refactored.
2433 1983 def write_err(self,data):
2434 1984 """Write a string to the default error output"""
2435 1985 Term.cerr.write(data)
2436 1986
2437 1987 def ask_yes_no(self,prompt,default=True):
2438 1988 if self.quiet:
2439 1989 return True
2440 1990 return ask_yes_no(prompt,default)
2441 1991
2442 1992 #-------------------------------------------------------------------------
2443 # Things related to GUI support and pylab
2444 #-------------------------------------------------------------------------
2445
2446 def enable_pylab(self, gui=None):
2447 """Activate pylab support at runtime.
2448
2449 This turns on support for matplotlib, preloads into the interactive
2450 namespace all of numpy and pylab, and configures IPython to correcdtly
2451 interact with the GUI event loop. The GUI backend to be used can be
2452 optionally selected with the optional :param:`gui` argument.
2453
2454 Parameters
2455 ----------
2456 gui : optional, string
2457
2458 If given, dictates the choice of matplotlib GUI backend to use
2459 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2460 'gtk'), otherwise we use the default chosen by matplotlib (as
2461 dictated by the matplotlib build-time options plus the user's
2462 matplotlibrc configuration file).
2463 """
2464 # We want to prevent the loading of pylab to pollute the user's
2465 # namespace as shown by the %who* magics, so we execute the activation
2466 # code in an empty namespace, and we update *both* user_ns and
2467 # user_ns_hidden with this information.
2468 ns = {}
2469 gui = pylab_activate(ns, gui)
2470 self.user_ns.update(ns)
2471 self.user_ns_hidden.update(ns)
2472 # Now we must activate the gui pylab wants to use, and fix %run to take
2473 # plot updates into account
2474 enable_gui(gui)
2475 self.magic_run = self._pylab_magic_run
2476
2477 #-------------------------------------------------------------------------
2478 1993 # Things related to IPython exiting
2479 1994 #-------------------------------------------------------------------------
2480 1995
2481 def ask_exit(self):
2482 """ Ask the shell to exit. Can be overiden and used as a callback. """
2483 self.exit_now = True
2484
2485 def exit(self):
2486 """Handle interactive exit.
2487
2488 This method calls the ask_exit callback."""
2489 if self.confirm_exit:
2490 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2491 self.ask_exit()
2492 else:
2493 self.ask_exit()
2494
2495 1996 def atexit_operations(self):
2496 1997 """This will be executed at the time of exit.
2497 1998
2498 1999 Saving of persistent data should be performed here.
2499 2000 """
2500 2001 self.savehist()
2501 2002
2502 2003 # Cleanup all tempfiles left around
2503 2004 for tfile in self.tempfiles:
2504 2005 try:
2505 2006 os.unlink(tfile)
2506 2007 except OSError:
2507 2008 pass
2508 2009
2509 2010 # Clear all user namespaces to release all references cleanly.
2510 2011 self.reset()
2511 2012
2512 2013 # Run user hooks
2513 2014 self.hooks.shutdown_hook()
2514 2015
2515 2016 def cleanup(self):
2516 2017 self.restore_sys_module_state()
2517 2018
2518 2019
2519 2020 class InteractiveShellABC(object):
2520 2021 """An abstract base class for InteractiveShell."""
2521 2022 __metaclass__ = abc.ABCMeta
2522 2023
2523 2024 InteractiveShellABC.register(InteractiveShell)
@@ -1,30 +1,30 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 This module is *completely* deprecated and should no longer be used for
5 5 any purpose. Currently, we have a few parts of the core that have
6 6 not been componentized and thus, still rely on this module. When everything
7 7 has been made into a component, this module will be sent to deathrow.
8 8 """
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (C) 2008-2009 The IPython Development Team
12 12 #
13 13 # Distributed under the terms of the BSD License. The full license is in
14 14 # the file COPYING, distributed as part of this software.
15 15 #-----------------------------------------------------------------------------
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Imports
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Classes and functions
23 23 #-----------------------------------------------------------------------------
24 24
25 25
26 26 def get():
27 27 """Get the global InteractiveShell instance."""
28 from IPython.core.interactiveshell import InteractiveShell
29 return InteractiveShell.instance()
28 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
29 return TerminalInteractiveShell.instance()
30 30
@@ -1,3708 +1,3651 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2009 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import os
23 23 import sys
24 24 import shutil
25 25 import re
26 26 import time
27 27 import textwrap
28 28 import types
29 29 from cStringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pformat
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 45 # 2.5 compatibility
46 46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48 48
49 49 import IPython
50 50 from IPython.core import debugger, oinspect
51 51 from IPython.core.error import TryNext
52 52 from IPython.core.error import UsageError
53 53 from IPython.core.fakemodule import FakeModule
54 54 from IPython.core.macro import Macro
55 55 from IPython.core.page import page
56 56 from IPython.core.prefilter import ESC_MAGIC
57 57 from IPython.lib.pylabtools import mpl_runner
58 58 from IPython.lib.inputhook import enable_gui
59 59 from IPython.external.Itpl import itpl, printpl
60 60 from IPython.testing import decorators as testdec
61 61 from IPython.utils.io import Term, file_read, nlprint
62 62 from IPython.utils.path import get_py_filename
63 63 from IPython.utils.process import arg_split, abbrev_cwd
64 64 from IPython.utils.terminal import set_term_title
65 65 from IPython.utils.text import LSString, SList, StringTypes
66 66 from IPython.utils.timing import clock, clock2
67 67 from IPython.utils.warn import warn, error
68 68 from IPython.utils.ipstruct import Struct
69 69 import IPython.utils.generics
70 70
71 71 #-----------------------------------------------------------------------------
72 72 # Utility functions
73 73 #-----------------------------------------------------------------------------
74 74
75 75 def on_off(tag):
76 76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 77 return ['OFF','ON'][tag]
78 78
79 79 class Bunch: pass
80 80
81 81 def compress_dhist(dh):
82 82 head, tail = dh[:-10], dh[-10:]
83 83
84 84 newhead = []
85 85 done = set()
86 86 for h in head:
87 87 if h in done:
88 88 continue
89 89 newhead.append(h)
90 90 done.add(h)
91 91
92 92 return newhead + tail
93 93
94 94
95 95 #***************************************************************************
96 96 # Main class implementing Magic functionality
97 97
98 98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 99 # on construction of the main InteractiveShell object. Something odd is going
100 100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 101 # eventually this needs to be clarified.
102 102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 103 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 104 # make Magic a configurable that InteractiveShell does not subclass.
105 105
106 106 class Magic:
107 107 """Magic functions for InteractiveShell.
108 108
109 109 Shell functions which can be reached as %function_name. All magic
110 110 functions should accept a string, which they can parse for their own
111 111 needs. This can make some functions easier to type, eg `%cd ../`
112 112 vs. `%cd("../")`
113 113
114 114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 115 at the command line, but it is is needed in the definition. """
116 116
117 117 # class globals
118 118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 119 'Automagic is ON, % prefix NOT needed for magic functions.']
120 120
121 121 #......................................................................
122 122 # some utility functions
123 123
124 124 def __init__(self,shell):
125 125
126 126 self.options_table = {}
127 127 if profile is None:
128 128 self.magic_prun = self.profile_missing_notice
129 129 self.shell = shell
130 130
131 131 # namespace for holding state we may need
132 132 self._magic_state = Bunch()
133 133
134 134 def profile_missing_notice(self, *args, **kwargs):
135 135 error("""\
136 136 The profile module could not be found. It has been removed from the standard
137 137 python packages because of its non-free license. To use profiling, install the
138 138 python-profiler package from non-free.""")
139 139
140 140 def default_option(self,fn,optstr):
141 141 """Make an entry in the options_table for fn, with value optstr"""
142 142
143 143 if fn not in self.lsmagic():
144 144 error("%s is not a magic function" % fn)
145 145 self.options_table[fn] = optstr
146 146
147 147 def lsmagic(self):
148 148 """Return a list of currently available magic functions.
149 149
150 150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 151 ['magic_ls','magic_cd',...]"""
152 152
153 153 # FIXME. This needs a cleanup, in the way the magics list is built.
154 154
155 155 # magics in class definition
156 156 class_magic = lambda fn: fn.startswith('magic_') and \
157 157 callable(Magic.__dict__[fn])
158 158 # in instance namespace (run-time user additions)
159 159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 160 callable(self.__dict__[fn])
161 161 # and bound magics by user (so they can access self):
162 162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 163 callable(self.__class__.__dict__[fn])
164 164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 165 filter(inst_magic,self.__dict__.keys()) + \
166 166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 167 out = []
168 168 for fn in set(magics):
169 169 out.append(fn.replace('magic_','',1))
170 170 out.sort()
171 171 return out
172 172
173 173 def extract_input_slices(self,slices,raw=False):
174 174 """Return as a string a set of input history slices.
175 175
176 176 Inputs:
177 177
178 178 - slices: the set of slices is given as a list of strings (like
179 179 ['1','4:8','9'], since this function is for use by magic functions
180 180 which get their arguments as strings.
181 181
182 182 Optional inputs:
183 183
184 184 - raw(False): by default, the processed input is used. If this is
185 185 true, the raw input history is used instead.
186 186
187 187 Note that slices can be called with two notations:
188 188
189 189 N:M -> standard python form, means including items N...(M-1).
190 190
191 191 N-M -> include items N..M (closed endpoint)."""
192 192
193 193 if raw:
194 194 hist = self.shell.input_hist_raw
195 195 else:
196 196 hist = self.shell.input_hist
197 197
198 198 cmds = []
199 199 for chunk in slices:
200 200 if ':' in chunk:
201 201 ini,fin = map(int,chunk.split(':'))
202 202 elif '-' in chunk:
203 203 ini,fin = map(int,chunk.split('-'))
204 204 fin += 1
205 205 else:
206 206 ini = int(chunk)
207 207 fin = ini+1
208 208 cmds.append(hist[ini:fin])
209 209 return cmds
210 210
211 211 def _ofind(self, oname, namespaces=None):
212 212 """Find an object in the available namespaces.
213 213
214 214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215 215
216 216 Has special code to detect magic functions.
217 217 """
218 218 oname = oname.strip()
219 219 alias_ns = None
220 220 if namespaces is None:
221 221 # Namespaces to search in:
222 222 # Put them in a list. The order is important so that we
223 223 # find things in the same order that Python finds them.
224 224 namespaces = [ ('Interactive', self.shell.user_ns),
225 225 ('IPython internal', self.shell.internal_ns),
226 226 ('Python builtin', __builtin__.__dict__),
227 227 ('Alias', self.shell.alias_manager.alias_table),
228 228 ]
229 229 alias_ns = self.shell.alias_manager.alias_table
230 230
231 231 # initialize results to 'null'
232 232 found = False; obj = None; ospace = None; ds = None;
233 233 ismagic = False; isalias = False; parent = None
234 234
235 235 # We need to special-case 'print', which as of python2.6 registers as a
236 236 # function but should only be treated as one if print_function was
237 237 # loaded with a future import. In this case, just bail.
238 238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 239 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 240 return {'found':found, 'obj':obj, 'namespace':ospace,
241 241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242 242
243 243 # Look for the given name by splitting it in parts. If the head is
244 244 # found, then we look for all the remaining parts as members, and only
245 245 # declare success if we can find them all.
246 246 oname_parts = oname.split('.')
247 247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 248 for nsname,ns in namespaces:
249 249 try:
250 250 obj = ns[oname_head]
251 251 except KeyError:
252 252 continue
253 253 else:
254 254 #print 'oname_rest:', oname_rest # dbg
255 255 for part in oname_rest:
256 256 try:
257 257 parent = obj
258 258 obj = getattr(obj,part)
259 259 except:
260 260 # Blanket except b/c some badly implemented objects
261 261 # allow __getattr__ to raise exceptions other than
262 262 # AttributeError, which then crashes IPython.
263 263 break
264 264 else:
265 265 # If we finish the for loop (no break), we got all members
266 266 found = True
267 267 ospace = nsname
268 268 if ns == alias_ns:
269 269 isalias = True
270 270 break # namespace loop
271 271
272 272 # Try to see if it's magic
273 273 if not found:
274 274 if oname.startswith(ESC_MAGIC):
275 275 oname = oname[1:]
276 276 obj = getattr(self,'magic_'+oname,None)
277 277 if obj is not None:
278 278 found = True
279 279 ospace = 'IPython internal'
280 280 ismagic = True
281 281
282 282 # Last try: special-case some literals like '', [], {}, etc:
283 283 if not found and oname_head in ["''",'""','[]','{}','()']:
284 284 obj = eval(oname_head)
285 285 found = True
286 286 ospace = 'Interactive'
287 287
288 288 return {'found':found, 'obj':obj, 'namespace':ospace,
289 289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290 290
291 291 def arg_err(self,func):
292 292 """Print docstring if incorrect arguments were passed"""
293 293 print 'Error in arguments:'
294 294 print oinspect.getdoc(func)
295 295
296 296 def format_latex(self,strng):
297 297 """Format a string for latex inclusion."""
298 298
299 299 # Characters that need to be escaped for latex:
300 300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 301 # Magic command names as headers:
302 302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 303 re.MULTILINE)
304 304 # Magic commands
305 305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 306 re.MULTILINE)
307 307 # Paragraph continue
308 308 par_re = re.compile(r'\\$',re.MULTILINE)
309 309
310 310 # The "\n" symbol
311 311 newline_re = re.compile(r'\\n')
312 312
313 313 # Now build the string for output:
314 314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 316 strng)
317 317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 318 strng = par_re.sub(r'\\\\',strng)
319 319 strng = escape_re.sub(r'\\\1',strng)
320 320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 321 return strng
322 322
323 323 def format_screen(self,strng):
324 324 """Format a string for screen printing.
325 325
326 326 This removes some latex-type format codes."""
327 327 # Paragraph continue
328 328 par_re = re.compile(r'\\$',re.MULTILINE)
329 329 strng = par_re.sub('',strng)
330 330 return strng
331 331
332 332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 333 """Parse options passed to an argument string.
334 334
335 335 The interface is similar to that of getopt(), but it returns back a
336 336 Struct with the options as keys and the stripped argument string still
337 337 as a string.
338 338
339 339 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 340 This allows us to easily expand variables, glob files, quote
341 341 arguments, etc.
342 342
343 343 Options:
344 344 -mode: default 'string'. If given as 'list', the argument string is
345 345 returned as a list (split on whitespace) instead of a string.
346 346
347 347 -list_all: put all option values in lists. Normally only options
348 348 appearing more than once are put in a list.
349 349
350 350 -posix (True): whether to split the input line in POSIX mode or not,
351 351 as per the conventions outlined in the shlex module from the
352 352 standard library."""
353 353
354 354 # inject default options at the beginning of the input line
355 355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357 357
358 358 mode = kw.get('mode','string')
359 359 if mode not in ['string','list']:
360 360 raise ValueError,'incorrect mode given: %s' % mode
361 361 # Get options
362 362 list_all = kw.get('list_all',0)
363 363 posix = kw.get('posix', os.name == 'posix')
364 364
365 365 # Check if we have more than one argument to warrant extra processing:
366 366 odict = {} # Dictionary with options
367 367 args = arg_str.split()
368 368 if len(args) >= 1:
369 369 # If the list of inputs only has 0 or 1 thing in it, there's no
370 370 # need to look for options
371 371 argv = arg_split(arg_str,posix)
372 372 # Do regular option processing
373 373 try:
374 374 opts,args = getopt(argv,opt_str,*long_opts)
375 375 except GetoptError,e:
376 376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 377 " ".join(long_opts)))
378 378 for o,a in opts:
379 379 if o.startswith('--'):
380 380 o = o[2:]
381 381 else:
382 382 o = o[1:]
383 383 try:
384 384 odict[o].append(a)
385 385 except AttributeError:
386 386 odict[o] = [odict[o],a]
387 387 except KeyError:
388 388 if list_all:
389 389 odict[o] = [a]
390 390 else:
391 391 odict[o] = a
392 392
393 393 # Prepare opts,args for return
394 394 opts = Struct(odict)
395 395 if mode == 'string':
396 396 args = ' '.join(args)
397 397
398 398 return opts,args
399 399
400 400 #......................................................................
401 401 # And now the actual magic functions
402 402
403 403 # Functions for IPython shell work (vars,funcs, config, etc)
404 404 def magic_lsmagic(self, parameter_s = ''):
405 405 """List currently available magic functions."""
406 406 mesc = ESC_MAGIC
407 407 print 'Available magic functions:\n'+mesc+\
408 408 (' '+mesc).join(self.lsmagic())
409 409 print '\n' + Magic.auto_status[self.shell.automagic]
410 410 return None
411 411
412 412 def magic_magic(self, parameter_s = ''):
413 413 """Print information about the magic function system.
414 414
415 415 Supported formats: -latex, -brief, -rest
416 416 """
417 417
418 418 mode = ''
419 419 try:
420 420 if parameter_s.split()[0] == '-latex':
421 421 mode = 'latex'
422 422 if parameter_s.split()[0] == '-brief':
423 423 mode = 'brief'
424 424 if parameter_s.split()[0] == '-rest':
425 425 mode = 'rest'
426 426 rest_docs = []
427 427 except:
428 428 pass
429 429
430 430 magic_docs = []
431 431 for fname in self.lsmagic():
432 432 mname = 'magic_' + fname
433 433 for space in (Magic,self,self.__class__):
434 434 try:
435 435 fn = space.__dict__[mname]
436 436 except KeyError:
437 437 pass
438 438 else:
439 439 break
440 440 if mode == 'brief':
441 441 # only first line
442 442 if fn.__doc__:
443 443 fndoc = fn.__doc__.split('\n',1)[0]
444 444 else:
445 445 fndoc = 'No documentation'
446 446 else:
447 447 if fn.__doc__:
448 448 fndoc = fn.__doc__.rstrip()
449 449 else:
450 450 fndoc = 'No documentation'
451 451
452 452
453 453 if mode == 'rest':
454 454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 455 fname,fndoc))
456 456
457 457 else:
458 458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 459 fname,fndoc))
460 460
461 461 magic_docs = ''.join(magic_docs)
462 462
463 463 if mode == 'rest':
464 464 return "".join(rest_docs)
465 465
466 466 if mode == 'latex':
467 467 print self.format_latex(magic_docs)
468 468 return
469 469 else:
470 470 magic_docs = self.format_screen(magic_docs)
471 471 if mode == 'brief':
472 472 return magic_docs
473 473
474 474 outmsg = """
475 475 IPython's 'magic' functions
476 476 ===========================
477 477
478 478 The magic function system provides a series of functions which allow you to
479 479 control the behavior of IPython itself, plus a lot of system-type
480 480 features. All these functions are prefixed with a % character, but parameters
481 481 are given without parentheses or quotes.
482 482
483 483 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 484 %automagic function), you don't need to type in the % explicitly. By default,
485 485 IPython ships with automagic on, so you should only rarely need the % escape.
486 486
487 487 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 488 to 'mydir', if it exists.
489 489
490 490 You can define your own magic functions to extend the system. See the supplied
491 491 ipythonrc and example-magic.py files for details (in your ipython
492 492 configuration directory, typically $HOME/.ipython/).
493 493
494 494 You can also define your own aliased names for magic functions. In your
495 495 ipythonrc file, placing a line like:
496 496
497 497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498 498
499 499 will define %pf as a new name for %profile.
500 500
501 501 You can also call magics in code using the magic() function, which IPython
502 502 automatically adds to the builtin namespace. Type 'magic?' for details.
503 503
504 504 For a list of the available magic functions, use %lsmagic. For a description
505 505 of any of them, type %magic_name?, e.g. '%cd?'.
506 506
507 507 Currently the magic system has the following functions:\n"""
508 508
509 509 mesc = ESC_MAGIC
510 510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 511 "\n\n%s%s\n\n%s" % (outmsg,
512 512 magic_docs,mesc,mesc,
513 513 (' '+mesc).join(self.lsmagic()),
514 514 Magic.auto_status[self.shell.automagic] ) )
515 515
516 516 page(outmsg,screen_lines=self.shell.usable_screen_length)
517 517
518 518
519 519 def magic_autoindent(self, parameter_s = ''):
520 520 """Toggle autoindent on/off (if available)."""
521 521
522 522 self.shell.set_autoindent()
523 523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524 524
525 525
526 526 def magic_automagic(self, parameter_s = ''):
527 527 """Make magic functions callable without having to type the initial %.
528 528
529 529 Without argumentsl toggles on/off (when off, you must call it as
530 530 %automagic, of course). With arguments it sets the value, and you can
531 531 use any of (case insensitive):
532 532
533 533 - on,1,True: to activate
534 534
535 535 - off,0,False: to deactivate.
536 536
537 537 Note that magic functions have lowest priority, so if there's a
538 538 variable whose name collides with that of a magic fn, automagic won't
539 539 work for that function (you get the variable instead). However, if you
540 540 delete the variable (del var), the previously shadowed magic function
541 541 becomes visible to automagic again."""
542 542
543 543 arg = parameter_s.lower()
544 544 if parameter_s in ('on','1','true'):
545 545 self.shell.automagic = True
546 546 elif parameter_s in ('off','0','false'):
547 547 self.shell.automagic = False
548 548 else:
549 549 self.shell.automagic = not self.shell.automagic
550 550 print '\n' + Magic.auto_status[self.shell.automagic]
551 551
552 552 @testdec.skip_doctest
553 553 def magic_autocall(self, parameter_s = ''):
554 554 """Make functions callable without having to type parentheses.
555 555
556 556 Usage:
557 557
558 558 %autocall [mode]
559 559
560 560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 561 value is toggled on and off (remembering the previous state).
562 562
563 563 In more detail, these values mean:
564 564
565 565 0 -> fully disabled
566 566
567 567 1 -> active, but do not apply if there are no arguments on the line.
568 568
569 569 In this mode, you get:
570 570
571 571 In [1]: callable
572 572 Out[1]: <built-in function callable>
573 573
574 574 In [2]: callable 'hello'
575 575 ------> callable('hello')
576 576 Out[2]: False
577 577
578 578 2 -> Active always. Even if no arguments are present, the callable
579 579 object is called:
580 580
581 581 In [2]: float
582 582 ------> float()
583 583 Out[2]: 0.0
584 584
585 585 Note that even with autocall off, you can still use '/' at the start of
586 586 a line to treat the first argument on the command line as a function
587 587 and add parentheses to it:
588 588
589 589 In [8]: /str 43
590 590 ------> str(43)
591 591 Out[8]: '43'
592 592
593 593 # all-random (note for auto-testing)
594 594 """
595 595
596 596 if parameter_s:
597 597 arg = int(parameter_s)
598 598 else:
599 599 arg = 'toggle'
600 600
601 601 if not arg in (0,1,2,'toggle'):
602 602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 603 return
604 604
605 605 if arg in (0,1,2):
606 606 self.shell.autocall = arg
607 607 else: # toggle
608 608 if self.shell.autocall:
609 609 self._magic_state.autocall_save = self.shell.autocall
610 610 self.shell.autocall = 0
611 611 else:
612 612 try:
613 613 self.shell.autocall = self._magic_state.autocall_save
614 614 except AttributeError:
615 615 self.shell.autocall = self._magic_state.autocall_save = 1
616 616
617 617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618 618
619 619 def magic_system_verbose(self, parameter_s = ''):
620 620 """Set verbose printing of system calls.
621 621
622 622 If called without an argument, act as a toggle"""
623 623
624 624 if parameter_s:
625 625 val = bool(eval(parameter_s))
626 626 else:
627 627 val = None
628 628
629 629 if self.shell.system_verbose:
630 630 self.shell.system_verbose = False
631 631 else:
632 632 self.shell.system_verbose = True
633 633 print "System verbose printing is:",\
634 634 ['OFF','ON'][self.shell.system_verbose]
635 635
636 636
637 637 def magic_page(self, parameter_s=''):
638 638 """Pretty print the object and display it through a pager.
639 639
640 640 %page [options] OBJECT
641 641
642 642 If no object is given, use _ (last output).
643 643
644 644 Options:
645 645
646 646 -r: page str(object), don't pretty-print it."""
647 647
648 648 # After a function contributed by Olivier Aubert, slightly modified.
649 649
650 650 # Process options/args
651 651 opts,args = self.parse_options(parameter_s,'r')
652 652 raw = 'r' in opts
653 653
654 654 oname = args and args or '_'
655 655 info = self._ofind(oname)
656 656 if info['found']:
657 657 txt = (raw and str or pformat)( info['obj'] )
658 658 page(txt)
659 659 else:
660 660 print 'Object `%s` not found' % oname
661 661
662 662 def magic_profile(self, parameter_s=''):
663 663 """Print your currently active IPython profile."""
664 664 if self.shell.profile:
665 665 printpl('Current IPython profile: $self.shell.profile.')
666 666 else:
667 667 print 'No profile active.'
668 668
669 669 def magic_pinfo(self, parameter_s='', namespaces=None):
670 670 """Provide detailed information about an object.
671 671
672 672 '%pinfo object' is just a synonym for object? or ?object."""
673 673
674 674 #print 'pinfo par: <%s>' % parameter_s # dbg
675 675
676 676
677 677 # detail_level: 0 -> obj? , 1 -> obj??
678 678 detail_level = 0
679 679 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 680 # happen if the user types 'pinfo foo?' at the cmd line.
681 681 pinfo,qmark1,oname,qmark2 = \
682 682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 683 if pinfo or qmark1 or qmark2:
684 684 detail_level = 1
685 685 if "*" in oname:
686 686 self.magic_psearch(oname)
687 687 else:
688 688 self._inspect('pinfo', oname, detail_level=detail_level,
689 689 namespaces=namespaces)
690 690
691 691 def magic_pdef(self, parameter_s='', namespaces=None):
692 692 """Print the definition header for any callable object.
693 693
694 694 If the object is a class, print the constructor information."""
695 695 self._inspect('pdef',parameter_s, namespaces)
696 696
697 697 def magic_pdoc(self, parameter_s='', namespaces=None):
698 698 """Print the docstring for an object.
699 699
700 700 If the given object is a class, it will print both the class and the
701 701 constructor docstrings."""
702 702 self._inspect('pdoc',parameter_s, namespaces)
703 703
704 704 def magic_psource(self, parameter_s='', namespaces=None):
705 705 """Print (or run through pager) the source code for an object."""
706 706 self._inspect('psource',parameter_s, namespaces)
707 707
708 708 def magic_pfile(self, parameter_s=''):
709 709 """Print (or run through pager) the file where an object is defined.
710 710
711 711 The file opens at the line where the object definition begins. IPython
712 712 will honor the environment variable PAGER if set, and otherwise will
713 713 do its best to print the file in a convenient form.
714 714
715 715 If the given argument is not an object currently defined, IPython will
716 716 try to interpret it as a filename (automatically adding a .py extension
717 717 if needed). You can thus use %pfile as a syntax highlighting code
718 718 viewer."""
719 719
720 720 # first interpret argument as an object name
721 721 out = self._inspect('pfile',parameter_s)
722 722 # if not, try the input as a filename
723 723 if out == 'not found':
724 724 try:
725 725 filename = get_py_filename(parameter_s)
726 726 except IOError,msg:
727 727 print msg
728 728 return
729 729 page(self.shell.inspector.format(file(filename).read()))
730 730
731 731 def _inspect(self,meth,oname,namespaces=None,**kw):
732 732 """Generic interface to the inspector system.
733 733
734 734 This function is meant to be called by pdef, pdoc & friends."""
735 735
736 736 #oname = oname.strip()
737 737 #print '1- oname: <%r>' % oname # dbg
738 738 try:
739 739 oname = oname.strip().encode('ascii')
740 740 #print '2- oname: <%r>' % oname # dbg
741 741 except UnicodeEncodeError:
742 742 print 'Python identifiers can only contain ascii characters.'
743 743 return 'not found'
744 744
745 745 info = Struct(self._ofind(oname, namespaces))
746 746
747 747 if info.found:
748 748 try:
749 749 IPython.utils.generics.inspect_object(info.obj)
750 750 return
751 751 except TryNext:
752 752 pass
753 753 # Get the docstring of the class property if it exists.
754 754 path = oname.split('.')
755 755 root = '.'.join(path[:-1])
756 756 if info.parent is not None:
757 757 try:
758 758 target = getattr(info.parent, '__class__')
759 759 # The object belongs to a class instance.
760 760 try:
761 761 target = getattr(target, path[-1])
762 762 # The class defines the object.
763 763 if isinstance(target, property):
764 764 oname = root + '.__class__.' + path[-1]
765 765 info = Struct(self._ofind(oname))
766 766 except AttributeError: pass
767 767 except AttributeError: pass
768 768
769 769 pmethod = getattr(self.shell.inspector,meth)
770 770 formatter = info.ismagic and self.format_screen or None
771 771 if meth == 'pdoc':
772 772 pmethod(info.obj,oname,formatter)
773 773 elif meth == 'pinfo':
774 774 pmethod(info.obj,oname,formatter,info,**kw)
775 775 else:
776 776 pmethod(info.obj,oname)
777 777 else:
778 778 print 'Object `%s` not found.' % oname
779 779 return 'not found' # so callers can take other action
780 780
781 781 def magic_psearch(self, parameter_s=''):
782 782 """Search for object in namespaces by wildcard.
783 783
784 784 %psearch [options] PATTERN [OBJECT TYPE]
785 785
786 786 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 788 rest of the command line must be unchanged (options come first), so
789 789 for example the following forms are equivalent
790 790
791 791 %psearch -i a* function
792 792 -i a* function?
793 793 ?-i a* function
794 794
795 795 Arguments:
796 796
797 797 PATTERN
798 798
799 799 where PATTERN is a string containing * as a wildcard similar to its
800 800 use in a shell. The pattern is matched in all namespaces on the
801 801 search path. By default objects starting with a single _ are not
802 802 matched, many IPython generated objects have a single
803 803 underscore. The default is case insensitive matching. Matching is
804 804 also done on the attributes of objects and not only on the objects
805 805 in a module.
806 806
807 807 [OBJECT TYPE]
808 808
809 809 Is the name of a python type from the types module. The name is
810 810 given in lowercase without the ending type, ex. StringType is
811 811 written string. By adding a type here only objects matching the
812 812 given type are matched. Using all here makes the pattern match all
813 813 types (this is the default).
814 814
815 815 Options:
816 816
817 817 -a: makes the pattern match even objects whose names start with a
818 818 single underscore. These names are normally ommitted from the
819 819 search.
820 820
821 821 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 822 these options is given, the default is read from your ipythonrc
823 823 file. The option name which sets this value is
824 824 'wildcards_case_sensitive'. If this option is not specified in your
825 825 ipythonrc file, IPython's internal default is to do a case sensitive
826 826 search.
827 827
828 828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 829 specifiy can be searched in any of the following namespaces:
830 830 'builtin', 'user', 'user_global','internal', 'alias', where
831 831 'builtin' and 'user' are the search defaults. Note that you should
832 832 not use quotes when specifying namespaces.
833 833
834 834 'Builtin' contains the python module builtin, 'user' contains all
835 835 user data, 'alias' only contain the shell aliases and no python
836 836 objects, 'internal' contains objects used by IPython. The
837 837 'user_global' namespace is only used by embedded IPython instances,
838 838 and it contains module-level globals. You can add namespaces to the
839 839 search with -s or exclude them with -e (these options can be given
840 840 more than once).
841 841
842 842 Examples:
843 843
844 844 %psearch a* -> objects beginning with an a
845 845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 846 %psearch a* function -> all functions beginning with an a
847 847 %psearch re.e* -> objects beginning with an e in module re
848 848 %psearch r*.e* -> objects that start with e in modules starting in r
849 849 %psearch r*.* string -> all strings in modules beginning with r
850 850
851 851 Case sensitve search:
852 852
853 853 %psearch -c a* list all object beginning with lower case a
854 854
855 855 Show objects beginning with a single _:
856 856
857 857 %psearch -a _* list objects beginning with a single underscore"""
858 858 try:
859 859 parameter_s = parameter_s.encode('ascii')
860 860 except UnicodeEncodeError:
861 861 print 'Python identifiers can only contain ascii characters.'
862 862 return
863 863
864 864 # default namespaces to be searched
865 865 def_search = ['user','builtin']
866 866
867 867 # Process options/args
868 868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 869 opt = opts.get
870 870 shell = self.shell
871 871 psearch = shell.inspector.psearch
872 872
873 873 # select case options
874 874 if opts.has_key('i'):
875 875 ignore_case = True
876 876 elif opts.has_key('c'):
877 877 ignore_case = False
878 878 else:
879 879 ignore_case = not shell.wildcards_case_sensitive
880 880
881 881 # Build list of namespaces to search from user options
882 882 def_search.extend(opt('s',[]))
883 883 ns_exclude = ns_exclude=opt('e',[])
884 884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885 885
886 886 # Call the actual search
887 887 try:
888 888 psearch(args,shell.ns_table,ns_search,
889 889 show_all=opt('a'),ignore_case=ignore_case)
890 890 except:
891 891 shell.showtraceback()
892 892
893 893 def magic_who_ls(self, parameter_s=''):
894 894 """Return a sorted list of all interactive variables.
895 895
896 896 If arguments are given, only variables of types matching these
897 897 arguments are returned."""
898 898
899 899 user_ns = self.shell.user_ns
900 900 internal_ns = self.shell.internal_ns
901 901 user_ns_hidden = self.shell.user_ns_hidden
902 902 out = [ i for i in user_ns
903 903 if not i.startswith('_') \
904 904 and not (i in internal_ns or i in user_ns_hidden) ]
905 905
906 906 typelist = parameter_s.split()
907 907 if typelist:
908 908 typeset = set(typelist)
909 909 out = [i for i in out if type(i).__name__ in typeset]
910 910
911 911 out.sort()
912 912 return out
913 913
914 914 def magic_who(self, parameter_s=''):
915 915 """Print all interactive variables, with some minimal formatting.
916 916
917 917 If any arguments are given, only variables whose type matches one of
918 918 these are printed. For example:
919 919
920 920 %who function str
921 921
922 922 will only list functions and strings, excluding all other types of
923 923 variables. To find the proper type names, simply use type(var) at a
924 924 command line to see how python prints type names. For example:
925 925
926 926 In [1]: type('hello')\\
927 927 Out[1]: <type 'str'>
928 928
929 929 indicates that the type name for strings is 'str'.
930 930
931 931 %who always excludes executed names loaded through your configuration
932 932 file and things which are internal to IPython.
933 933
934 934 This is deliberate, as typically you may load many modules and the
935 935 purpose of %who is to show you only what you've manually defined."""
936 936
937 937 varlist = self.magic_who_ls(parameter_s)
938 938 if not varlist:
939 939 if parameter_s:
940 940 print 'No variables match your requested type.'
941 941 else:
942 942 print 'Interactive namespace is empty.'
943 943 return
944 944
945 945 # if we have variables, move on...
946 946 count = 0
947 947 for i in varlist:
948 948 print i+'\t',
949 949 count += 1
950 950 if count > 8:
951 951 count = 0
952 952 print
953 953 print
954 954
955 955 def magic_whos(self, parameter_s=''):
956 956 """Like %who, but gives some extra information about each variable.
957 957
958 958 The same type filtering of %who can be applied here.
959 959
960 960 For all variables, the type is printed. Additionally it prints:
961 961
962 962 - For {},[],(): their length.
963 963
964 964 - For numpy and Numeric arrays, a summary with shape, number of
965 965 elements, typecode and size in memory.
966 966
967 967 - Everything else: a string representation, snipping their middle if
968 968 too long."""
969 969
970 970 varnames = self.magic_who_ls(parameter_s)
971 971 if not varnames:
972 972 if parameter_s:
973 973 print 'No variables match your requested type.'
974 974 else:
975 975 print 'Interactive namespace is empty.'
976 976 return
977 977
978 978 # if we have variables, move on...
979 979
980 980 # for these types, show len() instead of data:
981 981 seq_types = [types.DictType,types.ListType,types.TupleType]
982 982
983 983 # for numpy/Numeric arrays, display summary info
984 984 try:
985 985 import numpy
986 986 except ImportError:
987 987 ndarray_type = None
988 988 else:
989 989 ndarray_type = numpy.ndarray.__name__
990 990 try:
991 991 import Numeric
992 992 except ImportError:
993 993 array_type = None
994 994 else:
995 995 array_type = Numeric.ArrayType.__name__
996 996
997 997 # Find all variable names and types so we can figure out column sizes
998 998 def get_vars(i):
999 999 return self.shell.user_ns[i]
1000 1000
1001 1001 # some types are well known and can be shorter
1002 1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 1003 def type_name(v):
1004 1004 tn = type(v).__name__
1005 1005 return abbrevs.get(tn,tn)
1006 1006
1007 1007 varlist = map(get_vars,varnames)
1008 1008
1009 1009 typelist = []
1010 1010 for vv in varlist:
1011 1011 tt = type_name(vv)
1012 1012
1013 1013 if tt=='instance':
1014 1014 typelist.append( abbrevs.get(str(vv.__class__),
1015 1015 str(vv.__class__)))
1016 1016 else:
1017 1017 typelist.append(tt)
1018 1018
1019 1019 # column labels and # of spaces as separator
1020 1020 varlabel = 'Variable'
1021 1021 typelabel = 'Type'
1022 1022 datalabel = 'Data/Info'
1023 1023 colsep = 3
1024 1024 # variable format strings
1025 1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 1028 # find the size of the columns to format the output nicely
1029 1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 1031 # table header
1032 1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 1034 # and the table itself
1035 1035 kb = 1024
1036 1036 Mb = 1048576 # kb**2
1037 1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 1038 print itpl(vformat),
1039 1039 if vtype in seq_types:
1040 1040 print len(var)
1041 1041 elif vtype in [array_type,ndarray_type]:
1042 1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 1043 if vtype==ndarray_type:
1044 1044 # numpy
1045 1045 vsize = var.size
1046 1046 vbytes = vsize*var.itemsize
1047 1047 vdtype = var.dtype
1048 1048 else:
1049 1049 # Numeric
1050 1050 vsize = Numeric.size(var)
1051 1051 vbytes = vsize*var.itemsize()
1052 1052 vdtype = var.typecode()
1053 1053
1054 1054 if vbytes < 100000:
1055 1055 print aformat % (vshape,vsize,vdtype,vbytes)
1056 1056 else:
1057 1057 print aformat % (vshape,vsize,vdtype,vbytes),
1058 1058 if vbytes < Mb:
1059 1059 print '(%s kb)' % (vbytes/kb,)
1060 1060 else:
1061 1061 print '(%s Mb)' % (vbytes/Mb,)
1062 1062 else:
1063 1063 try:
1064 1064 vstr = str(var)
1065 1065 except UnicodeEncodeError:
1066 1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 1067 'backslashreplace')
1068 1068 vstr = vstr.replace('\n','\\n')
1069 1069 if len(vstr) < 50:
1070 1070 print vstr
1071 1071 else:
1072 1072 printpl(vfmt_short)
1073 1073
1074 1074 def magic_reset(self, parameter_s=''):
1075 1075 """Resets the namespace by removing all names defined by the user.
1076 1076
1077 1077 Input/Output history are left around in case you need them.
1078 1078
1079 1079 Parameters
1080 1080 ----------
1081 1081 -y : force reset without asking for confirmation.
1082 1082
1083 1083 Examples
1084 1084 --------
1085 1085 In [6]: a = 1
1086 1086
1087 1087 In [7]: a
1088 1088 Out[7]: 1
1089 1089
1090 1090 In [8]: 'a' in _ip.user_ns
1091 1091 Out[8]: True
1092 1092
1093 1093 In [9]: %reset -f
1094 1094
1095 1095 In [10]: 'a' in _ip.user_ns
1096 1096 Out[10]: False
1097 1097 """
1098 1098
1099 1099 if parameter_s == '-f':
1100 1100 ans = True
1101 1101 else:
1102 1102 ans = self.shell.ask_yes_no(
1103 1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 1104 if not ans:
1105 1105 print 'Nothing done.'
1106 1106 return
1107 1107 user_ns = self.shell.user_ns
1108 1108 for i in self.magic_who_ls():
1109 1109 del(user_ns[i])
1110 1110
1111 1111 # Also flush the private list of module references kept for script
1112 1112 # execution protection
1113 1113 self.shell.clear_main_mod_cache()
1114 1114
1115 1115 def magic_reset_selective(self, parameter_s=''):
1116 1116 """Resets the namespace by removing names defined by the user.
1117 1117
1118 1118 Input/Output history are left around in case you need them.
1119 1119
1120 1120 %reset_selective [-f] regex
1121 1121
1122 1122 No action is taken if regex is not included
1123 1123
1124 1124 Options
1125 1125 -f : force reset without asking for confirmation.
1126 1126
1127 1127 Examples
1128 1128 --------
1129 1129
1130 1130 We first fully reset the namespace so your output looks identical to
1131 1131 this example for pedagogical reasons; in practice you do not need a
1132 1132 full reset.
1133 1133
1134 1134 In [1]: %reset -f
1135 1135
1136 1136 Now, with a clean namespace we can make a few variables and use
1137 1137 %reset_selective to only delete names that match our regexp:
1138 1138
1139 1139 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1140 1140
1141 1141 In [3]: who_ls
1142 1142 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1143 1143
1144 1144 In [4]: %reset_selective -f b[2-3]m
1145 1145
1146 1146 In [5]: who_ls
1147 1147 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1148 1148
1149 1149 In [6]: %reset_selective -f d
1150 1150
1151 1151 In [7]: who_ls
1152 1152 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1153 1153
1154 1154 In [8]: %reset_selective -f c
1155 1155
1156 1156 In [9]: who_ls
1157 1157 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1158 1158
1159 1159 In [10]: %reset_selective -f b
1160 1160
1161 1161 In [11]: who_ls
1162 1162 Out[11]: ['a']
1163 1163 """
1164 1164
1165 1165 opts, regex = self.parse_options(parameter_s,'f')
1166 1166
1167 1167 if opts.has_key('f'):
1168 1168 ans = True
1169 1169 else:
1170 1170 ans = self.shell.ask_yes_no(
1171 1171 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1172 1172 if not ans:
1173 1173 print 'Nothing done.'
1174 1174 return
1175 1175 user_ns = self.shell.user_ns
1176 1176 if not regex:
1177 1177 print 'No regex pattern specified. Nothing done.'
1178 1178 return
1179 1179 else:
1180 1180 try:
1181 1181 m = re.compile(regex)
1182 1182 except TypeError:
1183 1183 raise TypeError('regex must be a string or compiled pattern')
1184 1184 for i in self.magic_who_ls():
1185 1185 if m.search(i):
1186 1186 del(user_ns[i])
1187 1187
1188 1188 def magic_logstart(self,parameter_s=''):
1189 1189 """Start logging anywhere in a session.
1190 1190
1191 1191 %logstart [-o|-r|-t] [log_name [log_mode]]
1192 1192
1193 1193 If no name is given, it defaults to a file named 'ipython_log.py' in your
1194 1194 current directory, in 'rotate' mode (see below).
1195 1195
1196 1196 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1197 1197 history up to that point and then continues logging.
1198 1198
1199 1199 %logstart takes a second optional parameter: logging mode. This can be one
1200 1200 of (note that the modes are given unquoted):\\
1201 1201 append: well, that says it.\\
1202 1202 backup: rename (if exists) to name~ and start name.\\
1203 1203 global: single logfile in your home dir, appended to.\\
1204 1204 over : overwrite existing log.\\
1205 1205 rotate: create rotating logs name.1~, name.2~, etc.
1206 1206
1207 1207 Options:
1208 1208
1209 1209 -o: log also IPython's output. In this mode, all commands which
1210 1210 generate an Out[NN] prompt are recorded to the logfile, right after
1211 1211 their corresponding input line. The output lines are always
1212 1212 prepended with a '#[Out]# ' marker, so that the log remains valid
1213 1213 Python code.
1214 1214
1215 1215 Since this marker is always the same, filtering only the output from
1216 1216 a log is very easy, using for example a simple awk call:
1217 1217
1218 1218 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1219 1219
1220 1220 -r: log 'raw' input. Normally, IPython's logs contain the processed
1221 1221 input, so that user lines are logged in their final form, converted
1222 1222 into valid Python. For example, %Exit is logged as
1223 1223 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1224 1224 exactly as typed, with no transformations applied.
1225 1225
1226 1226 -t: put timestamps before each input line logged (these are put in
1227 1227 comments)."""
1228 1228
1229 1229 opts,par = self.parse_options(parameter_s,'ort')
1230 1230 log_output = 'o' in opts
1231 1231 log_raw_input = 'r' in opts
1232 1232 timestamp = 't' in opts
1233 1233
1234 1234 logger = self.shell.logger
1235 1235
1236 1236 # if no args are given, the defaults set in the logger constructor by
1237 1237 # ipytohn remain valid
1238 1238 if par:
1239 1239 try:
1240 1240 logfname,logmode = par.split()
1241 1241 except:
1242 1242 logfname = par
1243 1243 logmode = 'backup'
1244 1244 else:
1245 1245 logfname = logger.logfname
1246 1246 logmode = logger.logmode
1247 1247 # put logfname into rc struct as if it had been called on the command
1248 1248 # line, so it ends up saved in the log header Save it in case we need
1249 1249 # to restore it...
1250 1250 old_logfile = self.shell.logfile
1251 1251 if logfname:
1252 1252 logfname = os.path.expanduser(logfname)
1253 1253 self.shell.logfile = logfname
1254 1254
1255 1255 loghead = '# IPython log file\n\n'
1256 1256 try:
1257 1257 started = logger.logstart(logfname,loghead,logmode,
1258 1258 log_output,timestamp,log_raw_input)
1259 1259 except:
1260 1260 self.shell.logfile = old_logfile
1261 1261 warn("Couldn't start log: %s" % sys.exc_info()[1])
1262 1262 else:
1263 1263 # log input history up to this point, optionally interleaving
1264 1264 # output if requested
1265 1265
1266 1266 if timestamp:
1267 1267 # disable timestamping for the previous history, since we've
1268 1268 # lost those already (no time machine here).
1269 1269 logger.timestamp = False
1270 1270
1271 1271 if log_raw_input:
1272 1272 input_hist = self.shell.input_hist_raw
1273 1273 else:
1274 1274 input_hist = self.shell.input_hist
1275 1275
1276 1276 if log_output:
1277 1277 log_write = logger.log_write
1278 1278 output_hist = self.shell.output_hist
1279 1279 for n in range(1,len(input_hist)-1):
1280 1280 log_write(input_hist[n].rstrip())
1281 1281 if n in output_hist:
1282 1282 log_write(repr(output_hist[n]),'output')
1283 1283 else:
1284 1284 logger.log_write(input_hist[1:])
1285 1285 if timestamp:
1286 1286 # re-enable timestamping
1287 1287 logger.timestamp = True
1288 1288
1289 1289 print ('Activating auto-logging. '
1290 1290 'Current session state plus future input saved.')
1291 1291 logger.logstate()
1292 1292
1293 1293 def magic_logstop(self,parameter_s=''):
1294 1294 """Fully stop logging and close log file.
1295 1295
1296 1296 In order to start logging again, a new %logstart call needs to be made,
1297 1297 possibly (though not necessarily) with a new filename, mode and other
1298 1298 options."""
1299 1299 self.logger.logstop()
1300 1300
1301 1301 def magic_logoff(self,parameter_s=''):
1302 1302 """Temporarily stop logging.
1303 1303
1304 1304 You must have previously started logging."""
1305 1305 self.shell.logger.switch_log(0)
1306 1306
1307 1307 def magic_logon(self,parameter_s=''):
1308 1308 """Restart logging.
1309 1309
1310 1310 This function is for restarting logging which you've temporarily
1311 1311 stopped with %logoff. For starting logging for the first time, you
1312 1312 must use the %logstart function, which allows you to specify an
1313 1313 optional log filename."""
1314 1314
1315 1315 self.shell.logger.switch_log(1)
1316 1316
1317 1317 def magic_logstate(self,parameter_s=''):
1318 1318 """Print the status of the logging system."""
1319 1319
1320 1320 self.shell.logger.logstate()
1321 1321
1322 1322 def magic_pdb(self, parameter_s=''):
1323 1323 """Control the automatic calling of the pdb interactive debugger.
1324 1324
1325 1325 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1326 1326 argument it works as a toggle.
1327 1327
1328 1328 When an exception is triggered, IPython can optionally call the
1329 1329 interactive pdb debugger after the traceback printout. %pdb toggles
1330 1330 this feature on and off.
1331 1331
1332 1332 The initial state of this feature is set in your ipythonrc
1333 1333 configuration file (the variable is called 'pdb').
1334 1334
1335 1335 If you want to just activate the debugger AFTER an exception has fired,
1336 1336 without having to type '%pdb on' and rerunning your code, you can use
1337 1337 the %debug magic."""
1338 1338
1339 1339 par = parameter_s.strip().lower()
1340 1340
1341 1341 if par:
1342 1342 try:
1343 1343 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1344 1344 except KeyError:
1345 1345 print ('Incorrect argument. Use on/1, off/0, '
1346 1346 'or nothing for a toggle.')
1347 1347 return
1348 1348 else:
1349 1349 # toggle
1350 1350 new_pdb = not self.shell.call_pdb
1351 1351
1352 1352 # set on the shell
1353 1353 self.shell.call_pdb = new_pdb
1354 1354 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1355 1355
1356 1356 def magic_debug(self, parameter_s=''):
1357 1357 """Activate the interactive debugger in post-mortem mode.
1358 1358
1359 1359 If an exception has just occurred, this lets you inspect its stack
1360 1360 frames interactively. Note that this will always work only on the last
1361 1361 traceback that occurred, so you must call this quickly after an
1362 1362 exception that you wish to inspect has fired, because if another one
1363 1363 occurs, it clobbers the previous one.
1364 1364
1365 1365 If you want IPython to automatically do this on every exception, see
1366 1366 the %pdb magic for more details.
1367 1367 """
1368 1368 self.shell.debugger(force=True)
1369 1369
1370 1370 @testdec.skip_doctest
1371 1371 def magic_prun(self, parameter_s ='',user_mode=1,
1372 1372 opts=None,arg_lst=None,prog_ns=None):
1373 1373
1374 1374 """Run a statement through the python code profiler.
1375 1375
1376 1376 Usage:
1377 1377 %prun [options] statement
1378 1378
1379 1379 The given statement (which doesn't require quote marks) is run via the
1380 1380 python profiler in a manner similar to the profile.run() function.
1381 1381 Namespaces are internally managed to work correctly; profile.run
1382 1382 cannot be used in IPython because it makes certain assumptions about
1383 1383 namespaces which do not hold under IPython.
1384 1384
1385 1385 Options:
1386 1386
1387 1387 -l <limit>: you can place restrictions on what or how much of the
1388 1388 profile gets printed. The limit value can be:
1389 1389
1390 1390 * A string: only information for function names containing this string
1391 1391 is printed.
1392 1392
1393 1393 * An integer: only these many lines are printed.
1394 1394
1395 1395 * A float (between 0 and 1): this fraction of the report is printed
1396 1396 (for example, use a limit of 0.4 to see the topmost 40% only).
1397 1397
1398 1398 You can combine several limits with repeated use of the option. For
1399 1399 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1400 1400 information about class constructors.
1401 1401
1402 1402 -r: return the pstats.Stats object generated by the profiling. This
1403 1403 object has all the information about the profile in it, and you can
1404 1404 later use it for further analysis or in other functions.
1405 1405
1406 1406 -s <key>: sort profile by given key. You can provide more than one key
1407 1407 by using the option several times: '-s key1 -s key2 -s key3...'. The
1408 1408 default sorting key is 'time'.
1409 1409
1410 1410 The following is copied verbatim from the profile documentation
1411 1411 referenced below:
1412 1412
1413 1413 When more than one key is provided, additional keys are used as
1414 1414 secondary criteria when the there is equality in all keys selected
1415 1415 before them.
1416 1416
1417 1417 Abbreviations can be used for any key names, as long as the
1418 1418 abbreviation is unambiguous. The following are the keys currently
1419 1419 defined:
1420 1420
1421 1421 Valid Arg Meaning
1422 1422 "calls" call count
1423 1423 "cumulative" cumulative time
1424 1424 "file" file name
1425 1425 "module" file name
1426 1426 "pcalls" primitive call count
1427 1427 "line" line number
1428 1428 "name" function name
1429 1429 "nfl" name/file/line
1430 1430 "stdname" standard name
1431 1431 "time" internal time
1432 1432
1433 1433 Note that all sorts on statistics are in descending order (placing
1434 1434 most time consuming items first), where as name, file, and line number
1435 1435 searches are in ascending order (i.e., alphabetical). The subtle
1436 1436 distinction between "nfl" and "stdname" is that the standard name is a
1437 1437 sort of the name as printed, which means that the embedded line
1438 1438 numbers get compared in an odd way. For example, lines 3, 20, and 40
1439 1439 would (if the file names were the same) appear in the string order
1440 1440 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1441 1441 line numbers. In fact, sort_stats("nfl") is the same as
1442 1442 sort_stats("name", "file", "line").
1443 1443
1444 1444 -T <filename>: save profile results as shown on screen to a text
1445 1445 file. The profile is still shown on screen.
1446 1446
1447 1447 -D <filename>: save (via dump_stats) profile statistics to given
1448 1448 filename. This data is in a format understod by the pstats module, and
1449 1449 is generated by a call to the dump_stats() method of profile
1450 1450 objects. The profile is still shown on screen.
1451 1451
1452 1452 If you want to run complete programs under the profiler's control, use
1453 1453 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1454 1454 contains profiler specific options as described here.
1455 1455
1456 1456 You can read the complete documentation for the profile module with::
1457 1457
1458 1458 In [1]: import profile; profile.help()
1459 1459 """
1460 1460
1461 1461 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1462 1462 # protect user quote marks
1463 1463 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1464 1464
1465 1465 if user_mode: # regular user call
1466 1466 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1467 1467 list_all=1)
1468 1468 namespace = self.shell.user_ns
1469 1469 else: # called to run a program by %run -p
1470 1470 try:
1471 1471 filename = get_py_filename(arg_lst[0])
1472 1472 except IOError,msg:
1473 1473 error(msg)
1474 1474 return
1475 1475
1476 1476 arg_str = 'execfile(filename,prog_ns)'
1477 1477 namespace = locals()
1478 1478
1479 1479 opts.merge(opts_def)
1480 1480
1481 1481 prof = profile.Profile()
1482 1482 try:
1483 1483 prof = prof.runctx(arg_str,namespace,namespace)
1484 1484 sys_exit = ''
1485 1485 except SystemExit:
1486 1486 sys_exit = """*** SystemExit exception caught in code being profiled."""
1487 1487
1488 1488 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1489 1489
1490 1490 lims = opts.l
1491 1491 if lims:
1492 1492 lims = [] # rebuild lims with ints/floats/strings
1493 1493 for lim in opts.l:
1494 1494 try:
1495 1495 lims.append(int(lim))
1496 1496 except ValueError:
1497 1497 try:
1498 1498 lims.append(float(lim))
1499 1499 except ValueError:
1500 1500 lims.append(lim)
1501 1501
1502 1502 # Trap output.
1503 1503 stdout_trap = StringIO()
1504 1504
1505 1505 if hasattr(stats,'stream'):
1506 1506 # In newer versions of python, the stats object has a 'stream'
1507 1507 # attribute to write into.
1508 1508 stats.stream = stdout_trap
1509 1509 stats.print_stats(*lims)
1510 1510 else:
1511 1511 # For older versions, we manually redirect stdout during printing
1512 1512 sys_stdout = sys.stdout
1513 1513 try:
1514 1514 sys.stdout = stdout_trap
1515 1515 stats.print_stats(*lims)
1516 1516 finally:
1517 1517 sys.stdout = sys_stdout
1518 1518
1519 1519 output = stdout_trap.getvalue()
1520 1520 output = output.rstrip()
1521 1521
1522 1522 page(output,screen_lines=self.shell.usable_screen_length)
1523 1523 print sys_exit,
1524 1524
1525 1525 dump_file = opts.D[0]
1526 1526 text_file = opts.T[0]
1527 1527 if dump_file:
1528 1528 prof.dump_stats(dump_file)
1529 1529 print '\n*** Profile stats marshalled to file',\
1530 1530 `dump_file`+'.',sys_exit
1531 1531 if text_file:
1532 1532 pfile = file(text_file,'w')
1533 1533 pfile.write(output)
1534 1534 pfile.close()
1535 1535 print '\n*** Profile printout saved to text file',\
1536 1536 `text_file`+'.',sys_exit
1537 1537
1538 1538 if opts.has_key('r'):
1539 1539 return stats
1540 1540 else:
1541 1541 return None
1542 1542
1543 1543 @testdec.skip_doctest
1544 1544 def magic_run(self, parameter_s ='',runner=None,
1545 1545 file_finder=get_py_filename):
1546 1546 """Run the named file inside IPython as a program.
1547 1547
1548 1548 Usage:\\
1549 1549 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1550 1550
1551 1551 Parameters after the filename are passed as command-line arguments to
1552 1552 the program (put in sys.argv). Then, control returns to IPython's
1553 1553 prompt.
1554 1554
1555 1555 This is similar to running at a system prompt:\\
1556 1556 $ python file args\\
1557 1557 but with the advantage of giving you IPython's tracebacks, and of
1558 1558 loading all variables into your interactive namespace for further use
1559 1559 (unless -p is used, see below).
1560 1560
1561 1561 The file is executed in a namespace initially consisting only of
1562 1562 __name__=='__main__' and sys.argv constructed as indicated. It thus
1563 1563 sees its environment as if it were being run as a stand-alone program
1564 1564 (except for sharing global objects such as previously imported
1565 1565 modules). But after execution, the IPython interactive namespace gets
1566 1566 updated with all variables defined in the program (except for __name__
1567 1567 and sys.argv). This allows for very convenient loading of code for
1568 1568 interactive work, while giving each program a 'clean sheet' to run in.
1569 1569
1570 1570 Options:
1571 1571
1572 1572 -n: __name__ is NOT set to '__main__', but to the running file's name
1573 1573 without extension (as python does under import). This allows running
1574 1574 scripts and reloading the definitions in them without calling code
1575 1575 protected by an ' if __name__ == "__main__" ' clause.
1576 1576
1577 1577 -i: run the file in IPython's namespace instead of an empty one. This
1578 1578 is useful if you are experimenting with code written in a text editor
1579 1579 which depends on variables defined interactively.
1580 1580
1581 1581 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1582 1582 being run. This is particularly useful if IPython is being used to
1583 1583 run unittests, which always exit with a sys.exit() call. In such
1584 1584 cases you are interested in the output of the test results, not in
1585 1585 seeing a traceback of the unittest module.
1586 1586
1587 1587 -t: print timing information at the end of the run. IPython will give
1588 1588 you an estimated CPU time consumption for your script, which under
1589 1589 Unix uses the resource module to avoid the wraparound problems of
1590 1590 time.clock(). Under Unix, an estimate of time spent on system tasks
1591 1591 is also given (for Windows platforms this is reported as 0.0).
1592 1592
1593 1593 If -t is given, an additional -N<N> option can be given, where <N>
1594 1594 must be an integer indicating how many times you want the script to
1595 1595 run. The final timing report will include total and per run results.
1596 1596
1597 1597 For example (testing the script uniq_stable.py):
1598 1598
1599 1599 In [1]: run -t uniq_stable
1600 1600
1601 1601 IPython CPU timings (estimated):\\
1602 1602 User : 0.19597 s.\\
1603 1603 System: 0.0 s.\\
1604 1604
1605 1605 In [2]: run -t -N5 uniq_stable
1606 1606
1607 1607 IPython CPU timings (estimated):\\
1608 1608 Total runs performed: 5\\
1609 1609 Times : Total Per run\\
1610 1610 User : 0.910862 s, 0.1821724 s.\\
1611 1611 System: 0.0 s, 0.0 s.
1612 1612
1613 1613 -d: run your program under the control of pdb, the Python debugger.
1614 1614 This allows you to execute your program step by step, watch variables,
1615 1615 etc. Internally, what IPython does is similar to calling:
1616 1616
1617 1617 pdb.run('execfile("YOURFILENAME")')
1618 1618
1619 1619 with a breakpoint set on line 1 of your file. You can change the line
1620 1620 number for this automatic breakpoint to be <N> by using the -bN option
1621 1621 (where N must be an integer). For example:
1622 1622
1623 1623 %run -d -b40 myscript
1624 1624
1625 1625 will set the first breakpoint at line 40 in myscript.py. Note that
1626 1626 the first breakpoint must be set on a line which actually does
1627 1627 something (not a comment or docstring) for it to stop execution.
1628 1628
1629 1629 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1630 1630 first enter 'c' (without qoutes) to start execution up to the first
1631 1631 breakpoint.
1632 1632
1633 1633 Entering 'help' gives information about the use of the debugger. You
1634 1634 can easily see pdb's full documentation with "import pdb;pdb.help()"
1635 1635 at a prompt.
1636 1636
1637 1637 -p: run program under the control of the Python profiler module (which
1638 1638 prints a detailed report of execution times, function calls, etc).
1639 1639
1640 1640 You can pass other options after -p which affect the behavior of the
1641 1641 profiler itself. See the docs for %prun for details.
1642 1642
1643 1643 In this mode, the program's variables do NOT propagate back to the
1644 1644 IPython interactive namespace (because they remain in the namespace
1645 1645 where the profiler executes them).
1646 1646
1647 1647 Internally this triggers a call to %prun, see its documentation for
1648 1648 details on the options available specifically for profiling.
1649 1649
1650 1650 There is one special usage for which the text above doesn't apply:
1651 1651 if the filename ends with .ipy, the file is run as ipython script,
1652 1652 just as if the commands were written on IPython prompt.
1653 1653 """
1654 1654
1655 1655 # get arguments and set sys.argv for program to be run.
1656 1656 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1657 1657 mode='list',list_all=1)
1658 1658
1659 1659 try:
1660 1660 filename = file_finder(arg_lst[0])
1661 1661 except IndexError:
1662 1662 warn('you must provide at least a filename.')
1663 1663 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1664 1664 return
1665 1665 except IOError,msg:
1666 1666 error(msg)
1667 1667 return
1668 1668
1669 1669 if filename.lower().endswith('.ipy'):
1670 1670 self.shell.safe_execfile_ipy(filename)
1671 1671 return
1672 1672
1673 1673 # Control the response to exit() calls made by the script being run
1674 1674 exit_ignore = opts.has_key('e')
1675 1675
1676 1676 # Make sure that the running script gets a proper sys.argv as if it
1677 1677 # were run from a system shell.
1678 1678 save_argv = sys.argv # save it for later restoring
1679 1679 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1680 1680
1681 1681 if opts.has_key('i'):
1682 1682 # Run in user's interactive namespace
1683 1683 prog_ns = self.shell.user_ns
1684 1684 __name__save = self.shell.user_ns['__name__']
1685 1685 prog_ns['__name__'] = '__main__'
1686 1686 main_mod = self.shell.new_main_mod(prog_ns)
1687 1687 else:
1688 1688 # Run in a fresh, empty namespace
1689 1689 if opts.has_key('n'):
1690 1690 name = os.path.splitext(os.path.basename(filename))[0]
1691 1691 else:
1692 1692 name = '__main__'
1693 1693
1694 1694 main_mod = self.shell.new_main_mod()
1695 1695 prog_ns = main_mod.__dict__
1696 1696 prog_ns['__name__'] = name
1697 1697
1698 1698 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1699 1699 # set the __file__ global in the script's namespace
1700 1700 prog_ns['__file__'] = filename
1701 1701
1702 1702 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1703 1703 # that, if we overwrite __main__, we replace it at the end
1704 1704 main_mod_name = prog_ns['__name__']
1705 1705
1706 1706 if main_mod_name == '__main__':
1707 1707 restore_main = sys.modules['__main__']
1708 1708 else:
1709 1709 restore_main = False
1710 1710
1711 1711 # This needs to be undone at the end to prevent holding references to
1712 1712 # every single object ever created.
1713 1713 sys.modules[main_mod_name] = main_mod
1714 1714
1715 1715 stats = None
1716 1716 try:
1717 1717 self.shell.savehist()
1718 1718
1719 1719 if opts.has_key('p'):
1720 1720 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1721 1721 else:
1722 1722 if opts.has_key('d'):
1723 1723 deb = debugger.Pdb(self.shell.colors)
1724 1724 # reset Breakpoint state, which is moronically kept
1725 1725 # in a class
1726 1726 bdb.Breakpoint.next = 1
1727 1727 bdb.Breakpoint.bplist = {}
1728 1728 bdb.Breakpoint.bpbynumber = [None]
1729 1729 # Set an initial breakpoint to stop execution
1730 1730 maxtries = 10
1731 1731 bp = int(opts.get('b',[1])[0])
1732 1732 checkline = deb.checkline(filename,bp)
1733 1733 if not checkline:
1734 1734 for bp in range(bp+1,bp+maxtries+1):
1735 1735 if deb.checkline(filename,bp):
1736 1736 break
1737 1737 else:
1738 1738 msg = ("\nI failed to find a valid line to set "
1739 1739 "a breakpoint\n"
1740 1740 "after trying up to line: %s.\n"
1741 1741 "Please set a valid breakpoint manually "
1742 1742 "with the -b option." % bp)
1743 1743 error(msg)
1744 1744 return
1745 1745 # if we find a good linenumber, set the breakpoint
1746 1746 deb.do_break('%s:%s' % (filename,bp))
1747 1747 # Start file run
1748 1748 print "NOTE: Enter 'c' at the",
1749 1749 print "%s prompt to start your script." % deb.prompt
1750 1750 try:
1751 1751 deb.run('execfile("%s")' % filename,prog_ns)
1752 1752
1753 1753 except:
1754 1754 etype, value, tb = sys.exc_info()
1755 1755 # Skip three frames in the traceback: the %run one,
1756 1756 # one inside bdb.py, and the command-line typed by the
1757 1757 # user (run by exec in pdb itself).
1758 1758 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1759 1759 else:
1760 1760 if runner is None:
1761 1761 runner = self.shell.safe_execfile
1762 1762 if opts.has_key('t'):
1763 1763 # timed execution
1764 1764 try:
1765 1765 nruns = int(opts['N'][0])
1766 1766 if nruns < 1:
1767 1767 error('Number of runs must be >=1')
1768 1768 return
1769 1769 except (KeyError):
1770 1770 nruns = 1
1771 1771 if nruns == 1:
1772 1772 t0 = clock2()
1773 1773 runner(filename,prog_ns,prog_ns,
1774 1774 exit_ignore=exit_ignore)
1775 1775 t1 = clock2()
1776 1776 t_usr = t1[0]-t0[0]
1777 1777 t_sys = t1[1]-t0[1]
1778 1778 print "\nIPython CPU timings (estimated):"
1779 1779 print " User : %10s s." % t_usr
1780 1780 print " System: %10s s." % t_sys
1781 1781 else:
1782 1782 runs = range(nruns)
1783 1783 t0 = clock2()
1784 1784 for nr in runs:
1785 1785 runner(filename,prog_ns,prog_ns,
1786 1786 exit_ignore=exit_ignore)
1787 1787 t1 = clock2()
1788 1788 t_usr = t1[0]-t0[0]
1789 1789 t_sys = t1[1]-t0[1]
1790 1790 print "\nIPython CPU timings (estimated):"
1791 1791 print "Total runs performed:",nruns
1792 1792 print " Times : %10s %10s" % ('Total','Per run')
1793 1793 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1794 1794 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1795 1795
1796 1796 else:
1797 1797 # regular execution
1798 1798 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1799 1799
1800 1800 if opts.has_key('i'):
1801 1801 self.shell.user_ns['__name__'] = __name__save
1802 1802 else:
1803 1803 # The shell MUST hold a reference to prog_ns so after %run
1804 1804 # exits, the python deletion mechanism doesn't zero it out
1805 1805 # (leaving dangling references).
1806 1806 self.shell.cache_main_mod(prog_ns,filename)
1807 1807 # update IPython interactive namespace
1808 1808
1809 1809 # Some forms of read errors on the file may mean the
1810 1810 # __name__ key was never set; using pop we don't have to
1811 1811 # worry about a possible KeyError.
1812 1812 prog_ns.pop('__name__', None)
1813 1813
1814 1814 self.shell.user_ns.update(prog_ns)
1815 1815 finally:
1816 1816 # It's a bit of a mystery why, but __builtins__ can change from
1817 1817 # being a module to becoming a dict missing some key data after
1818 1818 # %run. As best I can see, this is NOT something IPython is doing
1819 1819 # at all, and similar problems have been reported before:
1820 1820 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1821 1821 # Since this seems to be done by the interpreter itself, the best
1822 1822 # we can do is to at least restore __builtins__ for the user on
1823 1823 # exit.
1824 1824 self.shell.user_ns['__builtins__'] = __builtin__
1825 1825
1826 1826 # Ensure key global structures are restored
1827 1827 sys.argv = save_argv
1828 1828 if restore_main:
1829 1829 sys.modules['__main__'] = restore_main
1830 1830 else:
1831 1831 # Remove from sys.modules the reference to main_mod we'd
1832 1832 # added. Otherwise it will trap references to objects
1833 1833 # contained therein.
1834 1834 del sys.modules[main_mod_name]
1835 1835
1836 1836 self.shell.reloadhist()
1837 1837
1838 1838 return stats
1839 1839
1840 1840 @testdec.skip_doctest
1841 1841 def magic_timeit(self, parameter_s =''):
1842 1842 """Time execution of a Python statement or expression
1843 1843
1844 1844 Usage:\\
1845 1845 %timeit [-n<N> -r<R> [-t|-c]] statement
1846 1846
1847 1847 Time execution of a Python statement or expression using the timeit
1848 1848 module.
1849 1849
1850 1850 Options:
1851 1851 -n<N>: execute the given statement <N> times in a loop. If this value
1852 1852 is not given, a fitting value is chosen.
1853 1853
1854 1854 -r<R>: repeat the loop iteration <R> times and take the best result.
1855 1855 Default: 3
1856 1856
1857 1857 -t: use time.time to measure the time, which is the default on Unix.
1858 1858 This function measures wall time.
1859 1859
1860 1860 -c: use time.clock to measure the time, which is the default on
1861 1861 Windows and measures wall time. On Unix, resource.getrusage is used
1862 1862 instead and returns the CPU user time.
1863 1863
1864 1864 -p<P>: use a precision of <P> digits to display the timing result.
1865 1865 Default: 3
1866 1866
1867 1867
1868 1868 Examples:
1869 1869
1870 1870 In [1]: %timeit pass
1871 1871 10000000 loops, best of 3: 53.3 ns per loop
1872 1872
1873 1873 In [2]: u = None
1874 1874
1875 1875 In [3]: %timeit u is None
1876 1876 10000000 loops, best of 3: 184 ns per loop
1877 1877
1878 1878 In [4]: %timeit -r 4 u == None
1879 1879 1000000 loops, best of 4: 242 ns per loop
1880 1880
1881 1881 In [5]: import time
1882 1882
1883 1883 In [6]: %timeit -n1 time.sleep(2)
1884 1884 1 loops, best of 3: 2 s per loop
1885 1885
1886 1886
1887 1887 The times reported by %timeit will be slightly higher than those
1888 1888 reported by the timeit.py script when variables are accessed. This is
1889 1889 due to the fact that %timeit executes the statement in the namespace
1890 1890 of the shell, compared with timeit.py, which uses a single setup
1891 1891 statement to import function or create variables. Generally, the bias
1892 1892 does not matter as long as results from timeit.py are not mixed with
1893 1893 those from %timeit."""
1894 1894
1895 1895 import timeit
1896 1896 import math
1897 1897
1898 1898 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1899 1899 # certain terminals. Until we figure out a robust way of
1900 1900 # auto-detecting if the terminal can deal with it, use plain 'us' for
1901 1901 # microseconds. I am really NOT happy about disabling the proper
1902 1902 # 'micro' prefix, but crashing is worse... If anyone knows what the
1903 1903 # right solution for this is, I'm all ears...
1904 1904 #
1905 1905 # Note: using
1906 1906 #
1907 1907 # s = u'\xb5'
1908 1908 # s.encode(sys.getdefaultencoding())
1909 1909 #
1910 1910 # is not sufficient, as I've seen terminals where that fails but
1911 1911 # print s
1912 1912 #
1913 1913 # succeeds
1914 1914 #
1915 1915 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1916 1916
1917 1917 #units = [u"s", u"ms",u'\xb5',"ns"]
1918 1918 units = [u"s", u"ms",u'us',"ns"]
1919 1919
1920 1920 scaling = [1, 1e3, 1e6, 1e9]
1921 1921
1922 1922 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1923 1923 posix=False)
1924 1924 if stmt == "":
1925 1925 return
1926 1926 timefunc = timeit.default_timer
1927 1927 number = int(getattr(opts, "n", 0))
1928 1928 repeat = int(getattr(opts, "r", timeit.default_repeat))
1929 1929 precision = int(getattr(opts, "p", 3))
1930 1930 if hasattr(opts, "t"):
1931 1931 timefunc = time.time
1932 1932 if hasattr(opts, "c"):
1933 1933 timefunc = clock
1934 1934
1935 1935 timer = timeit.Timer(timer=timefunc)
1936 1936 # this code has tight coupling to the inner workings of timeit.Timer,
1937 1937 # but is there a better way to achieve that the code stmt has access
1938 1938 # to the shell namespace?
1939 1939
1940 1940 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1941 1941 'setup': "pass"}
1942 1942 # Track compilation time so it can be reported if too long
1943 1943 # Minimum time above which compilation time will be reported
1944 1944 tc_min = 0.1
1945 1945
1946 1946 t0 = clock()
1947 1947 code = compile(src, "<magic-timeit>", "exec")
1948 1948 tc = clock()-t0
1949 1949
1950 1950 ns = {}
1951 1951 exec code in self.shell.user_ns, ns
1952 1952 timer.inner = ns["inner"]
1953 1953
1954 1954 if number == 0:
1955 1955 # determine number so that 0.2 <= total time < 2.0
1956 1956 number = 1
1957 1957 for i in range(1, 10):
1958 1958 if timer.timeit(number) >= 0.2:
1959 1959 break
1960 1960 number *= 10
1961 1961
1962 1962 best = min(timer.repeat(repeat, number)) / number
1963 1963
1964 1964 if best > 0.0 and best < 1000.0:
1965 1965 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1966 1966 elif best >= 1000.0:
1967 1967 order = 0
1968 1968 else:
1969 1969 order = 3
1970 1970 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1971 1971 precision,
1972 1972 best * scaling[order],
1973 1973 units[order])
1974 1974 if tc > tc_min:
1975 1975 print "Compiler time: %.2f s" % tc
1976 1976
1977 1977 @testdec.skip_doctest
1978 1978 def magic_time(self,parameter_s = ''):
1979 1979 """Time execution of a Python statement or expression.
1980 1980
1981 1981 The CPU and wall clock times are printed, and the value of the
1982 1982 expression (if any) is returned. Note that under Win32, system time
1983 1983 is always reported as 0, since it can not be measured.
1984 1984
1985 1985 This function provides very basic timing functionality. In Python
1986 1986 2.3, the timeit module offers more control and sophistication, so this
1987 1987 could be rewritten to use it (patches welcome).
1988 1988
1989 1989 Some examples:
1990 1990
1991 1991 In [1]: time 2**128
1992 1992 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1993 1993 Wall time: 0.00
1994 1994 Out[1]: 340282366920938463463374607431768211456L
1995 1995
1996 1996 In [2]: n = 1000000
1997 1997
1998 1998 In [3]: time sum(range(n))
1999 1999 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2000 2000 Wall time: 1.37
2001 2001 Out[3]: 499999500000L
2002 2002
2003 2003 In [4]: time print 'hello world'
2004 2004 hello world
2005 2005 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2006 2006 Wall time: 0.00
2007 2007
2008 2008 Note that the time needed by Python to compile the given expression
2009 2009 will be reported if it is more than 0.1s. In this example, the
2010 2010 actual exponentiation is done by Python at compilation time, so while
2011 2011 the expression can take a noticeable amount of time to compute, that
2012 2012 time is purely due to the compilation:
2013 2013
2014 2014 In [5]: time 3**9999;
2015 2015 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2016 2016 Wall time: 0.00 s
2017 2017
2018 2018 In [6]: time 3**999999;
2019 2019 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2020 2020 Wall time: 0.00 s
2021 2021 Compiler : 0.78 s
2022 2022 """
2023 2023
2024 2024 # fail immediately if the given expression can't be compiled
2025 2025
2026 2026 expr = self.shell.prefilter(parameter_s,False)
2027 2027
2028 2028 # Minimum time above which compilation time will be reported
2029 2029 tc_min = 0.1
2030 2030
2031 2031 try:
2032 2032 mode = 'eval'
2033 2033 t0 = clock()
2034 2034 code = compile(expr,'<timed eval>',mode)
2035 2035 tc = clock()-t0
2036 2036 except SyntaxError:
2037 2037 mode = 'exec'
2038 2038 t0 = clock()
2039 2039 code = compile(expr,'<timed exec>',mode)
2040 2040 tc = clock()-t0
2041 2041 # skew measurement as little as possible
2042 2042 glob = self.shell.user_ns
2043 2043 clk = clock2
2044 2044 wtime = time.time
2045 2045 # time execution
2046 2046 wall_st = wtime()
2047 2047 if mode=='eval':
2048 2048 st = clk()
2049 2049 out = eval(code,glob)
2050 2050 end = clk()
2051 2051 else:
2052 2052 st = clk()
2053 2053 exec code in glob
2054 2054 end = clk()
2055 2055 out = None
2056 2056 wall_end = wtime()
2057 2057 # Compute actual times and report
2058 2058 wall_time = wall_end-wall_st
2059 2059 cpu_user = end[0]-st[0]
2060 2060 cpu_sys = end[1]-st[1]
2061 2061 cpu_tot = cpu_user+cpu_sys
2062 2062 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2063 2063 (cpu_user,cpu_sys,cpu_tot)
2064 2064 print "Wall time: %.2f s" % wall_time
2065 2065 if tc > tc_min:
2066 2066 print "Compiler : %.2f s" % tc
2067 2067 return out
2068 2068
2069 2069 @testdec.skip_doctest
2070 2070 def magic_macro(self,parameter_s = ''):
2071 2071 """Define a set of input lines as a macro for future re-execution.
2072 2072
2073 2073 Usage:\\
2074 2074 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2075 2075
2076 2076 Options:
2077 2077
2078 2078 -r: use 'raw' input. By default, the 'processed' history is used,
2079 2079 so that magics are loaded in their transformed version to valid
2080 2080 Python. If this option is given, the raw input as typed as the
2081 2081 command line is used instead.
2082 2082
2083 2083 This will define a global variable called `name` which is a string
2084 2084 made of joining the slices and lines you specify (n1,n2,... numbers
2085 2085 above) from your input history into a single string. This variable
2086 2086 acts like an automatic function which re-executes those lines as if
2087 2087 you had typed them. You just type 'name' at the prompt and the code
2088 2088 executes.
2089 2089
2090 2090 The notation for indicating number ranges is: n1-n2 means 'use line
2091 2091 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2092 2092 using the lines numbered 5,6 and 7.
2093 2093
2094 2094 Note: as a 'hidden' feature, you can also use traditional python slice
2095 2095 notation, where N:M means numbers N through M-1.
2096 2096
2097 2097 For example, if your history contains (%hist prints it):
2098 2098
2099 2099 44: x=1
2100 2100 45: y=3
2101 2101 46: z=x+y
2102 2102 47: print x
2103 2103 48: a=5
2104 2104 49: print 'x',x,'y',y
2105 2105
2106 2106 you can create a macro with lines 44 through 47 (included) and line 49
2107 2107 called my_macro with:
2108 2108
2109 2109 In [55]: %macro my_macro 44-47 49
2110 2110
2111 2111 Now, typing `my_macro` (without quotes) will re-execute all this code
2112 2112 in one pass.
2113 2113
2114 2114 You don't need to give the line-numbers in order, and any given line
2115 2115 number can appear multiple times. You can assemble macros with any
2116 2116 lines from your input history in any order.
2117 2117
2118 2118 The macro is a simple object which holds its value in an attribute,
2119 2119 but IPython's display system checks for macros and executes them as
2120 2120 code instead of printing them when you type their name.
2121 2121
2122 2122 You can view a macro's contents by explicitly printing it with:
2123 2123
2124 2124 'print macro_name'.
2125 2125
2126 2126 For one-off cases which DON'T contain magic function calls in them you
2127 2127 can obtain similar results by explicitly executing slices from your
2128 2128 input history with:
2129 2129
2130 2130 In [60]: exec In[44:48]+In[49]"""
2131 2131
2132 2132 opts,args = self.parse_options(parameter_s,'r',mode='list')
2133 2133 if not args:
2134 2134 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2135 2135 macs.sort()
2136 2136 return macs
2137 2137 if len(args) == 1:
2138 2138 raise UsageError(
2139 2139 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2140 2140 name,ranges = args[0], args[1:]
2141 2141
2142 2142 #print 'rng',ranges # dbg
2143 2143 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2144 2144 macro = Macro(lines)
2145 2145 self.shell.define_macro(name, macro)
2146 2146 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2147 2147 print 'Macro contents:'
2148 2148 print macro,
2149 2149
2150 2150 def magic_save(self,parameter_s = ''):
2151 2151 """Save a set of lines to a given filename.
2152 2152
2153 2153 Usage:\\
2154 2154 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2155 2155
2156 2156 Options:
2157 2157
2158 2158 -r: use 'raw' input. By default, the 'processed' history is used,
2159 2159 so that magics are loaded in their transformed version to valid
2160 2160 Python. If this option is given, the raw input as typed as the
2161 2161 command line is used instead.
2162 2162
2163 2163 This function uses the same syntax as %macro for line extraction, but
2164 2164 instead of creating a macro it saves the resulting string to the
2165 2165 filename you specify.
2166 2166
2167 2167 It adds a '.py' extension to the file if you don't do so yourself, and
2168 2168 it asks for confirmation before overwriting existing files."""
2169 2169
2170 2170 opts,args = self.parse_options(parameter_s,'r',mode='list')
2171 2171 fname,ranges = args[0], args[1:]
2172 2172 if not fname.endswith('.py'):
2173 2173 fname += '.py'
2174 2174 if os.path.isfile(fname):
2175 2175 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2176 2176 if ans.lower() not in ['y','yes']:
2177 2177 print 'Operation cancelled.'
2178 2178 return
2179 2179 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2180 2180 f = file(fname,'w')
2181 2181 f.write(cmds)
2182 2182 f.close()
2183 2183 print 'The following commands were written to file `%s`:' % fname
2184 2184 print cmds
2185 2185
2186 2186 def _edit_macro(self,mname,macro):
2187 2187 """open an editor with the macro data in a file"""
2188 2188 filename = self.shell.mktempfile(macro.value)
2189 2189 self.shell.hooks.editor(filename)
2190 2190
2191 2191 # and make a new macro object, to replace the old one
2192 2192 mfile = open(filename)
2193 2193 mvalue = mfile.read()
2194 2194 mfile.close()
2195 2195 self.shell.user_ns[mname] = Macro(mvalue)
2196 2196
2197 2197 def magic_ed(self,parameter_s=''):
2198 2198 """Alias to %edit."""
2199 2199 return self.magic_edit(parameter_s)
2200 2200
2201 2201 @testdec.skip_doctest
2202 2202 def magic_edit(self,parameter_s='',last_call=['','']):
2203 2203 """Bring up an editor and execute the resulting code.
2204 2204
2205 2205 Usage:
2206 2206 %edit [options] [args]
2207 2207
2208 2208 %edit runs IPython's editor hook. The default version of this hook is
2209 2209 set to call the __IPYTHON__.rc.editor command. This is read from your
2210 2210 environment variable $EDITOR. If this isn't found, it will default to
2211 2211 vi under Linux/Unix and to notepad under Windows. See the end of this
2212 2212 docstring for how to change the editor hook.
2213 2213
2214 2214 You can also set the value of this editor via the command line option
2215 2215 '-editor' or in your ipythonrc file. This is useful if you wish to use
2216 2216 specifically for IPython an editor different from your typical default
2217 2217 (and for Windows users who typically don't set environment variables).
2218 2218
2219 2219 This command allows you to conveniently edit multi-line code right in
2220 2220 your IPython session.
2221 2221
2222 2222 If called without arguments, %edit opens up an empty editor with a
2223 2223 temporary file and will execute the contents of this file when you
2224 2224 close it (don't forget to save it!).
2225 2225
2226 2226
2227 2227 Options:
2228 2228
2229 2229 -n <number>: open the editor at a specified line number. By default,
2230 2230 the IPython editor hook uses the unix syntax 'editor +N filename', but
2231 2231 you can configure this by providing your own modified hook if your
2232 2232 favorite editor supports line-number specifications with a different
2233 2233 syntax.
2234 2234
2235 2235 -p: this will call the editor with the same data as the previous time
2236 2236 it was used, regardless of how long ago (in your current session) it
2237 2237 was.
2238 2238
2239 2239 -r: use 'raw' input. This option only applies to input taken from the
2240 2240 user's history. By default, the 'processed' history is used, so that
2241 2241 magics are loaded in their transformed version to valid Python. If
2242 2242 this option is given, the raw input as typed as the command line is
2243 2243 used instead. When you exit the editor, it will be executed by
2244 2244 IPython's own processor.
2245 2245
2246 2246 -x: do not execute the edited code immediately upon exit. This is
2247 2247 mainly useful if you are editing programs which need to be called with
2248 2248 command line arguments, which you can then do using %run.
2249 2249
2250 2250
2251 2251 Arguments:
2252 2252
2253 2253 If arguments are given, the following possibilites exist:
2254 2254
2255 2255 - The arguments are numbers or pairs of colon-separated numbers (like
2256 2256 1 4:8 9). These are interpreted as lines of previous input to be
2257 2257 loaded into the editor. The syntax is the same of the %macro command.
2258 2258
2259 2259 - If the argument doesn't start with a number, it is evaluated as a
2260 2260 variable and its contents loaded into the editor. You can thus edit
2261 2261 any string which contains python code (including the result of
2262 2262 previous edits).
2263 2263
2264 2264 - If the argument is the name of an object (other than a string),
2265 2265 IPython will try to locate the file where it was defined and open the
2266 2266 editor at the point where it is defined. You can use `%edit function`
2267 2267 to load an editor exactly at the point where 'function' is defined,
2268 2268 edit it and have the file be executed automatically.
2269 2269
2270 2270 If the object is a macro (see %macro for details), this opens up your
2271 2271 specified editor with a temporary file containing the macro's data.
2272 2272 Upon exit, the macro is reloaded with the contents of the file.
2273 2273
2274 2274 Note: opening at an exact line is only supported under Unix, and some
2275 2275 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2276 2276 '+NUMBER' parameter necessary for this feature. Good editors like
2277 2277 (X)Emacs, vi, jed, pico and joe all do.
2278 2278
2279 2279 - If the argument is not found as a variable, IPython will look for a
2280 2280 file with that name (adding .py if necessary) and load it into the
2281 2281 editor. It will execute its contents with execfile() when you exit,
2282 2282 loading any code in the file into your interactive namespace.
2283 2283
2284 2284 After executing your code, %edit will return as output the code you
2285 2285 typed in the editor (except when it was an existing file). This way
2286 2286 you can reload the code in further invocations of %edit as a variable,
2287 2287 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2288 2288 the output.
2289 2289
2290 2290 Note that %edit is also available through the alias %ed.
2291 2291
2292 2292 This is an example of creating a simple function inside the editor and
2293 2293 then modifying it. First, start up the editor:
2294 2294
2295 2295 In [1]: ed
2296 2296 Editing... done. Executing edited code...
2297 2297 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2298 2298
2299 2299 We can then call the function foo():
2300 2300
2301 2301 In [2]: foo()
2302 2302 foo() was defined in an editing session
2303 2303
2304 2304 Now we edit foo. IPython automatically loads the editor with the
2305 2305 (temporary) file where foo() was previously defined:
2306 2306
2307 2307 In [3]: ed foo
2308 2308 Editing... done. Executing edited code...
2309 2309
2310 2310 And if we call foo() again we get the modified version:
2311 2311
2312 2312 In [4]: foo()
2313 2313 foo() has now been changed!
2314 2314
2315 2315 Here is an example of how to edit a code snippet successive
2316 2316 times. First we call the editor:
2317 2317
2318 2318 In [5]: ed
2319 2319 Editing... done. Executing edited code...
2320 2320 hello
2321 2321 Out[5]: "print 'hello'n"
2322 2322
2323 2323 Now we call it again with the previous output (stored in _):
2324 2324
2325 2325 In [6]: ed _
2326 2326 Editing... done. Executing edited code...
2327 2327 hello world
2328 2328 Out[6]: "print 'hello world'n"
2329 2329
2330 2330 Now we call it with the output #8 (stored in _8, also as Out[8]):
2331 2331
2332 2332 In [7]: ed _8
2333 2333 Editing... done. Executing edited code...
2334 2334 hello again
2335 2335 Out[7]: "print 'hello again'n"
2336 2336
2337 2337
2338 2338 Changing the default editor hook:
2339 2339
2340 2340 If you wish to write your own editor hook, you can put it in a
2341 2341 configuration file which you load at startup time. The default hook
2342 2342 is defined in the IPython.core.hooks module, and you can use that as a
2343 2343 starting example for further modifications. That file also has
2344 2344 general instructions on how to set a new hook for use once you've
2345 2345 defined it."""
2346 2346
2347 2347 # FIXME: This function has become a convoluted mess. It needs a
2348 2348 # ground-up rewrite with clean, simple logic.
2349 2349
2350 2350 def make_filename(arg):
2351 2351 "Make a filename from the given args"
2352 2352 try:
2353 2353 filename = get_py_filename(arg)
2354 2354 except IOError:
2355 2355 if args.endswith('.py'):
2356 2356 filename = arg
2357 2357 else:
2358 2358 filename = None
2359 2359 return filename
2360 2360
2361 2361 # custom exceptions
2362 2362 class DataIsObject(Exception): pass
2363 2363
2364 2364 opts,args = self.parse_options(parameter_s,'prxn:')
2365 2365 # Set a few locals from the options for convenience:
2366 2366 opts_p = opts.has_key('p')
2367 2367 opts_r = opts.has_key('r')
2368 2368
2369 2369 # Default line number value
2370 2370 lineno = opts.get('n',None)
2371 2371
2372 2372 if opts_p:
2373 2373 args = '_%s' % last_call[0]
2374 2374 if not self.shell.user_ns.has_key(args):
2375 2375 args = last_call[1]
2376 2376
2377 2377 # use last_call to remember the state of the previous call, but don't
2378 2378 # let it be clobbered by successive '-p' calls.
2379 2379 try:
2380 2380 last_call[0] = self.shell.outputcache.prompt_count
2381 2381 if not opts_p:
2382 2382 last_call[1] = parameter_s
2383 2383 except:
2384 2384 pass
2385 2385
2386 2386 # by default this is done with temp files, except when the given
2387 2387 # arg is a filename
2388 2388 use_temp = 1
2389 2389
2390 2390 if re.match(r'\d',args):
2391 2391 # Mode where user specifies ranges of lines, like in %macro.
2392 2392 # This means that you can't edit files whose names begin with
2393 2393 # numbers this way. Tough.
2394 2394 ranges = args.split()
2395 2395 data = ''.join(self.extract_input_slices(ranges,opts_r))
2396 2396 elif args.endswith('.py'):
2397 2397 filename = make_filename(args)
2398 2398 data = ''
2399 2399 use_temp = 0
2400 2400 elif args:
2401 2401 try:
2402 2402 # Load the parameter given as a variable. If not a string,
2403 2403 # process it as an object instead (below)
2404 2404
2405 2405 #print '*** args',args,'type',type(args) # dbg
2406 2406 data = eval(args,self.shell.user_ns)
2407 2407 if not type(data) in StringTypes:
2408 2408 raise DataIsObject
2409 2409
2410 2410 except (NameError,SyntaxError):
2411 2411 # given argument is not a variable, try as a filename
2412 2412 filename = make_filename(args)
2413 2413 if filename is None:
2414 2414 warn("Argument given (%s) can't be found as a variable "
2415 2415 "or as a filename." % args)
2416 2416 return
2417 2417
2418 2418 data = ''
2419 2419 use_temp = 0
2420 2420 except DataIsObject:
2421 2421
2422 2422 # macros have a special edit function
2423 2423 if isinstance(data,Macro):
2424 2424 self._edit_macro(args,data)
2425 2425 return
2426 2426
2427 2427 # For objects, try to edit the file where they are defined
2428 2428 try:
2429 2429 filename = inspect.getabsfile(data)
2430 2430 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2431 2431 # class created by %edit? Try to find source
2432 2432 # by looking for method definitions instead, the
2433 2433 # __module__ in those classes is FakeModule.
2434 2434 attrs = [getattr(data, aname) for aname in dir(data)]
2435 2435 for attr in attrs:
2436 2436 if not inspect.ismethod(attr):
2437 2437 continue
2438 2438 filename = inspect.getabsfile(attr)
2439 2439 if filename and 'fakemodule' not in filename.lower():
2440 2440 # change the attribute to be the edit target instead
2441 2441 data = attr
2442 2442 break
2443 2443
2444 2444 datafile = 1
2445 2445 except TypeError:
2446 2446 filename = make_filename(args)
2447 2447 datafile = 1
2448 2448 warn('Could not find file where `%s` is defined.\n'
2449 2449 'Opening a file named `%s`' % (args,filename))
2450 2450 # Now, make sure we can actually read the source (if it was in
2451 2451 # a temp file it's gone by now).
2452 2452 if datafile:
2453 2453 try:
2454 2454 if lineno is None:
2455 2455 lineno = inspect.getsourcelines(data)[1]
2456 2456 except IOError:
2457 2457 filename = make_filename(args)
2458 2458 if filename is None:
2459 2459 warn('The file `%s` where `%s` was defined cannot '
2460 2460 'be read.' % (filename,data))
2461 2461 return
2462 2462 use_temp = 0
2463 2463 else:
2464 2464 data = ''
2465 2465
2466 2466 if use_temp:
2467 2467 filename = self.shell.mktempfile(data)
2468 2468 print 'IPython will make a temporary file named:',filename
2469 2469
2470 2470 # do actual editing here
2471 2471 print 'Editing...',
2472 2472 sys.stdout.flush()
2473 2473 try:
2474 2474 # Quote filenames that may have spaces in them
2475 2475 if ' ' in filename:
2476 2476 filename = "%s" % filename
2477 2477 self.shell.hooks.editor(filename,lineno)
2478 2478 except TryNext:
2479 2479 warn('Could not open editor')
2480 2480 return
2481 2481
2482 2482 # XXX TODO: should this be generalized for all string vars?
2483 2483 # For now, this is special-cased to blocks created by cpaste
2484 2484 if args.strip() == 'pasted_block':
2485 2485 self.shell.user_ns['pasted_block'] = file_read(filename)
2486 2486
2487 2487 if opts.has_key('x'): # -x prevents actual execution
2488 2488 print
2489 2489 else:
2490 2490 print 'done. Executing edited code...'
2491 2491 if opts_r:
2492 2492 self.shell.runlines(file_read(filename))
2493 2493 else:
2494 2494 self.shell.safe_execfile(filename,self.shell.user_ns,
2495 2495 self.shell.user_ns)
2496 2496
2497 2497
2498 2498 if use_temp:
2499 2499 try:
2500 2500 return open(filename).read()
2501 2501 except IOError,msg:
2502 2502 if msg.filename == filename:
2503 2503 warn('File not found. Did you forget to save?')
2504 2504 return
2505 2505 else:
2506 2506 self.shell.showtraceback()
2507 2507
2508 2508 def magic_xmode(self,parameter_s = ''):
2509 2509 """Switch modes for the exception handlers.
2510 2510
2511 2511 Valid modes: Plain, Context and Verbose.
2512 2512
2513 2513 If called without arguments, acts as a toggle."""
2514 2514
2515 2515 def xmode_switch_err(name):
2516 2516 warn('Error changing %s exception modes.\n%s' %
2517 2517 (name,sys.exc_info()[1]))
2518 2518
2519 2519 shell = self.shell
2520 2520 new_mode = parameter_s.strip().capitalize()
2521 2521 try:
2522 2522 shell.InteractiveTB.set_mode(mode=new_mode)
2523 2523 print 'Exception reporting mode:',shell.InteractiveTB.mode
2524 2524 except:
2525 2525 xmode_switch_err('user')
2526 2526
2527 # threaded shells use a special handler in sys.excepthook
2528 if shell.isthreaded:
2529 try:
2530 shell.sys_excepthook.set_mode(mode=new_mode)
2531 except:
2532 xmode_switch_err('threaded')
2533
2534 2527 def magic_colors(self,parameter_s = ''):
2535 2528 """Switch color scheme for prompts, info system and exception handlers.
2536 2529
2537 2530 Currently implemented schemes: NoColor, Linux, LightBG.
2538 2531
2539 2532 Color scheme names are not case-sensitive."""
2540 2533
2541 2534 def color_switch_err(name):
2542 2535 warn('Error changing %s color schemes.\n%s' %
2543 2536 (name,sys.exc_info()[1]))
2544 2537
2545 2538
2546 2539 new_scheme = parameter_s.strip()
2547 2540 if not new_scheme:
2548 2541 raise UsageError(
2549 2542 "%colors: you must specify a color scheme. See '%colors?'")
2550 2543 return
2551 2544 # local shortcut
2552 2545 shell = self.shell
2553 2546
2554 2547 import IPython.utils.rlineimpl as readline
2555 2548
2556 2549 if not readline.have_readline and sys.platform == "win32":
2557 2550 msg = """\
2558 2551 Proper color support under MS Windows requires the pyreadline library.
2559 2552 You can find it at:
2560 2553 http://ipython.scipy.org/moin/PyReadline/Intro
2561 2554 Gary's readline needs the ctypes module, from:
2562 2555 http://starship.python.net/crew/theller/ctypes
2563 2556 (Note that ctypes is already part of Python versions 2.5 and newer).
2564 2557
2565 2558 Defaulting color scheme to 'NoColor'"""
2566 2559 new_scheme = 'NoColor'
2567 2560 warn(msg)
2568 2561
2569 2562 # readline option is 0
2570 2563 if not shell.has_readline:
2571 2564 new_scheme = 'NoColor'
2572 2565
2573 2566 # Set prompt colors
2574 2567 try:
2575 2568 shell.outputcache.set_colors(new_scheme)
2576 2569 except:
2577 2570 color_switch_err('prompt')
2578 2571 else:
2579 2572 shell.colors = \
2580 2573 shell.outputcache.color_table.active_scheme_name
2581 2574 # Set exception colors
2582 2575 try:
2583 2576 shell.InteractiveTB.set_colors(scheme = new_scheme)
2584 2577 shell.SyntaxTB.set_colors(scheme = new_scheme)
2585 2578 except:
2586 2579 color_switch_err('exception')
2587 2580
2588 # threaded shells use a verbose traceback in sys.excepthook
2589 if shell.isthreaded:
2590 try:
2591 shell.sys_excepthook.set_colors(scheme=new_scheme)
2592 except:
2593 color_switch_err('system exception handler')
2594
2595 2581 # Set info (for 'object?') colors
2596 2582 if shell.color_info:
2597 2583 try:
2598 2584 shell.inspector.set_active_scheme(new_scheme)
2599 2585 except:
2600 2586 color_switch_err('object inspector')
2601 2587 else:
2602 2588 shell.inspector.set_active_scheme('NoColor')
2603 2589
2604 2590 def magic_color_info(self,parameter_s = ''):
2605 2591 """Toggle color_info.
2606 2592
2607 2593 The color_info configuration parameter controls whether colors are
2608 2594 used for displaying object details (by things like %psource, %pfile or
2609 2595 the '?' system). This function toggles this value with each call.
2610 2596
2611 2597 Note that unless you have a fairly recent pager (less works better
2612 2598 than more) in your system, using colored object information displays
2613 2599 will not work properly. Test it and see."""
2614 2600
2615 2601 self.shell.color_info = not self.shell.color_info
2616 2602 self.magic_colors(self.shell.colors)
2617 2603 print 'Object introspection functions have now coloring:',
2618 2604 print ['OFF','ON'][int(self.shell.color_info)]
2619 2605
2620 2606 def magic_Pprint(self, parameter_s=''):
2621 2607 """Toggle pretty printing on/off."""
2622 2608
2623 2609 self.shell.pprint = 1 - self.shell.pprint
2624 2610 print 'Pretty printing has been turned', \
2625 2611 ['OFF','ON'][self.shell.pprint]
2626 2612
2627 2613 def magic_Exit(self, parameter_s=''):
2628 2614 """Exit IPython without confirmation."""
2629 2615
2630 2616 self.shell.ask_exit()
2631 2617
2632 2618 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2633 2619 magic_exit = magic_quit = magic_Quit = magic_Exit
2634 2620
2635 2621 #......................................................................
2636 2622 # Functions to implement unix shell-type things
2637 2623
2638 2624 @testdec.skip_doctest
2639 2625 def magic_alias(self, parameter_s = ''):
2640 2626 """Define an alias for a system command.
2641 2627
2642 2628 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2643 2629
2644 2630 Then, typing 'alias_name params' will execute the system command 'cmd
2645 2631 params' (from your underlying operating system).
2646 2632
2647 2633 Aliases have lower precedence than magic functions and Python normal
2648 2634 variables, so if 'foo' is both a Python variable and an alias, the
2649 2635 alias can not be executed until 'del foo' removes the Python variable.
2650 2636
2651 2637 You can use the %l specifier in an alias definition to represent the
2652 2638 whole line when the alias is called. For example:
2653 2639
2654 2640 In [2]: alias all echo "Input in brackets: <%l>"
2655 2641 In [3]: all hello world
2656 2642 Input in brackets: <hello world>
2657 2643
2658 2644 You can also define aliases with parameters using %s specifiers (one
2659 2645 per parameter):
2660 2646
2661 2647 In [1]: alias parts echo first %s second %s
2662 2648 In [2]: %parts A B
2663 2649 first A second B
2664 2650 In [3]: %parts A
2665 2651 Incorrect number of arguments: 2 expected.
2666 2652 parts is an alias to: 'echo first %s second %s'
2667 2653
2668 2654 Note that %l and %s are mutually exclusive. You can only use one or
2669 2655 the other in your aliases.
2670 2656
2671 2657 Aliases expand Python variables just like system calls using ! or !!
2672 2658 do: all expressions prefixed with '$' get expanded. For details of
2673 2659 the semantic rules, see PEP-215:
2674 2660 http://www.python.org/peps/pep-0215.html. This is the library used by
2675 2661 IPython for variable expansion. If you want to access a true shell
2676 2662 variable, an extra $ is necessary to prevent its expansion by IPython:
2677 2663
2678 2664 In [6]: alias show echo
2679 2665 In [7]: PATH='A Python string'
2680 2666 In [8]: show $PATH
2681 2667 A Python string
2682 2668 In [9]: show $$PATH
2683 2669 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2684 2670
2685 2671 You can use the alias facility to acess all of $PATH. See the %rehash
2686 2672 and %rehashx functions, which automatically create aliases for the
2687 2673 contents of your $PATH.
2688 2674
2689 2675 If called with no parameters, %alias prints the current alias table."""
2690 2676
2691 2677 par = parameter_s.strip()
2692 2678 if not par:
2693 2679 stored = self.db.get('stored_aliases', {} )
2694 2680 aliases = sorted(self.shell.alias_manager.aliases)
2695 2681 # for k, v in stored:
2696 2682 # atab.append(k, v[0])
2697 2683
2698 2684 print "Total number of aliases:", len(aliases)
2699 2685 return aliases
2700 2686
2701 2687 # Now try to define a new one
2702 2688 try:
2703 2689 alias,cmd = par.split(None, 1)
2704 2690 except:
2705 2691 print oinspect.getdoc(self.magic_alias)
2706 2692 else:
2707 2693 self.shell.alias_manager.soft_define_alias(alias, cmd)
2708 2694 # end magic_alias
2709 2695
2710 2696 def magic_unalias(self, parameter_s = ''):
2711 2697 """Remove an alias"""
2712 2698
2713 2699 aname = parameter_s.strip()
2714 2700 self.shell.alias_manager.undefine_alias(aname)
2715 2701 stored = self.db.get('stored_aliases', {} )
2716 2702 if aname in stored:
2717 2703 print "Removing %stored alias",aname
2718 2704 del stored[aname]
2719 2705 self.db['stored_aliases'] = stored
2720 2706
2721 2707
2722 2708 def magic_rehashx(self, parameter_s = ''):
2723 2709 """Update the alias table with all executable files in $PATH.
2724 2710
2725 2711 This version explicitly checks that every entry in $PATH is a file
2726 2712 with execute access (os.X_OK), so it is much slower than %rehash.
2727 2713
2728 2714 Under Windows, it checks executability as a match agains a
2729 2715 '|'-separated string of extensions, stored in the IPython config
2730 2716 variable win_exec_ext. This defaults to 'exe|com|bat'.
2731 2717
2732 2718 This function also resets the root module cache of module completer,
2733 2719 used on slow filesystems.
2734 2720 """
2735 2721 from IPython.core.alias import InvalidAliasError
2736 2722
2737 2723 # for the benefit of module completer in ipy_completers.py
2738 2724 del self.db['rootmodules']
2739 2725
2740 2726 path = [os.path.abspath(os.path.expanduser(p)) for p in
2741 2727 os.environ.get('PATH','').split(os.pathsep)]
2742 2728 path = filter(os.path.isdir,path)
2743 2729
2744 2730 syscmdlist = []
2745 2731 # Now define isexec in a cross platform manner.
2746 2732 if os.name == 'posix':
2747 2733 isexec = lambda fname:os.path.isfile(fname) and \
2748 2734 os.access(fname,os.X_OK)
2749 2735 else:
2750 2736 try:
2751 2737 winext = os.environ['pathext'].replace(';','|').replace('.','')
2752 2738 except KeyError:
2753 2739 winext = 'exe|com|bat|py'
2754 2740 if 'py' not in winext:
2755 2741 winext += '|py'
2756 2742 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2757 2743 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2758 2744 savedir = os.getcwd()
2759 2745
2760 2746 # Now walk the paths looking for executables to alias.
2761 2747 try:
2762 2748 # write the whole loop for posix/Windows so we don't have an if in
2763 2749 # the innermost part
2764 2750 if os.name == 'posix':
2765 2751 for pdir in path:
2766 2752 os.chdir(pdir)
2767 2753 for ff in os.listdir(pdir):
2768 2754 if isexec(ff):
2769 2755 try:
2770 2756 # Removes dots from the name since ipython
2771 2757 # will assume names with dots to be python.
2772 2758 self.shell.alias_manager.define_alias(
2773 2759 ff.replace('.',''), ff)
2774 2760 except InvalidAliasError:
2775 2761 pass
2776 2762 else:
2777 2763 syscmdlist.append(ff)
2778 2764 else:
2779 2765 no_alias = self.shell.alias_manager.no_alias
2780 2766 for pdir in path:
2781 2767 os.chdir(pdir)
2782 2768 for ff in os.listdir(pdir):
2783 2769 base, ext = os.path.splitext(ff)
2784 2770 if isexec(ff) and base.lower() not in no_alias:
2785 2771 if ext.lower() == '.exe':
2786 2772 ff = base
2787 2773 try:
2788 2774 # Removes dots from the name since ipython
2789 2775 # will assume names with dots to be python.
2790 2776 self.shell.alias_manager.define_alias(
2791 2777 base.lower().replace('.',''), ff)
2792 2778 except InvalidAliasError:
2793 2779 pass
2794 2780 syscmdlist.append(ff)
2795 2781 db = self.db
2796 2782 db['syscmdlist'] = syscmdlist
2797 2783 finally:
2798 2784 os.chdir(savedir)
2799 2785
2800 2786 def magic_pwd(self, parameter_s = ''):
2801 2787 """Return the current working directory path."""
2802 2788 return os.getcwd()
2803 2789
2804 2790 def magic_cd(self, parameter_s=''):
2805 2791 """Change the current working directory.
2806 2792
2807 2793 This command automatically maintains an internal list of directories
2808 2794 you visit during your IPython session, in the variable _dh. The
2809 2795 command %dhist shows this history nicely formatted. You can also
2810 2796 do 'cd -<tab>' to see directory history conveniently.
2811 2797
2812 2798 Usage:
2813 2799
2814 2800 cd 'dir': changes to directory 'dir'.
2815 2801
2816 2802 cd -: changes to the last visited directory.
2817 2803
2818 2804 cd -<n>: changes to the n-th directory in the directory history.
2819 2805
2820 2806 cd --foo: change to directory that matches 'foo' in history
2821 2807
2822 2808 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2823 2809 (note: cd <bookmark_name> is enough if there is no
2824 2810 directory <bookmark_name>, but a bookmark with the name exists.)
2825 2811 'cd -b <tab>' allows you to tab-complete bookmark names.
2826 2812
2827 2813 Options:
2828 2814
2829 2815 -q: quiet. Do not print the working directory after the cd command is
2830 2816 executed. By default IPython's cd command does print this directory,
2831 2817 since the default prompts do not display path information.
2832 2818
2833 2819 Note that !cd doesn't work for this purpose because the shell where
2834 2820 !command runs is immediately discarded after executing 'command'."""
2835 2821
2836 2822 parameter_s = parameter_s.strip()
2837 2823 #bkms = self.shell.persist.get("bookmarks",{})
2838 2824
2839 2825 oldcwd = os.getcwd()
2840 2826 numcd = re.match(r'(-)(\d+)$',parameter_s)
2841 2827 # jump in directory history by number
2842 2828 if numcd:
2843 2829 nn = int(numcd.group(2))
2844 2830 try:
2845 2831 ps = self.shell.user_ns['_dh'][nn]
2846 2832 except IndexError:
2847 2833 print 'The requested directory does not exist in history.'
2848 2834 return
2849 2835 else:
2850 2836 opts = {}
2851 2837 elif parameter_s.startswith('--'):
2852 2838 ps = None
2853 2839 fallback = None
2854 2840 pat = parameter_s[2:]
2855 2841 dh = self.shell.user_ns['_dh']
2856 2842 # first search only by basename (last component)
2857 2843 for ent in reversed(dh):
2858 2844 if pat in os.path.basename(ent) and os.path.isdir(ent):
2859 2845 ps = ent
2860 2846 break
2861 2847
2862 2848 if fallback is None and pat in ent and os.path.isdir(ent):
2863 2849 fallback = ent
2864 2850
2865 2851 # if we have no last part match, pick the first full path match
2866 2852 if ps is None:
2867 2853 ps = fallback
2868 2854
2869 2855 if ps is None:
2870 2856 print "No matching entry in directory history"
2871 2857 return
2872 2858 else:
2873 2859 opts = {}
2874 2860
2875 2861
2876 2862 else:
2877 2863 #turn all non-space-escaping backslashes to slashes,
2878 2864 # for c:\windows\directory\names\
2879 2865 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2880 2866 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2881 2867 # jump to previous
2882 2868 if ps == '-':
2883 2869 try:
2884 2870 ps = self.shell.user_ns['_dh'][-2]
2885 2871 except IndexError:
2886 2872 raise UsageError('%cd -: No previous directory to change to.')
2887 2873 # jump to bookmark if needed
2888 2874 else:
2889 2875 if not os.path.isdir(ps) or opts.has_key('b'):
2890 2876 bkms = self.db.get('bookmarks', {})
2891 2877
2892 2878 if bkms.has_key(ps):
2893 2879 target = bkms[ps]
2894 2880 print '(bookmark:%s) -> %s' % (ps,target)
2895 2881 ps = target
2896 2882 else:
2897 2883 if opts.has_key('b'):
2898 2884 raise UsageError("Bookmark '%s' not found. "
2899 2885 "Use '%%bookmark -l' to see your bookmarks." % ps)
2900 2886
2901 2887 # at this point ps should point to the target dir
2902 2888 if ps:
2903 2889 try:
2904 2890 os.chdir(os.path.expanduser(ps))
2905 2891 if self.shell.term_title:
2906 2892 set_term_title('IPython: ' + abbrev_cwd())
2907 2893 except OSError:
2908 2894 print sys.exc_info()[1]
2909 2895 else:
2910 2896 cwd = os.getcwd()
2911 2897 dhist = self.shell.user_ns['_dh']
2912 2898 if oldcwd != cwd:
2913 2899 dhist.append(cwd)
2914 2900 self.db['dhist'] = compress_dhist(dhist)[-100:]
2915 2901
2916 2902 else:
2917 2903 os.chdir(self.shell.home_dir)
2918 2904 if self.shell.term_title:
2919 2905 set_term_title('IPython: ' + '~')
2920 2906 cwd = os.getcwd()
2921 2907 dhist = self.shell.user_ns['_dh']
2922 2908
2923 2909 if oldcwd != cwd:
2924 2910 dhist.append(cwd)
2925 2911 self.db['dhist'] = compress_dhist(dhist)[-100:]
2926 2912 if not 'q' in opts and self.shell.user_ns['_dh']:
2927 2913 print self.shell.user_ns['_dh'][-1]
2928 2914
2929 2915
2930 2916 def magic_env(self, parameter_s=''):
2931 2917 """List environment variables."""
2932 2918
2933 2919 return os.environ.data
2934 2920
2935 2921 def magic_pushd(self, parameter_s=''):
2936 2922 """Place the current dir on stack and change directory.
2937 2923
2938 2924 Usage:\\
2939 2925 %pushd ['dirname']
2940 2926 """
2941 2927
2942 2928 dir_s = self.shell.dir_stack
2943 2929 tgt = os.path.expanduser(parameter_s)
2944 2930 cwd = os.getcwd().replace(self.home_dir,'~')
2945 2931 if tgt:
2946 2932 self.magic_cd(parameter_s)
2947 2933 dir_s.insert(0,cwd)
2948 2934 return self.magic_dirs()
2949 2935
2950 2936 def magic_popd(self, parameter_s=''):
2951 2937 """Change to directory popped off the top of the stack.
2952 2938 """
2953 2939 if not self.shell.dir_stack:
2954 2940 raise UsageError("%popd on empty stack")
2955 2941 top = self.shell.dir_stack.pop(0)
2956 2942 self.magic_cd(top)
2957 2943 print "popd ->",top
2958 2944
2959 2945 def magic_dirs(self, parameter_s=''):
2960 2946 """Return the current directory stack."""
2961 2947
2962 2948 return self.shell.dir_stack
2963 2949
2964 2950 def magic_dhist(self, parameter_s=''):
2965 2951 """Print your history of visited directories.
2966 2952
2967 2953 %dhist -> print full history\\
2968 2954 %dhist n -> print last n entries only\\
2969 2955 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2970 2956
2971 2957 This history is automatically maintained by the %cd command, and
2972 2958 always available as the global list variable _dh. You can use %cd -<n>
2973 2959 to go to directory number <n>.
2974 2960
2975 2961 Note that most of time, you should view directory history by entering
2976 2962 cd -<TAB>.
2977 2963
2978 2964 """
2979 2965
2980 2966 dh = self.shell.user_ns['_dh']
2981 2967 if parameter_s:
2982 2968 try:
2983 2969 args = map(int,parameter_s.split())
2984 2970 except:
2985 2971 self.arg_err(Magic.magic_dhist)
2986 2972 return
2987 2973 if len(args) == 1:
2988 2974 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2989 2975 elif len(args) == 2:
2990 2976 ini,fin = args
2991 2977 else:
2992 2978 self.arg_err(Magic.magic_dhist)
2993 2979 return
2994 2980 else:
2995 2981 ini,fin = 0,len(dh)
2996 2982 nlprint(dh,
2997 2983 header = 'Directory history (kept in _dh)',
2998 2984 start=ini,stop=fin)
2999 2985
3000 2986 @testdec.skip_doctest
3001 2987 def magic_sc(self, parameter_s=''):
3002 2988 """Shell capture - execute a shell command and capture its output.
3003 2989
3004 2990 DEPRECATED. Suboptimal, retained for backwards compatibility.
3005 2991
3006 2992 You should use the form 'var = !command' instead. Example:
3007 2993
3008 2994 "%sc -l myfiles = ls ~" should now be written as
3009 2995
3010 2996 "myfiles = !ls ~"
3011 2997
3012 2998 myfiles.s, myfiles.l and myfiles.n still apply as documented
3013 2999 below.
3014 3000
3015 3001 --
3016 3002 %sc [options] varname=command
3017 3003
3018 3004 IPython will run the given command using commands.getoutput(), and
3019 3005 will then update the user's interactive namespace with a variable
3020 3006 called varname, containing the value of the call. Your command can
3021 3007 contain shell wildcards, pipes, etc.
3022 3008
3023 3009 The '=' sign in the syntax is mandatory, and the variable name you
3024 3010 supply must follow Python's standard conventions for valid names.
3025 3011
3026 3012 (A special format without variable name exists for internal use)
3027 3013
3028 3014 Options:
3029 3015
3030 3016 -l: list output. Split the output on newlines into a list before
3031 3017 assigning it to the given variable. By default the output is stored
3032 3018 as a single string.
3033 3019
3034 3020 -v: verbose. Print the contents of the variable.
3035 3021
3036 3022 In most cases you should not need to split as a list, because the
3037 3023 returned value is a special type of string which can automatically
3038 3024 provide its contents either as a list (split on newlines) or as a
3039 3025 space-separated string. These are convenient, respectively, either
3040 3026 for sequential processing or to be passed to a shell command.
3041 3027
3042 3028 For example:
3043 3029
3044 3030 # all-random
3045 3031
3046 3032 # Capture into variable a
3047 3033 In [1]: sc a=ls *py
3048 3034
3049 3035 # a is a string with embedded newlines
3050 3036 In [2]: a
3051 3037 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3052 3038
3053 3039 # which can be seen as a list:
3054 3040 In [3]: a.l
3055 3041 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3056 3042
3057 3043 # or as a whitespace-separated string:
3058 3044 In [4]: a.s
3059 3045 Out[4]: 'setup.py win32_manual_post_install.py'
3060 3046
3061 3047 # a.s is useful to pass as a single command line:
3062 3048 In [5]: !wc -l $a.s
3063 3049 146 setup.py
3064 3050 130 win32_manual_post_install.py
3065 3051 276 total
3066 3052
3067 3053 # while the list form is useful to loop over:
3068 3054 In [6]: for f in a.l:
3069 3055 ...: !wc -l $f
3070 3056 ...:
3071 3057 146 setup.py
3072 3058 130 win32_manual_post_install.py
3073 3059
3074 3060 Similiarly, the lists returned by the -l option are also special, in
3075 3061 the sense that you can equally invoke the .s attribute on them to
3076 3062 automatically get a whitespace-separated string from their contents:
3077 3063
3078 3064 In [7]: sc -l b=ls *py
3079 3065
3080 3066 In [8]: b
3081 3067 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3082 3068
3083 3069 In [9]: b.s
3084 3070 Out[9]: 'setup.py win32_manual_post_install.py'
3085 3071
3086 3072 In summary, both the lists and strings used for ouptut capture have
3087 3073 the following special attributes:
3088 3074
3089 3075 .l (or .list) : value as list.
3090 3076 .n (or .nlstr): value as newline-separated string.
3091 3077 .s (or .spstr): value as space-separated string.
3092 3078 """
3093 3079
3094 3080 opts,args = self.parse_options(parameter_s,'lv')
3095 3081 # Try to get a variable name and command to run
3096 3082 try:
3097 3083 # the variable name must be obtained from the parse_options
3098 3084 # output, which uses shlex.split to strip options out.
3099 3085 var,_ = args.split('=',1)
3100 3086 var = var.strip()
3101 3087 # But the the command has to be extracted from the original input
3102 3088 # parameter_s, not on what parse_options returns, to avoid the
3103 3089 # quote stripping which shlex.split performs on it.
3104 3090 _,cmd = parameter_s.split('=',1)
3105 3091 except ValueError:
3106 3092 var,cmd = '',''
3107 3093 # If all looks ok, proceed
3108 3094 out,err = self.shell.getoutputerror(cmd)
3109 3095 if err:
3110 3096 print >> Term.cerr,err
3111 3097 if opts.has_key('l'):
3112 3098 out = SList(out.split('\n'))
3113 3099 else:
3114 3100 out = LSString(out)
3115 3101 if opts.has_key('v'):
3116 3102 print '%s ==\n%s' % (var,pformat(out))
3117 3103 if var:
3118 3104 self.shell.user_ns.update({var:out})
3119 3105 else:
3120 3106 return out
3121 3107
3122 3108 def magic_sx(self, parameter_s=''):
3123 3109 """Shell execute - run a shell command and capture its output.
3124 3110
3125 3111 %sx command
3126 3112
3127 3113 IPython will run the given command using commands.getoutput(), and
3128 3114 return the result formatted as a list (split on '\\n'). Since the
3129 3115 output is _returned_, it will be stored in ipython's regular output
3130 3116 cache Out[N] and in the '_N' automatic variables.
3131 3117
3132 3118 Notes:
3133 3119
3134 3120 1) If an input line begins with '!!', then %sx is automatically
3135 3121 invoked. That is, while:
3136 3122 !ls
3137 3123 causes ipython to simply issue system('ls'), typing
3138 3124 !!ls
3139 3125 is a shorthand equivalent to:
3140 3126 %sx ls
3141 3127
3142 3128 2) %sx differs from %sc in that %sx automatically splits into a list,
3143 3129 like '%sc -l'. The reason for this is to make it as easy as possible
3144 3130 to process line-oriented shell output via further python commands.
3145 3131 %sc is meant to provide much finer control, but requires more
3146 3132 typing.
3147 3133
3148 3134 3) Just like %sc -l, this is a list with special attributes:
3149 3135
3150 3136 .l (or .list) : value as list.
3151 3137 .n (or .nlstr): value as newline-separated string.
3152 3138 .s (or .spstr): value as whitespace-separated string.
3153 3139
3154 3140 This is very useful when trying to use such lists as arguments to
3155 3141 system commands."""
3156 3142
3157 3143 if parameter_s:
3158 3144 out,err = self.shell.getoutputerror(parameter_s)
3159 3145 if err:
3160 3146 print >> Term.cerr,err
3161 3147 return SList(out.split('\n'))
3162 3148
3163 def magic_bg(self, parameter_s=''):
3164 """Run a job in the background, in a separate thread.
3165
3166 For example,
3167
3168 %bg myfunc(x,y,z=1)
3169
3170 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3171 execution starts, a message will be printed indicating the job
3172 number. If your job number is 5, you can use
3173
3174 myvar = jobs.result(5) or myvar = jobs[5].result
3175
3176 to assign this result to variable 'myvar'.
3177
3178 IPython has a job manager, accessible via the 'jobs' object. You can
3179 type jobs? to get more information about it, and use jobs.<TAB> to see
3180 its attributes. All attributes not starting with an underscore are
3181 meant for public use.
3182
3183 In particular, look at the jobs.new() method, which is used to create
3184 new jobs. This magic %bg function is just a convenience wrapper
3185 around jobs.new(), for expression-based jobs. If you want to create a
3186 new job with an explicit function object and arguments, you must call
3187 jobs.new() directly.
3188
3189 The jobs.new docstring also describes in detail several important
3190 caveats associated with a thread-based model for background job
3191 execution. Type jobs.new? for details.
3192
3193 You can check the status of all jobs with jobs.status().
3194
3195 The jobs variable is set by IPython into the Python builtin namespace.
3196 If you ever declare a variable named 'jobs', you will shadow this
3197 name. You can either delete your global jobs variable to regain
3198 access to the job manager, or make a new name and assign it manually
3199 to the manager (stored in IPython's namespace). For example, to
3200 assign the job manager to the Jobs name, use:
3201
3202 Jobs = __builtins__.jobs"""
3203
3204 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3205
3206 3149 def magic_r(self, parameter_s=''):
3207 3150 """Repeat previous input.
3208 3151
3209 3152 Note: Consider using the more powerfull %rep instead!
3210 3153
3211 3154 If given an argument, repeats the previous command which starts with
3212 3155 the same string, otherwise it just repeats the previous input.
3213 3156
3214 3157 Shell escaped commands (with ! as first character) are not recognized
3215 3158 by this system, only pure python code and magic commands.
3216 3159 """
3217 3160
3218 3161 start = parameter_s.strip()
3219 3162 esc_magic = ESC_MAGIC
3220 3163 # Identify magic commands even if automagic is on (which means
3221 3164 # the in-memory version is different from that typed by the user).
3222 3165 if self.shell.automagic:
3223 3166 start_magic = esc_magic+start
3224 3167 else:
3225 3168 start_magic = start
3226 3169 # Look through the input history in reverse
3227 3170 for n in range(len(self.shell.input_hist)-2,0,-1):
3228 3171 input = self.shell.input_hist[n]
3229 3172 # skip plain 'r' lines so we don't recurse to infinity
3230 3173 if input != '_ip.magic("r")\n' and \
3231 3174 (input.startswith(start) or input.startswith(start_magic)):
3232 3175 #print 'match',`input` # dbg
3233 3176 print 'Executing:',input,
3234 3177 self.shell.runlines(input)
3235 3178 return
3236 3179 print 'No previous input matching `%s` found.' % start
3237 3180
3238 3181
3239 3182 def magic_bookmark(self, parameter_s=''):
3240 3183 """Manage IPython's bookmark system.
3241 3184
3242 3185 %bookmark <name> - set bookmark to current dir
3243 3186 %bookmark <name> <dir> - set bookmark to <dir>
3244 3187 %bookmark -l - list all bookmarks
3245 3188 %bookmark -d <name> - remove bookmark
3246 3189 %bookmark -r - remove all bookmarks
3247 3190
3248 3191 You can later on access a bookmarked folder with:
3249 3192 %cd -b <name>
3250 3193 or simply '%cd <name>' if there is no directory called <name> AND
3251 3194 there is such a bookmark defined.
3252 3195
3253 3196 Your bookmarks persist through IPython sessions, but they are
3254 3197 associated with each profile."""
3255 3198
3256 3199 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3257 3200 if len(args) > 2:
3258 3201 raise UsageError("%bookmark: too many arguments")
3259 3202
3260 3203 bkms = self.db.get('bookmarks',{})
3261 3204
3262 3205 if opts.has_key('d'):
3263 3206 try:
3264 3207 todel = args[0]
3265 3208 except IndexError:
3266 3209 raise UsageError(
3267 3210 "%bookmark -d: must provide a bookmark to delete")
3268 3211 else:
3269 3212 try:
3270 3213 del bkms[todel]
3271 3214 except KeyError:
3272 3215 raise UsageError(
3273 3216 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3274 3217
3275 3218 elif opts.has_key('r'):
3276 3219 bkms = {}
3277 3220 elif opts.has_key('l'):
3278 3221 bks = bkms.keys()
3279 3222 bks.sort()
3280 3223 if bks:
3281 3224 size = max(map(len,bks))
3282 3225 else:
3283 3226 size = 0
3284 3227 fmt = '%-'+str(size)+'s -> %s'
3285 3228 print 'Current bookmarks:'
3286 3229 for bk in bks:
3287 3230 print fmt % (bk,bkms[bk])
3288 3231 else:
3289 3232 if not args:
3290 3233 raise UsageError("%bookmark: You must specify the bookmark name")
3291 3234 elif len(args)==1:
3292 3235 bkms[args[0]] = os.getcwd()
3293 3236 elif len(args)==2:
3294 3237 bkms[args[0]] = args[1]
3295 3238 self.db['bookmarks'] = bkms
3296 3239
3297 3240 def magic_pycat(self, parameter_s=''):
3298 3241 """Show a syntax-highlighted file through a pager.
3299 3242
3300 3243 This magic is similar to the cat utility, but it will assume the file
3301 3244 to be Python source and will show it with syntax highlighting. """
3302 3245
3303 3246 try:
3304 3247 filename = get_py_filename(parameter_s)
3305 3248 cont = file_read(filename)
3306 3249 except IOError:
3307 3250 try:
3308 3251 cont = eval(parameter_s,self.user_ns)
3309 3252 except NameError:
3310 3253 cont = None
3311 3254 if cont is None:
3312 3255 print "Error: no such file or variable"
3313 3256 return
3314 3257
3315 3258 page(self.shell.pycolorize(cont),
3316 3259 screen_lines=self.shell.usable_screen_length)
3317 3260
3318 3261 def _rerun_pasted(self):
3319 3262 """ Rerun a previously pasted command.
3320 3263 """
3321 3264 b = self.user_ns.get('pasted_block', None)
3322 3265 if b is None:
3323 3266 raise UsageError('No previous pasted block available')
3324 3267 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3325 3268 exec b in self.user_ns
3326 3269
3327 3270 def _get_pasted_lines(self, sentinel):
3328 3271 """ Yield pasted lines until the user enters the given sentinel value.
3329 3272 """
3330 3273 from IPython.core import interactiveshell
3331 3274 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3332 3275 while True:
3333 3276 l = interactiveshell.raw_input_original(':')
3334 3277 if l == sentinel:
3335 3278 return
3336 3279 else:
3337 3280 yield l
3338 3281
3339 3282 def _strip_pasted_lines_for_code(self, raw_lines):
3340 3283 """ Strip non-code parts of a sequence of lines to return a block of
3341 3284 code.
3342 3285 """
3343 3286 # Regular expressions that declare text we strip from the input:
3344 3287 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3345 3288 r'^\s*(\s?>)+', # Python input prompt
3346 3289 r'^\s*\.{3,}', # Continuation prompts
3347 3290 r'^\++',
3348 3291 ]
3349 3292
3350 3293 strip_from_start = map(re.compile,strip_re)
3351 3294
3352 3295 lines = []
3353 3296 for l in raw_lines:
3354 3297 for pat in strip_from_start:
3355 3298 l = pat.sub('',l)
3356 3299 lines.append(l)
3357 3300
3358 3301 block = "\n".join(lines) + '\n'
3359 3302 #print "block:\n",block
3360 3303 return block
3361 3304
3362 3305 def _execute_block(self, block, par):
3363 3306 """ Execute a block, or store it in a variable, per the user's request.
3364 3307 """
3365 3308 if not par:
3366 3309 b = textwrap.dedent(block)
3367 3310 self.user_ns['pasted_block'] = b
3368 3311 exec b in self.user_ns
3369 3312 else:
3370 3313 self.user_ns[par] = SList(block.splitlines())
3371 3314 print "Block assigned to '%s'" % par
3372 3315
3373 3316 def magic_cpaste(self, parameter_s=''):
3374 3317 """Allows you to paste & execute a pre-formatted code block from clipboard.
3375 3318
3376 3319 You must terminate the block with '--' (two minus-signs) alone on the
3377 3320 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3378 3321 is the new sentinel for this operation)
3379 3322
3380 3323 The block is dedented prior to execution to enable execution of method
3381 3324 definitions. '>' and '+' characters at the beginning of a line are
3382 3325 ignored, to allow pasting directly from e-mails, diff files and
3383 3326 doctests (the '...' continuation prompt is also stripped). The
3384 3327 executed block is also assigned to variable named 'pasted_block' for
3385 3328 later editing with '%edit pasted_block'.
3386 3329
3387 3330 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3388 3331 This assigns the pasted block to variable 'foo' as string, without
3389 3332 dedenting or executing it (preceding >>> and + is still stripped)
3390 3333
3391 3334 '%cpaste -r' re-executes the block previously entered by cpaste.
3392 3335
3393 3336 Do not be alarmed by garbled output on Windows (it's a readline bug).
3394 3337 Just press enter and type -- (and press enter again) and the block
3395 3338 will be what was just pasted.
3396 3339
3397 3340 IPython statements (magics, shell escapes) are not supported (yet).
3398 3341
3399 3342 See also
3400 3343 --------
3401 3344 paste: automatically pull code from clipboard.
3402 3345 """
3403 3346
3404 3347 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3405 3348 par = args.strip()
3406 3349 if opts.has_key('r'):
3407 3350 self._rerun_pasted()
3408 3351 return
3409 3352
3410 3353 sentinel = opts.get('s','--')
3411 3354
3412 3355 block = self._strip_pasted_lines_for_code(
3413 3356 self._get_pasted_lines(sentinel))
3414 3357
3415 3358 self._execute_block(block, par)
3416 3359
3417 3360 def magic_paste(self, parameter_s=''):
3418 3361 """Allows you to paste & execute a pre-formatted code block from clipboard.
3419 3362
3420 3363 The text is pulled directly from the clipboard without user
3421 3364 intervention and printed back on the screen before execution (unless
3422 3365 the -q flag is given to force quiet mode).
3423 3366
3424 3367 The block is dedented prior to execution to enable execution of method
3425 3368 definitions. '>' and '+' characters at the beginning of a line are
3426 3369 ignored, to allow pasting directly from e-mails, diff files and
3427 3370 doctests (the '...' continuation prompt is also stripped). The
3428 3371 executed block is also assigned to variable named 'pasted_block' for
3429 3372 later editing with '%edit pasted_block'.
3430 3373
3431 3374 You can also pass a variable name as an argument, e.g. '%paste foo'.
3432 3375 This assigns the pasted block to variable 'foo' as string, without
3433 3376 dedenting or executing it (preceding >>> and + is still stripped)
3434 3377
3435 3378 Options
3436 3379 -------
3437 3380
3438 3381 -r: re-executes the block previously entered by cpaste.
3439 3382
3440 3383 -q: quiet mode: do not echo the pasted text back to the terminal.
3441 3384
3442 3385 IPython statements (magics, shell escapes) are not supported (yet).
3443 3386
3444 3387 See also
3445 3388 --------
3446 3389 cpaste: manually paste code into terminal until you mark its end.
3447 3390 """
3448 3391 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3449 3392 par = args.strip()
3450 3393 if opts.has_key('r'):
3451 3394 self._rerun_pasted()
3452 3395 return
3453 3396
3454 3397 text = self.shell.hooks.clipboard_get()
3455 3398 block = self._strip_pasted_lines_for_code(text.splitlines())
3456 3399
3457 3400 # By default, echo back to terminal unless quiet mode is requested
3458 3401 if not opts.has_key('q'):
3459 3402 write = self.shell.write
3460 3403 write(self.shell.pycolorize(block))
3461 3404 if not block.endswith('\n'):
3462 3405 write('\n')
3463 3406 write("## -- End pasted text --\n")
3464 3407
3465 3408 self._execute_block(block, par)
3466 3409
3467 3410 def magic_quickref(self,arg):
3468 3411 """ Show a quick reference sheet """
3469 3412 import IPython.core.usage
3470 3413 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3471 3414
3472 3415 page(qr)
3473 3416
3474 3417 def magic_doctest_mode(self,parameter_s=''):
3475 3418 """Toggle doctest mode on and off.
3476 3419
3477 3420 This mode allows you to toggle the prompt behavior between normal
3478 3421 IPython prompts and ones that are as similar to the default IPython
3479 3422 interpreter as possible.
3480 3423
3481 3424 It also supports the pasting of code snippets that have leading '>>>'
3482 3425 and '...' prompts in them. This means that you can paste doctests from
3483 3426 files or docstrings (even if they have leading whitespace), and the
3484 3427 code will execute correctly. You can then use '%history -tn' to see
3485 3428 the translated history without line numbers; this will give you the
3486 3429 input after removal of all the leading prompts and whitespace, which
3487 3430 can be pasted back into an editor.
3488 3431
3489 3432 With these features, you can switch into this mode easily whenever you
3490 3433 need to do testing and changes to doctests, without having to leave
3491 3434 your existing IPython session.
3492 3435 """
3493 3436
3494 3437 from IPython.utils.ipstruct import Struct
3495 3438
3496 3439 # Shorthands
3497 3440 shell = self.shell
3498 3441 oc = shell.outputcache
3499 3442 meta = shell.meta
3500 3443 # dstore is a data store kept in the instance metadata bag to track any
3501 3444 # changes we make, so we can undo them later.
3502 3445 dstore = meta.setdefault('doctest_mode',Struct())
3503 3446 save_dstore = dstore.setdefault
3504 3447
3505 3448 # save a few values we'll need to recover later
3506 3449 mode = save_dstore('mode',False)
3507 3450 save_dstore('rc_pprint',shell.pprint)
3508 3451 save_dstore('xmode',shell.InteractiveTB.mode)
3509 3452 save_dstore('rc_separate_out',shell.separate_out)
3510 3453 save_dstore('rc_separate_out2',shell.separate_out2)
3511 3454 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3512 3455 save_dstore('rc_separate_in',shell.separate_in)
3513 3456
3514 3457 if mode == False:
3515 3458 # turn on
3516 3459 oc.prompt1.p_template = '>>> '
3517 3460 oc.prompt2.p_template = '... '
3518 3461 oc.prompt_out.p_template = ''
3519 3462
3520 3463 # Prompt separators like plain python
3521 3464 oc.input_sep = oc.prompt1.sep = ''
3522 3465 oc.output_sep = ''
3523 3466 oc.output_sep2 = ''
3524 3467
3525 3468 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3526 3469 oc.prompt_out.pad_left = False
3527 3470
3528 3471 shell.pprint = False
3529 3472
3530 3473 shell.magic_xmode('Plain')
3531 3474
3532 3475 else:
3533 3476 # turn off
3534 3477 oc.prompt1.p_template = shell.prompt_in1
3535 3478 oc.prompt2.p_template = shell.prompt_in2
3536 3479 oc.prompt_out.p_template = shell.prompt_out
3537 3480
3538 3481 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3539 3482
3540 3483 oc.output_sep = dstore.rc_separate_out
3541 3484 oc.output_sep2 = dstore.rc_separate_out2
3542 3485
3543 3486 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3544 3487 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3545 3488
3546 3489 shell.pprint = dstore.rc_pprint
3547 3490
3548 3491 shell.magic_xmode(dstore.xmode)
3549 3492
3550 3493 # Store new mode and inform
3551 3494 dstore.mode = bool(1-int(mode))
3552 3495 print 'Doctest mode is:',
3553 3496 print ['OFF','ON'][dstore.mode]
3554 3497
3555 3498 def magic_gui(self, parameter_s=''):
3556 3499 """Enable or disable IPython GUI event loop integration.
3557 3500
3558 3501 %gui [-a] [GUINAME]
3559 3502
3560 3503 This magic replaces IPython's threaded shells that were activated
3561 3504 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3562 3505 can now be enabled, disabled and swtiched at runtime and keyboard
3563 3506 interrupts should work without any problems. The following toolkits
3564 3507 are supported: wxPython, PyQt4, PyGTK, and Tk::
3565 3508
3566 3509 %gui wx # enable wxPython event loop integration
3567 3510 %gui qt4|qt # enable PyQt4 event loop integration
3568 3511 %gui gtk # enable PyGTK event loop integration
3569 3512 %gui tk # enable Tk event loop integration
3570 3513 %gui # disable all event loop integration
3571 3514
3572 3515 WARNING: after any of these has been called you can simply create
3573 3516 an application object, but DO NOT start the event loop yourself, as
3574 3517 we have already handled that.
3575 3518
3576 3519 If you want us to create an appropriate application object add the
3577 3520 "-a" flag to your command::
3578 3521
3579 3522 %gui -a wx
3580 3523
3581 3524 This is highly recommended for most users.
3582 3525 """
3583 3526 opts, arg = self.parse_options(parameter_s,'a')
3584 3527 if arg=='': arg = None
3585 3528 return enable_gui(arg, 'a' in opts)
3586 3529
3587 3530 def magic_load_ext(self, module_str):
3588 3531 """Load an IPython extension by its module name."""
3589 3532 return self.extension_manager.load_extension(module_str)
3590 3533
3591 3534 def magic_unload_ext(self, module_str):
3592 3535 """Unload an IPython extension by its module name."""
3593 3536 self.extension_manager.unload_extension(module_str)
3594 3537
3595 3538 def magic_reload_ext(self, module_str):
3596 3539 """Reload an IPython extension by its module name."""
3597 3540 self.extension_manager.reload_extension(module_str)
3598 3541
3599 3542 @testdec.skip_doctest
3600 3543 def magic_install_profiles(self, s):
3601 3544 """Install the default IPython profiles into the .ipython dir.
3602 3545
3603 3546 If the default profiles have already been installed, they will not
3604 3547 be overwritten. You can force overwriting them by using the ``-o``
3605 3548 option::
3606 3549
3607 3550 In [1]: %install_profiles -o
3608 3551 """
3609 3552 if '-o' in s:
3610 3553 overwrite = True
3611 3554 else:
3612 3555 overwrite = False
3613 3556 from IPython.config import profile
3614 3557 profile_dir = os.path.split(profile.__file__)[0]
3615 3558 ipython_dir = self.ipython_dir
3616 3559 files = os.listdir(profile_dir)
3617 3560
3618 3561 to_install = []
3619 3562 for f in files:
3620 3563 if f.startswith('ipython_config'):
3621 3564 src = os.path.join(profile_dir, f)
3622 3565 dst = os.path.join(ipython_dir, f)
3623 3566 if (not os.path.isfile(dst)) or overwrite:
3624 3567 to_install.append((f, src, dst))
3625 3568 if len(to_install)>0:
3626 3569 print "Installing profiles to: ", ipython_dir
3627 3570 for (f, src, dst) in to_install:
3628 3571 shutil.copy(src, dst)
3629 3572 print " %s" % f
3630 3573
3631 3574 def magic_install_default_config(self, s):
3632 3575 """Install IPython's default config file into the .ipython dir.
3633 3576
3634 3577 If the default config file (:file:`ipython_config.py`) is already
3635 3578 installed, it will not be overwritten. You can force overwriting
3636 3579 by using the ``-o`` option::
3637 3580
3638 3581 In [1]: %install_default_config
3639 3582 """
3640 3583 if '-o' in s:
3641 3584 overwrite = True
3642 3585 else:
3643 3586 overwrite = False
3644 3587 from IPython.config import default
3645 3588 config_dir = os.path.split(default.__file__)[0]
3646 3589 ipython_dir = self.ipython_dir
3647 3590 default_config_file_name = 'ipython_config.py'
3648 3591 src = os.path.join(config_dir, default_config_file_name)
3649 3592 dst = os.path.join(ipython_dir, default_config_file_name)
3650 3593 if (not os.path.isfile(dst)) or overwrite:
3651 3594 shutil.copy(src, dst)
3652 3595 print "Installing default config file: %s" % dst
3653 3596
3654 3597 # Pylab support: simple wrappers that activate pylab, load gui input
3655 3598 # handling and modify slightly %run
3656 3599
3657 3600 @testdec.skip_doctest
3658 3601 def _pylab_magic_run(self, parameter_s=''):
3659 3602 Magic.magic_run(self, parameter_s,
3660 3603 runner=mpl_runner(self.shell.safe_execfile))
3661 3604
3662 3605 _pylab_magic_run.__doc__ = magic_run.__doc__
3663 3606
3664 3607 @testdec.skip_doctest
3665 3608 def magic_pylab(self, s):
3666 3609 """Load numpy and matplotlib to work interactively.
3667 3610
3668 3611 %pylab [GUINAME]
3669 3612
3670 3613 This function lets you activate pylab (matplotlib, numpy and
3671 3614 interactive support) at any point during an IPython session.
3672 3615
3673 3616 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3674 3617 pylab and mlab, as well as all names from numpy and pylab.
3675 3618
3676 3619 Parameters
3677 3620 ----------
3678 3621 guiname : optional
3679 3622 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3680 3623 'tk'). If given, the corresponding Matplotlib backend is used,
3681 3624 otherwise matplotlib's default (which you can override in your
3682 3625 matplotlib config file) is used.
3683 3626
3684 3627 Examples
3685 3628 --------
3686 3629 In this case, where the MPL default is TkAgg:
3687 3630 In [2]: %pylab
3688 3631
3689 3632 Welcome to pylab, a matplotlib-based Python environment.
3690 3633 Backend in use: TkAgg
3691 3634 For more information, type 'help(pylab)'.
3692 3635
3693 3636 But you can explicitly request a different backend:
3694 3637 In [3]: %pylab qt
3695 3638
3696 3639 Welcome to pylab, a matplotlib-based Python environment.
3697 3640 Backend in use: Qt4Agg
3698 3641 For more information, type 'help(pylab)'.
3699 3642 """
3700 3643 self.shell.enable_pylab(s)
3701 3644
3702 3645 def magic_tb(self, s):
3703 3646 """Print the last traceback with the currently active exception mode.
3704 3647
3705 3648 See %xmode for changing exception reporting modes."""
3706 3649 self.shell.showtraceback()
3707 3650
3708 3651 # end Magic
@@ -1,62 +1,59 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3
4 4 def test_import_completer():
5 5 from IPython.core import completer
6 6
7 7 def test_import_crashhandler():
8 8 from IPython.core import crashhandler
9 9
10 10 def test_import_debugger():
11 11 from IPython.core import debugger
12 12
13 13 def test_import_fakemodule():
14 14 from IPython.core import fakemodule
15 15
16 16 def test_import_excolors():
17 17 from IPython.core import excolors
18 18
19 19 def test_import_history():
20 20 from IPython.core import history
21 21
22 22 def test_import_hooks():
23 23 from IPython.core import hooks
24 24
25 25 def test_import_ipapi():
26 26 from IPython.core import ipapi
27 27
28 28 def test_import_interactiveshell():
29 29 from IPython.core import interactiveshell
30 30
31 31 def test_import_logger():
32 32 from IPython.core import logger
33 33
34 34 def test_import_macro():
35 35 from IPython.core import macro
36 36
37 37 def test_import_magic():
38 38 from IPython.core import magic
39 39
40 40 def test_import_oinspect():
41 41 from IPython.core import oinspect
42 42
43 def test_import_outputtrap():
44 from IPython.core import outputtrap
45
46 43 def test_import_prefilter():
47 44 from IPython.core import prefilter
48 45
49 46 def test_import_prompts():
50 47 from IPython.core import prompts
51 48
52 49 def test_import_release():
53 50 from IPython.core import release
54 51
55 52 def test_import_shadowns():
56 53 from IPython.core import shadowns
57 54
58 55 def test_import_ultratb():
59 56 from IPython.core import ultratb
60 57
61 58 def test_import_usage():
62 59 from IPython.core import usage
1 NO CONTENT: file renamed from IPython/core/outputtrap.py to IPython/deathrow/outputtrap.py
@@ -1,275 +1,272 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 An embedded IPython shell.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 from __future__ import with_statement
27 27 import __main__
28 28
29 29 import sys
30 30 from contextlib import nested
31 31
32 32 from IPython.core import ultratb
33 from IPython.core.interactiveshell import InteractiveShell
33 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
34 34 from IPython.frontend.terminal.ipapp import load_default_config
35 35
36 36 from IPython.utils.traitlets import Bool, Str, CBool
37 37 from IPython.utils.io import ask_yes_no
38 38
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Classes and functions
42 42 #-----------------------------------------------------------------------------
43 43
44 44 # This is an additional magic that is exposed in embedded shells.
45 45 def kill_embedded(self,parameter_s=''):
46 46 """%kill_embedded : deactivate for good the current embedded IPython.
47 47
48 48 This function (after asking for confirmation) sets an internal flag so that
49 49 an embedded IPython will never activate again. This is useful to
50 50 permanently disable a shell that is being called inside a loop: once you've
51 51 figured out what you needed from it, you may then kill it and the program
52 52 will then continue to run without the interactive shell interfering again.
53 53 """
54 54
55 55 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
56 56 "(y/n)? [y/N] ",'n')
57 57 if kill:
58 58 self.embedded_active = False
59 59 print "This embedded IPython will not reactivate anymore once you exit."
60 60
61 61
62 class InteractiveShellEmbed(InteractiveShell):
62 class InteractiveShellEmbed(TerminalInteractiveShell):
63 63
64 64 dummy_mode = Bool(False)
65 65 exit_msg = Str('')
66 66 embedded = CBool(True)
67 67 embedded_active = CBool(True)
68 68 # Like the base class display_banner is not configurable, but here it
69 69 # is True by default.
70 70 display_banner = CBool(True)
71 71
72 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
73 user_ns=None, user_global_ns=None,
74 banner1=None, banner2=None, display_banner=None,
75 custom_exceptions=((),None), exit_msg=''):
72 def __init__(self, config=None, ipython_dir=None, user_ns=None,
73 user_global_ns=None, custom_exceptions=((),None),
74 usage=None, banner1=None, banner2=None,
75 display_banner=None, exit_msg=u''):
76 76
77 77 self.save_sys_ipcompleter()
78 78
79 79 super(InteractiveShellEmbed,self).__init__(
80 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
81 user_ns=user_ns, user_global_ns=user_global_ns,
82 banner1=banner1, banner2=banner2, display_banner=display_banner,
83 custom_exceptions=custom_exceptions)
80 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
81 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions,
82 usage=usage, banner1=banner1, banner2=banner2,
83 display_banner=display_banner
84 )
84 85
85 86 self.exit_msg = exit_msg
86 87 self.define_magic("kill_embedded", kill_embedded)
87 88
88 89 # don't use the ipython crash handler so that user exceptions aren't
89 90 # trapped
90 91 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
91 92 mode=self.xmode,
92 93 call_pdb=self.pdb)
93 94
94 95 self.restore_sys_ipcompleter()
95 96
96 97 def init_sys_modules(self):
97 98 pass
98 99
99 100 def save_sys_ipcompleter(self):
100 101 """Save readline completer status."""
101 102 try:
102 103 #print 'Save completer',sys.ipcompleter # dbg
103 104 self.sys_ipcompleter_orig = sys.ipcompleter
104 105 except:
105 106 pass # not nested with IPython
106 107
107 108 def restore_sys_ipcompleter(self):
108 109 """Restores the readline completer which was in place.
109 110
110 111 This allows embedded IPython within IPython not to disrupt the
111 112 parent's completion.
112 113 """
113 114 try:
114 115 self.readline.set_completer(self.sys_ipcompleter_orig)
115 116 sys.ipcompleter = self.sys_ipcompleter_orig
116 117 except:
117 118 pass
118 119
119 120 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
120 121 stack_depth=1):
121 122 """Activate the interactive interpreter.
122 123
123 124 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
124 125 the interpreter shell with the given local and global namespaces, and
125 126 optionally print a header string at startup.
126 127
127 128 The shell can be globally activated/deactivated using the
128 129 set/get_dummy_mode methods. This allows you to turn off a shell used
129 130 for debugging globally.
130 131
131 132 However, *each* time you call the shell you can override the current
132 133 state of dummy_mode with the optional keyword parameter 'dummy'. For
133 134 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
134 135 can still have a specific call work by making it as IPShell(dummy=0).
135 136
136 137 The optional keyword parameter dummy controls whether the call
137 138 actually does anything.
138 139 """
139 140
140 141 # If the user has turned it off, go away
141 142 if not self.embedded_active:
142 143 return
143 144
144 145 # Normal exits from interactive mode set this flag, so the shell can't
145 146 # re-enter (it checks this variable at the start of interactive mode).
146 147 self.exit_now = False
147 148
148 149 # Allow the dummy parameter to override the global __dummy_mode
149 150 if dummy or (dummy != 0 and self.dummy_mode):
150 151 return
151 152
152 153 if self.has_readline:
153 154 self.set_completer()
154 155
155 156 # self.banner is auto computed
156 157 if header:
157 158 self.old_banner2 = self.banner2
158 159 self.banner2 = self.banner2 + '\n' + header + '\n'
159 160 else:
160 161 self.old_banner2 = ''
161 162
162 163 # Call the embedding code with a stack depth of 1 so it can skip over
163 164 # our call and get the original caller's namespaces.
164 165 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
165 166
166 167 self.banner2 = self.old_banner2
167 168
168 169 if self.exit_msg is not None:
169 170 print self.exit_msg
170 171
171 172 self.restore_sys_ipcompleter()
172 173
173 174 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
174 175 display_banner=None):
175 176 """Embeds IPython into a running python program.
176 177
177 178 Input:
178 179
179 180 - header: An optional header message can be specified.
180 181
181 182 - local_ns, global_ns: working namespaces. If given as None, the
182 183 IPython-initialized one is updated with __main__.__dict__, so that
183 184 program variables become visible but user-specific configuration
184 185 remains possible.
185 186
186 187 - stack_depth: specifies how many levels in the stack to go to
187 188 looking for namespaces (when local_ns and global_ns are None). This
188 189 allows an intermediate caller to make sure that this function gets
189 190 the namespace from the intended level in the stack. By default (0)
190 191 it will get its locals and globals from the immediate caller.
191 192
192 193 Warning: it's possible to use this in a program which is being run by
193 194 IPython itself (via %run), but some funny things will happen (a few
194 195 globals get overwritten). In the future this will be cleaned up, as
195 196 there is no fundamental reason why it can't work perfectly."""
196 197
197 198 # Get locals and globals from caller
198 199 if local_ns is None or global_ns is None:
199 200 call_frame = sys._getframe(stack_depth).f_back
200 201
201 202 if local_ns is None:
202 203 local_ns = call_frame.f_locals
203 204 if global_ns is None:
204 205 global_ns = call_frame.f_globals
205 206
206 207 # Update namespaces and fire up interpreter
207 208
208 209 # The global one is easy, we can just throw it in
209 210 self.user_global_ns = global_ns
210 211
211 212 # but the user/local one is tricky: ipython needs it to store internal
212 213 # data, but we also need the locals. We'll copy locals in the user
213 214 # one, but will track what got copied so we can delete them at exit.
214 215 # This is so that a later embedded call doesn't see locals from a
215 216 # previous call (which most likely existed in a separate scope).
216 217 local_varnames = local_ns.keys()
217 218 self.user_ns.update(local_ns)
218 219 #self.user_ns['local_ns'] = local_ns # dbg
219 220
220 221 # Patch for global embedding to make sure that things don't overwrite
221 222 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
222 223 # FIXME. Test this a bit more carefully (the if.. is new)
223 224 if local_ns is None and global_ns is None:
224 225 self.user_global_ns.update(__main__.__dict__)
225 226
226 227 # make sure the tab-completer has the correct frame information, so it
227 228 # actually completes using the frame's locals/globals
228 229 self.set_completer_frame()
229 230
230 231 with nested(self.builtin_trap, self.display_trap):
231 232 self.interact(display_banner=display_banner)
232 233
233 234 # now, purge out the user namespace from anything we might have added
234 235 # from the caller's local namespace
235 236 delvar = self.user_ns.pop
236 237 for var in local_varnames:
237 238 delvar(var,None)
238 239
239 240
240 241 _embedded_shell = None
241 242
242 243
243 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
244 display_banner=True, exit_msg=''):
244 def embed(**kwargs):
245 245 """Call this to embed IPython at the current point in your program.
246 246
247 247 The first invocation of this will create an :class:`InteractiveShellEmbed`
248 248 instance and then call it. Consecutive calls just call the already
249 249 created instance.
250 250
251 251 Here is a simple example::
252 252
253 253 from IPython import embed
254 254 a = 10
255 255 b = 20
256 256 embed('First time')
257 257 c = 30
258 258 d = 40
259 259 embed
260 260
261 261 Full customization can be done by passing a :class:`Struct` in as the
262 262 config argument.
263 263 """
264 config = kwargs.get('config')
265 header = kwargs.pop('header', u'')
264 266 if config is None:
265 267 config = load_default_config()
266 config.InteractiveShellEmbed = config.InteractiveShell
268 config.InteractiveShellEmbed = config.TerminalInteractiveShell
267 269 global _embedded_shell
268 270 if _embedded_shell is None:
269 _embedded_shell = InteractiveShellEmbed(
270 config=config, usage=usage,
271 banner1=banner1, banner2=banner2,
272 display_banner=display_banner, exit_msg=exit_msg
273 )
271 _embedded_shell = InteractiveShellEmbed(**kwargs)
274 272 _embedded_shell(header=header, stack_depth=2)
275
@@ -1,665 +1,665 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.Application` object for the command
5 5 line :command:`ipython` program.
6 6
7 7 Authors
8 8 -------
9 9
10 10 * Brian Granger
11 11 * Fernando Perez
12 12 """
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2008-2010 The IPython Development Team
16 16 #
17 17 # Distributed under the terms of the BSD License. The full license is in
18 18 # the file COPYING, distributed as part of this software.
19 19 #-----------------------------------------------------------------------------
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Imports
23 23 #-----------------------------------------------------------------------------
24 24
25 25 from __future__ import absolute_import
26 26
27 27 import logging
28 28 import os
29 29 import sys
30 30
31 31 from IPython.core import release
32 32 from IPython.core.crashhandler import CrashHandler
33 33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.core.interactiveshell import InteractiveShell
34 from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
35 35 from IPython.config.loader import (
36 36 Config,
37 37 PyFileConfigLoader
38 38 )
39 39 from IPython.lib import inputhook
40 40 from IPython.utils.path import filefind, get_ipython_dir
41 41 from IPython.core import usage
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Globals, utilities and helpers
45 45 #-----------------------------------------------------------------------------
46 46
47 47 #: The default config file name for this application.
48 48 default_config_file_name = u'ipython_config.py'
49 49
50 50
51 51 class IPAppConfigLoader(BaseAppConfigLoader):
52 52
53 53 def _add_arguments(self):
54 54 super(IPAppConfigLoader, self)._add_arguments()
55 55 paa = self.parser.add_argument
56 56 paa('-p',
57 57 '--profile', dest='Global.profile', type=unicode,
58 58 help=
59 59 """The string name of the ipython profile to be used. Assume that your
60 60 config file is ipython_config-<name>.py (looks in current dir first,
61 61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 62 config files for different tasks, especially if include your basic one
63 63 in your more specialized ones. You can keep a basic
64 64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 65 include this one and load extra things for particular tasks.""",
66 66 metavar='Global.profile')
67 67 paa('--config-file',
68 68 dest='Global.config_file', type=unicode,
69 69 help=
70 70 """Set the config file name to override default. Normally IPython
71 71 loads ipython_config.py (from current directory) or
72 72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 73 fails, IPython starts with a bare bones configuration (no modules
74 74 loaded at all).""",
75 75 metavar='Global.config_file')
76 76 paa('--autocall',
77 77 dest='InteractiveShell.autocall', type=int,
78 78 help=
79 79 """Make IPython automatically call any callable object even if you
80 80 didn't type explicit parentheses. For example, 'str 43' becomes
81 81 'str(43)' automatically. The value can be '0' to disable the feature,
82 82 '1' for 'smart' autocall, where it is not applied if there are no more
83 83 arguments on the line, and '2' for 'full' autocall, where all callable
84 84 objects are automatically called (even if no arguments are present).
85 85 The default is '1'.""",
86 86 metavar='InteractiveShell.autocall')
87 87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
88 action='store_true', dest='TerminalInteractiveShell.autoindent',
89 89 help='Turn on autoindenting.')
90 90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
91 action='store_false', dest='TerminalInteractiveShell.autoindent',
92 92 help='Turn off autoindenting.')
93 93 paa('--automagic',
94 94 action='store_true', dest='InteractiveShell.automagic',
95 95 help=
96 96 """Turn on the auto calling of magic commands. Type %%magic at the
97 97 IPython prompt for more information.""")
98 98 paa('--no-automagic',
99 99 action='store_false', dest='InteractiveShell.automagic',
100 100 help='Turn off the auto calling of magic commands.')
101 101 paa('--autoedit-syntax',
102 action='store_true', dest='InteractiveShell.autoedit_syntax',
102 action='store_true', dest='TerminalInteractiveShell.autoedit_syntax',
103 103 help='Turn on auto editing of files with syntax errors.')
104 104 paa('--no-autoedit-syntax',
105 action='store_false', dest='InteractiveShell.autoedit_syntax',
105 action='store_false', dest='TerminalInteractiveShell.autoedit_syntax',
106 106 help='Turn off auto editing of files with syntax errors.')
107 107 paa('--banner',
108 108 action='store_true', dest='Global.display_banner',
109 109 help='Display a banner upon starting IPython.')
110 110 paa('--no-banner',
111 111 action='store_false', dest='Global.display_banner',
112 112 help="Don't display a banner upon starting IPython.")
113 113 paa('--cache-size',
114 114 type=int, dest='InteractiveShell.cache_size',
115 115 help=
116 116 """Set the size of the output cache. The default is 1000, you can
117 117 change it permanently in your config file. Setting it to 0 completely
118 118 disables the caching system, and the minimum value accepted is 20 (if
119 119 you provide a value less than 20, it is reset to 0 and a warning is
120 120 issued). This limit is defined because otherwise you'll spend more
121 121 time re-flushing a too small cache than working""",
122 122 metavar='InteractiveShell.cache_size')
123 123 paa('--classic',
124 124 action='store_true', dest='Global.classic',
125 125 help="Gives IPython a similar feel to the classic Python prompt.")
126 126 paa('--colors',
127 127 type=str, dest='InteractiveShell.colors',
128 128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 129 metavar='InteractiveShell.colors')
130 130 paa('--color-info',
131 131 action='store_true', dest='InteractiveShell.color_info',
132 132 help=
133 133 """IPython can display information about objects via a set of func-
134 134 tions, and optionally can use colors for this, syntax highlighting
135 135 source code and various other elements. However, because this
136 136 information is passed through a pager (like 'less') and many pagers get
137 137 confused with color codes, this option is off by default. You can test
138 138 it and turn it on permanently in your ipython_config.py file if it
139 139 works for you. Test it and turn it on permanently if it works with
140 140 your system. The magic function %%color_info allows you to toggle this
141 141 inter- actively for testing.""")
142 142 paa('--no-color-info',
143 143 action='store_false', dest='InteractiveShell.color_info',
144 144 help="Disable using colors for info related things.")
145 145 paa('--confirm-exit',
146 action='store_true', dest='InteractiveShell.confirm_exit',
146 action='store_true', dest='TerminalInteractiveShell.confirm_exit',
147 147 help=
148 148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 150 '%%Exit', you can force a direct exit without any confirmation.""")
151 151 paa('--no-confirm-exit',
152 action='store_false', dest='InteractiveShell.confirm_exit',
152 action='store_false', dest='TerminalInteractiveShell.confirm_exit',
153 153 help="Don't prompt the user when exiting.")
154 154 paa('--deep-reload',
155 155 action='store_true', dest='InteractiveShell.deep_reload',
156 156 help=
157 157 """Enable deep (recursive) reloading by default. IPython can use the
158 158 deep_reload module which reloads changes in modules recursively (it
159 159 replaces the reload() function, so you don't need to change anything to
160 160 use it). deep_reload() forces a full reload of modules whose code may
161 161 have changed, which the default reload() function does not. When
162 162 deep_reload is off, IPython will use the normal reload(), but
163 163 deep_reload will still be available as dreload(). This fea- ture is off
164 164 by default [which means that you have both normal reload() and
165 165 dreload()].""")
166 166 paa('--no-deep-reload',
167 167 action='store_false', dest='InteractiveShell.deep_reload',
168 168 help="Disable deep (recursive) reloading by default.")
169 169 paa('--editor',
170 type=str, dest='InteractiveShell.editor',
170 type=str, dest='TerminalInteractiveShell.editor',
171 171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='InteractiveShell.editor')
172 metavar='TerminalInteractiveShell.editor')
173 173 paa('--log','-l',
174 174 action='store_true', dest='InteractiveShell.logstart',
175 175 help="Start logging to the default log file (./ipython_log.py).")
176 176 paa('--logfile','-lf',
177 177 type=unicode, dest='InteractiveShell.logfile',
178 178 help="Start logging to logfile with this name.",
179 179 metavar='InteractiveShell.logfile')
180 180 paa('--log-append','-la',
181 181 type=unicode, dest='InteractiveShell.logappend',
182 182 help="Start logging to the given file in append mode.",
183 183 metavar='InteractiveShell.logfile')
184 184 paa('--pdb',
185 185 action='store_true', dest='InteractiveShell.pdb',
186 186 help="Enable auto calling the pdb debugger after every exception.")
187 187 paa('--no-pdb',
188 188 action='store_false', dest='InteractiveShell.pdb',
189 189 help="Disable auto calling the pdb debugger after every exception.")
190 190 paa('--pprint',
191 191 action='store_true', dest='InteractiveShell.pprint',
192 192 help="Enable auto pretty printing of results.")
193 193 paa('--no-pprint',
194 194 action='store_false', dest='InteractiveShell.pprint',
195 195 help="Disable auto auto pretty printing of results.")
196 196 paa('--prompt-in1','-pi1',
197 197 type=str, dest='InteractiveShell.prompt_in1',
198 198 help=
199 199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 200 numbered prompts, the number is represented with a '\#' in the string.
201 201 Don't forget to quote strings with spaces embedded in them. Most
202 202 bash-like escapes can be used to customize IPython's prompts, as well
203 203 as a few additional ones which are IPython-spe- cific. All valid
204 204 prompt escapes are described in detail in the Customization section of
205 205 the IPython manual.""",
206 206 metavar='InteractiveShell.prompt_in1')
207 207 paa('--prompt-in2','-pi2',
208 208 type=str, dest='InteractiveShell.prompt_in2',
209 209 help=
210 210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 211 option, but used for the continuation prompts. The special sequence
212 212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 213 can have your continuation prompt aligned with your input prompt).
214 214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 215 'In [\#]')""",
216 216 metavar='InteractiveShell.prompt_in2')
217 217 paa('--prompt-out','-po',
218 218 type=str, dest='InteractiveShell.prompt_out',
219 219 help="Set the output prompt ('Out[\#]:')",
220 220 metavar='InteractiveShell.prompt_out')
221 221 paa('--quick',
222 222 action='store_true', dest='Global.quick',
223 223 help="Enable quick startup with no config files.")
224 224 paa('--readline',
225 225 action='store_true', dest='InteractiveShell.readline_use',
226 226 help="Enable readline for command line usage.")
227 227 paa('--no-readline',
228 228 action='store_false', dest='InteractiveShell.readline_use',
229 229 help="Disable readline for command line usage.")
230 230 paa('--screen-length','-sl',
231 type=int, dest='InteractiveShell.screen_length',
231 type=int, dest='TerminalInteractiveShell.screen_length',
232 232 help=
233 233 """Number of lines of your screen, used to control printing of very
234 234 long strings. Strings longer than this number of lines will be sent
235 235 through a pager instead of directly printed. The default value for
236 236 this is 0, which means IPython will auto-detect your screen size every
237 237 time it needs to print certain potentially long strings (this doesn't
238 238 change the behavior of the 'print' keyword, it's only triggered
239 239 internally). If for some reason this isn't working well (it needs
240 240 curses support), specify it yourself. Otherwise don't change the
241 241 default.""",
242 metavar='InteractiveShell.screen_length')
242 metavar='TerminalInteractiveShell.screen_length')
243 243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
244 type=str, dest='TerminalInteractiveShell.separate_in',
245 245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
246 metavar='TerminalInteractiveShell.separate_in')
247 247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
248 type=str, dest='TerminalInteractiveShell.separate_out',
249 249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
250 metavar='TerminalInteractiveShell.separate_out')
251 251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
252 type=str, dest='TerminalInteractiveShell.separate_out2',
253 253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
254 metavar='TerminalInteractiveShell.separate_out2')
255 255 paa('--no-sep',
256 256 action='store_true', dest='Global.nosep',
257 257 help="Eliminate all spacing between prompts.")
258 258 paa('--term-title',
259 action='store_true', dest='InteractiveShell.term_title',
259 action='store_true', dest='TerminalInteractiveShell.term_title',
260 260 help="Enable auto setting the terminal title.")
261 261 paa('--no-term-title',
262 action='store_false', dest='InteractiveShell.term_title',
262 action='store_false', dest='TerminalInteractiveShell.term_title',
263 263 help="Disable auto setting the terminal title.")
264 264 paa('--xmode',
265 265 type=str, dest='InteractiveShell.xmode',
266 266 help=
267 267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 268 similar to python's normal traceback printing. Context: prints 5 lines
269 269 of context source code around each line in the traceback. Verbose:
270 270 similar to Context, but additionally prints the variables currently
271 271 visible where the exception happened (shortening their strings if too
272 272 long). This can potentially be very slow, if you happen to have a huge
273 273 data structure whose string representation is complex to compute.
274 274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 276 it more than once).
277 277 """,
278 278 metavar='InteractiveShell.xmode')
279 279 paa('--ext',
280 280 type=str, dest='Global.extra_extension',
281 281 help="The dotted module name of an IPython extension to load.",
282 282 metavar='Global.extra_extension')
283 283 paa('-c',
284 284 type=str, dest='Global.code_to_run',
285 285 help="Execute the given command string.",
286 286 metavar='Global.code_to_run')
287 287 paa('-i',
288 288 action='store_true', dest='Global.force_interact',
289 289 help=
290 290 "If running code from the command line, become interactive afterwards.")
291 291
292 292 # Options to start with GUI control enabled from the beginning
293 293 paa('--gui',
294 294 type=str, dest='Global.gui',
295 295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 296 metavar='gui-mode')
297 297 paa('--pylab','-pylab',
298 298 type=str, dest='Global.pylab',
299 299 nargs='?', const='auto', metavar='gui-mode',
300 300 help="Pre-load matplotlib and numpy for interactive use. "+
301 301 "If no value is given, the gui backend is matplotlib's, else use "+
302 302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
303 303
304 304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 305 # 'thread' names are really a misnomer now.
306 306 paa('--wthread', '-wthread',
307 307 action='store_true', dest='Global.wthread',
308 308 help=
309 309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 311 action='store_true', dest='Global.q4thread',
312 312 help=
313 313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 314 (DEPRECATED, use --gui qt)""")
315 315 paa('--gthread', '-gthread',
316 316 action='store_true', dest='Global.gthread',
317 317 help=
318 318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319 319
320 320
321 321 #-----------------------------------------------------------------------------
322 322 # Crash handler for this application
323 323 #-----------------------------------------------------------------------------
324 324
325 325
326 326 _message_template = """\
327 327 Oops, $self.app_name crashed. We do our best to make it stable, but...
328 328
329 329 A crash report was automatically generated with the following information:
330 330 - A verbatim copy of the crash traceback.
331 331 - A copy of your input history during this session.
332 332 - Data on your current $self.app_name configuration.
333 333
334 334 It was left in the file named:
335 335 \t'$self.crash_report_fname'
336 336 If you can email this file to the developers, the information in it will help
337 337 them in understanding and correcting the problem.
338 338
339 339 You can mail it to: $self.contact_name at $self.contact_email
340 340 with the subject '$self.app_name Crash Report'.
341 341
342 342 If you want to do it now, the following command will work (under Unix):
343 343 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
344 344
345 345 To ensure accurate tracking of this issue, please file a report about it at:
346 346 $self.bug_tracker
347 347 """
348 348
349 349 class IPAppCrashHandler(CrashHandler):
350 350 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
351 351
352 352 message_template = _message_template
353 353
354 354 def __init__(self, app):
355 355 contact_name = release.authors['Fernando'][0]
356 356 contact_email = release.authors['Fernando'][1]
357 357 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
358 358 super(IPAppCrashHandler,self).__init__(
359 359 app, contact_name, contact_email, bug_tracker
360 360 )
361 361
362 362 def make_report(self,traceback):
363 363 """Return a string containing a crash report."""
364 364
365 365 sec_sep = self.section_sep
366 366 # Start with parent report
367 367 report = [super(IPAppCrashHandler, self).make_report(traceback)]
368 368 # Add interactive-specific info we may have
369 369 rpt_add = report.append
370 370 try:
371 371 rpt_add(sec_sep+"History of session input:")
372 372 for line in self.app.shell.user_ns['_ih']:
373 373 rpt_add(line)
374 374 rpt_add('\n*** Last line of input (may not be in above history):\n')
375 375 rpt_add(self.app.shell._last_input_line+'\n')
376 376 except:
377 377 pass
378 378
379 379 return ''.join(report)
380 380
381 381
382 382 #-----------------------------------------------------------------------------
383 383 # Main classes and functions
384 384 #-----------------------------------------------------------------------------
385 385
386 386 class IPythonApp(Application):
387 387 name = u'ipython'
388 388 #: argparse formats better the 'usage' than the 'description' field
389 389 description = None
390 390 usage = usage.cl_usage
391 391 command_line_loader = IPAppConfigLoader
392 392 default_config_file_name = default_config_file_name
393 393 crash_handler_class = IPAppCrashHandler
394 394
395 395 def create_default_config(self):
396 396 super(IPythonApp, self).create_default_config()
397 397 # Eliminate multiple lookups
398 398 Global = self.default_config.Global
399 399
400 400 # Set all default values
401 401 Global.display_banner = True
402 402
403 403 # If the -c flag is given or a file is given to run at the cmd line
404 404 # like "ipython foo.py", normally we exit without starting the main
405 405 # loop. The force_interact config variable allows a user to override
406 406 # this and interact. It is also set by the -i cmd line flag, just
407 407 # like Python.
408 408 Global.force_interact = False
409 409
410 410 # By default always interact by starting the IPython mainloop.
411 411 Global.interact = True
412 412
413 413 # No GUI integration by default
414 414 Global.gui = False
415 415 # Pylab off by default
416 416 Global.pylab = False
417 417
418 418 # Deprecated versions of gui support that used threading, we support
419 419 # them just for bacwards compatibility as an alternate spelling for
420 420 # '--gui X'
421 421 Global.qthread = False
422 422 Global.q4thread = False
423 423 Global.wthread = False
424 424 Global.gthread = False
425 425
426 426 def load_file_config(self):
427 427 if hasattr(self.command_line_config.Global, 'quick'):
428 428 if self.command_line_config.Global.quick:
429 429 self.file_config = Config()
430 430 return
431 431 super(IPythonApp, self).load_file_config()
432 432
433 433 def post_load_file_config(self):
434 434 if hasattr(self.command_line_config.Global, 'extra_extension'):
435 435 if not hasattr(self.file_config.Global, 'extensions'):
436 436 self.file_config.Global.extensions = []
437 437 self.file_config.Global.extensions.append(
438 438 self.command_line_config.Global.extra_extension)
439 439 del self.command_line_config.Global.extra_extension
440 440
441 441 def pre_construct(self):
442 442 config = self.master_config
443 443
444 444 if hasattr(config.Global, 'classic'):
445 445 if config.Global.classic:
446 446 config.InteractiveShell.cache_size = 0
447 447 config.InteractiveShell.pprint = 0
448 448 config.InteractiveShell.prompt_in1 = '>>> '
449 449 config.InteractiveShell.prompt_in2 = '... '
450 450 config.InteractiveShell.prompt_out = ''
451 config.InteractiveShell.separate_in = \
452 config.InteractiveShell.separate_out = \
453 config.InteractiveShell.separate_out2 = ''
451 config.TerminalInteractiveShell.separate_in = \
452 config.TerminalInteractiveShell.separate_out = \
453 config.TerminalInteractiveShell.separate_out2 = ''
454 454 config.InteractiveShell.colors = 'NoColor'
455 455 config.InteractiveShell.xmode = 'Plain'
456 456
457 457 if hasattr(config.Global, 'nosep'):
458 458 if config.Global.nosep:
459 config.InteractiveShell.separate_in = \
460 config.InteractiveShell.separate_out = \
461 config.InteractiveShell.separate_out2 = ''
459 config.TerminalInteractiveShell.separate_in = \
460 config.TerminalInteractiveShell.separate_out = \
461 config.TerminalInteractiveShell.separate_out2 = ''
462 462
463 463 # if there is code of files to run from the cmd line, don't interact
464 464 # unless the -i flag (Global.force_interact) is true.
465 465 code_to_run = config.Global.get('code_to_run','')
466 466 file_to_run = False
467 467 if self.extra_args and self.extra_args[0]:
468 468 file_to_run = True
469 469 if file_to_run or code_to_run:
470 470 if not config.Global.force_interact:
471 471 config.Global.interact = False
472 472
473 473 def construct(self):
474 474 # I am a little hesitant to put these into InteractiveShell itself.
475 475 # But that might be the place for them
476 476 sys.path.insert(0, '')
477 477
478 478 # Create an InteractiveShell instance.
479 self.shell = InteractiveShell.instance(config=self.master_config)
479 self.shell = TerminalInteractiveShell.instance(config=self.master_config)
480 480
481 481 def post_construct(self):
482 482 """Do actions after construct, but before starting the app."""
483 483 config = self.master_config
484 484
485 485 # shell.display_banner should always be False for the terminal
486 486 # based app, because we call shell.show_banner() by hand below
487 487 # so the banner shows *before* all extension loading stuff.
488 488 self.shell.display_banner = False
489 489 if config.Global.display_banner and \
490 490 config.Global.interact:
491 491 self.shell.show_banner()
492 492
493 493 # Make sure there is a space below the banner.
494 494 if self.log_level <= logging.INFO: print
495 495
496 496 # Now a variety of things that happen after the banner is printed.
497 497 self._enable_gui_pylab()
498 498 self._load_extensions()
499 499 self._run_exec_lines()
500 500 self._run_exec_files()
501 501 self._run_cmd_line_code()
502 502
503 503 def _enable_gui_pylab(self):
504 504 """Enable GUI event loop integration, taking pylab into account."""
505 505 Global = self.master_config.Global
506 506
507 507 # Select which gui to use
508 508 if Global.gui:
509 509 gui = Global.gui
510 510 # The following are deprecated, but there's likely to be a lot of use
511 511 # of this form out there, so we might as well support it for now. But
512 512 # the --gui option above takes precedence.
513 513 elif Global.wthread:
514 514 gui = inputhook.GUI_WX
515 515 elif Global.qthread:
516 516 gui = inputhook.GUI_QT
517 517 elif Global.gthread:
518 518 gui = inputhook.GUI_GTK
519 519 else:
520 520 gui = None
521 521
522 522 # Using --pylab will also require gui activation, though which toolkit
523 523 # to use may be chosen automatically based on mpl configuration.
524 524 if Global.pylab:
525 525 activate = self.shell.enable_pylab
526 526 if Global.pylab == 'auto':
527 527 gui = None
528 528 else:
529 529 gui = Global.pylab
530 530 else:
531 531 # Enable only GUI integration, no pylab
532 532 activate = inputhook.enable_gui
533 533
534 534 if gui or Global.pylab:
535 535 try:
536 536 self.log.info("Enabling GUI event loop integration, "
537 537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
538 538 activate(gui)
539 539 except:
540 540 self.log.warn("Error in enabling GUI event loop integration:")
541 541 self.shell.showtraceback()
542 542
543 543 def _load_extensions(self):
544 544 """Load all IPython extensions in Global.extensions.
545 545
546 546 This uses the :meth:`ExtensionManager.load_extensions` to load all
547 547 the extensions listed in ``self.master_config.Global.extensions``.
548 548 """
549 549 try:
550 550 if hasattr(self.master_config.Global, 'extensions'):
551 551 self.log.debug("Loading IPython extensions...")
552 552 extensions = self.master_config.Global.extensions
553 553 for ext in extensions:
554 554 try:
555 555 self.log.info("Loading IPython extension: %s" % ext)
556 556 self.shell.extension_manager.load_extension(ext)
557 557 except:
558 558 self.log.warn("Error in loading extension: %s" % ext)
559 559 self.shell.showtraceback()
560 560 except:
561 561 self.log.warn("Unknown error in loading extensions:")
562 562 self.shell.showtraceback()
563 563
564 564 def _run_exec_lines(self):
565 565 """Run lines of code in Global.exec_lines in the user's namespace."""
566 566 try:
567 567 if hasattr(self.master_config.Global, 'exec_lines'):
568 568 self.log.debug("Running code from Global.exec_lines...")
569 569 exec_lines = self.master_config.Global.exec_lines
570 570 for line in exec_lines:
571 571 try:
572 572 self.log.info("Running code in user namespace: %s" %
573 573 line)
574 574 self.shell.runlines(line)
575 575 except:
576 576 self.log.warn("Error in executing line in user "
577 577 "namespace: %s" % line)
578 578 self.shell.showtraceback()
579 579 except:
580 580 self.log.warn("Unknown error in handling Global.exec_lines:")
581 581 self.shell.showtraceback()
582 582
583 583 def _exec_file(self, fname):
584 584 full_filename = filefind(fname, [u'.', self.ipython_dir])
585 585 if os.path.isfile(full_filename):
586 586 if full_filename.endswith(u'.py'):
587 587 self.log.info("Running file in user namespace: %s" %
588 588 full_filename)
589 589 # Ensure that __file__ is always defined to match Python behavior
590 590 self.shell.user_ns['__file__'] = fname
591 591 try:
592 592 self.shell.safe_execfile(full_filename, self.shell.user_ns)
593 593 finally:
594 594 del self.shell.user_ns['__file__']
595 595 elif full_filename.endswith('.ipy'):
596 596 self.log.info("Running file in user namespace: %s" %
597 597 full_filename)
598 598 self.shell.safe_execfile_ipy(full_filename)
599 599 else:
600 600 self.log.warn("File does not have a .py or .ipy extension: <%s>"
601 601 % full_filename)
602 602 def _run_exec_files(self):
603 603 try:
604 604 if hasattr(self.master_config.Global, 'exec_files'):
605 605 self.log.debug("Running files in Global.exec_files...")
606 606 exec_files = self.master_config.Global.exec_files
607 607 for fname in exec_files:
608 608 self._exec_file(fname)
609 609 except:
610 610 self.log.warn("Unknown error in handling Global.exec_files:")
611 611 self.shell.showtraceback()
612 612
613 613 def _run_cmd_line_code(self):
614 614 if hasattr(self.master_config.Global, 'code_to_run'):
615 615 line = self.master_config.Global.code_to_run
616 616 try:
617 617 self.log.info("Running code given at command line (-c): %s" %
618 618 line)
619 619 self.shell.runlines(line)
620 620 except:
621 621 self.log.warn("Error in executing line in user namespace: %s" %
622 622 line)
623 623 self.shell.showtraceback()
624 624 return
625 625 # Like Python itself, ignore the second if the first of these is present
626 626 try:
627 627 fname = self.extra_args[0]
628 628 except:
629 629 pass
630 630 else:
631 631 try:
632 632 self._exec_file(fname)
633 633 except:
634 634 self.log.warn("Error in executing file in user namespace: %s" %
635 635 fname)
636 636 self.shell.showtraceback()
637 637
638 638 def start_app(self):
639 639 if self.master_config.Global.interact:
640 640 self.log.debug("Starting IPython's mainloop...")
641 641 self.shell.mainloop()
642 642 else:
643 643 self.log.debug("IPython not interactive, start_app is no-op...")
644 644
645 645
646 646 def load_default_config(ipython_dir=None):
647 647 """Load the default config file from the default ipython_dir.
648 648
649 649 This is useful for embedded shells.
650 650 """
651 651 if ipython_dir is None:
652 652 ipython_dir = get_ipython_dir()
653 653 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
654 654 config = cl.load_config()
655 655 return config
656 656
657 657
658 658 def launch_new_instance():
659 659 """Create and run a full blown IPython instance"""
660 660 app = IPythonApp()
661 661 app.start()
662 662
663 663
664 664 if __name__ == '__main__':
665 665 launch_new_instance()
@@ -1,174 +1,173 b''
1 1 """Global IPython app to support test running.
2 2
3 3 We must start our own ipython object and heavily muck with it so that all the
4 4 modifications IPython makes to system behavior don't send the doctest machinery
5 5 into a fit. This code should be considered a gross hack, but it gets the job
6 6 done.
7 7 """
8 8
9 9 from __future__ import absolute_import
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import __builtin__
23 23 import commands
24 24 import os
25 25 import sys
26 26
27 27 from . import tools
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Functions
31 31 #-----------------------------------------------------------------------------
32 32
33 33 # Hack to modify the %run command so we can sync the user's namespace with the
34 34 # test globals. Once we move over to a clean magic system, this will be done
35 35 # with much less ugliness.
36 36
37 37 class py_file_finder(object):
38 38 def __init__(self,test_filename):
39 39 self.test_filename = test_filename
40 40
41 41 def __call__(self,name):
42 42 from IPython.utils.path import get_py_filename
43 43 try:
44 44 return get_py_filename(name)
45 45 except IOError:
46 46 test_dir = os.path.dirname(self.test_filename)
47 47 new_path = os.path.join(test_dir,name)
48 48 return get_py_filename(new_path)
49 49
50 50
51 51 def _run_ns_sync(self,arg_s,runner=None):
52 52 """Modified version of %run that syncs testing namespaces.
53 53
54 54 This is strictly needed for running doctests that call %run.
55 55 """
56 56 #print >> sys.stderr, 'in run_ns_sync', arg_s # dbg
57 57
58 58 _ip = get_ipython()
59 59 finder = py_file_finder(arg_s)
60 60 out = _ip.magic_run_ori(arg_s,runner,finder)
61 61 return out
62 62
63 63
64 64 class ipnsdict(dict):
65 65 """A special subclass of dict for use as an IPython namespace in doctests.
66 66
67 67 This subclass adds a simple checkpointing capability so that when testing
68 68 machinery clears it (we use it as the test execution context), it doesn't
69 69 get completely destroyed.
70 70 """
71 71
72 72 def __init__(self,*a):
73 73 dict.__init__(self,*a)
74 74 self._savedict = {}
75 75
76 76 def clear(self):
77 77 dict.clear(self)
78 78 self.update(self._savedict)
79 79
80 80 def _checkpoint(self):
81 81 self._savedict.clear()
82 82 self._savedict.update(self)
83 83
84 84 def update(self,other):
85 85 self._checkpoint()
86 86 dict.update(self,other)
87 87
88 88 # If '_' is in the namespace, python won't set it when executing code,
89 89 # and we have examples that test it. So we ensure that the namespace
90 90 # is always 'clean' of it before it's used for test code execution.
91 91 self.pop('_',None)
92 92
93 93 # The builtins namespace must *always* be the real __builtin__ module,
94 94 # else weird stuff happens. The main ipython code does have provisions
95 95 # to ensure this after %run, but since in this class we do some
96 96 # aggressive low-level cleaning of the execution namespace, we need to
97 97 # correct for that ourselves, to ensure consitency with the 'real'
98 98 # ipython.
99 99 self['__builtins__'] = __builtin__
100 100
101 101
102 102 def get_ipython():
103 103 # This will get replaced by the real thing once we start IPython below
104 104 return start_ipython()
105 105
106 106
107 107 def start_ipython():
108 108 """Start a global IPython shell, which we need for IPython-specific syntax.
109 109 """
110 110 global get_ipython
111 111
112 112 # This function should only ever run once!
113 113 if hasattr(start_ipython, 'already_called'):
114 114 return
115 115 start_ipython.already_called = True
116 116
117 # Ok, first time we're called, go ahead
118 from IPython.core import interactiveshell
117 from IPython.frontend.terminal import interactiveshell
119 118
120 119 def xsys(cmd):
121 120 """Execute a command and print its output.
122 121
123 122 This is just a convenience function to replace the IPython system call
124 123 with one that is more doctest-friendly.
125 124 """
126 125 cmd = _ip.var_expand(cmd,depth=1)
127 126 sys.stdout.write(commands.getoutput(cmd))
128 127 sys.stdout.flush()
129 128
130 129 # Store certain global objects that IPython modifies
131 130 _displayhook = sys.displayhook
132 131 _excepthook = sys.excepthook
133 132 _main = sys.modules.get('__main__')
134 133
135 134 # Create custom argv and namespaces for our IPython to be test-friendly
136 135 config = tools.default_config()
137 136
138 137 # Create and initialize our test-friendly IPython instance.
139 shell = interactiveshell.InteractiveShell.instance(
138 shell = interactiveshell.TerminalInteractiveShell.instance(
140 139 config=config,
141 140 user_ns=ipnsdict(), user_global_ns={}
142 141 )
143 142
144 143 # A few more tweaks needed for playing nicely with doctests...
145 144
146 145 # These traps are normally only active for interactive use, set them
147 146 # permanently since we'll be mocking interactive sessions.
148 147 shell.builtin_trap.set()
149 148
150 149 # Set error printing to stdout so nose can doctest exceptions
151 150 shell.InteractiveTB.out_stream = 'stdout'
152 151
153 152 # Modify the IPython system call with one that uses getoutput, so that we
154 153 # can capture subcommands and print them to Python's stdout, otherwise the
155 154 # doctest machinery would miss them.
156 155 shell.system = xsys
157 156
158 157 # IPython is ready, now clean up some global state...
159 158
160 159 # Deactivate the various python system hooks added by ipython for
161 160 # interactive convenience so we don't confuse the doctest system
162 161 sys.modules['__main__'] = _main
163 162 sys.displayhook = _displayhook
164 163 sys.excepthook = _excepthook
165 164
166 165 # So that ipython magics and aliases can be doctested (they work by making
167 166 # a call into a global _ip object). Also make the top-level get_ipython
168 167 # now return this without recursively calling here again.
169 168 _ip = shell
170 169 get_ipython = _ip.get_ipython
171 170 __builtin__._ip = _ip
172 171 __builtin__.get_ipython = get_ipython
173 172
174 173 return _ip
@@ -1,277 +1,277 b''
1 1 """Generic testing tools that do NOT depend on Twisted.
2 2
3 3 In particular, this module exposes a set of top-level assert* functions that
4 4 can be used in place of nose.tools.assert* in method generators (the ones in
5 5 nose can not, at least as of nose 0.10.4).
6 6
7 7 Note: our testing package contains testing.util, which does depend on Twisted
8 8 and provides utilities for tests that manage Deferreds. All testing support
9 9 tools that only depend on nose, IPython or the standard library should go here
10 10 instead.
11 11
12 12
13 13 Authors
14 14 -------
15 15 - Fernando Perez <Fernando.Perez@berkeley.edu>
16 16 """
17 17
18 18 from __future__ import absolute_import
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Copyright (C) 2009 The IPython Development Team
22 22 #
23 23 # Distributed under the terms of the BSD License. The full license is in
24 24 # the file COPYING, distributed as part of this software.
25 25 #-----------------------------------------------------------------------------
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Imports
29 29 #-----------------------------------------------------------------------------
30 30
31 31 import os
32 32 import re
33 33 import sys
34 34
35 35 try:
36 36 # These tools are used by parts of the runtime, so we make the nose
37 37 # dependency optional at this point. Nose is a hard dependency to run the
38 38 # test suite, but NOT to use ipython itself.
39 39 import nose.tools as nt
40 40 has_nose = True
41 41 except ImportError:
42 42 has_nose = False
43 43
44 44 from IPython.config.loader import Config
45 45 from IPython.utils.process import find_cmd, getoutputerror
46 46 from IPython.utils.text import list_strings
47 47 from IPython.utils.io import temp_pyfile
48 48
49 49 from . import decorators as dec
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Globals
53 53 #-----------------------------------------------------------------------------
54 54
55 55 # Make a bunch of nose.tools assert wrappers that can be used in test
56 56 # generators. This will expose an assert* function for each one in nose.tools.
57 57
58 58 _tpl = """
59 59 def %(name)s(*a,**kw):
60 60 return nt.%(name)s(*a,**kw)
61 61 """
62 62
63 63 if has_nose:
64 64 for _x in [a for a in dir(nt) if a.startswith('assert')]:
65 65 exec _tpl % dict(name=_x)
66 66
67 67 #-----------------------------------------------------------------------------
68 68 # Functions and classes
69 69 #-----------------------------------------------------------------------------
70 70
71 71 # The docstring for full_path doctests differently on win32 (different path
72 72 # separator) so just skip the doctest there. The example remains informative.
73 73 doctest_deco = dec.skip_doctest if sys.platform == 'win32' else dec.null_deco
74 74
75 75 @doctest_deco
76 76 def full_path(startPath,files):
77 77 """Make full paths for all the listed files, based on startPath.
78 78
79 79 Only the base part of startPath is kept, since this routine is typically
80 80 used with a script's __file__ variable as startPath. The base of startPath
81 81 is then prepended to all the listed files, forming the output list.
82 82
83 83 Parameters
84 84 ----------
85 85 startPath : string
86 86 Initial path to use as the base for the results. This path is split
87 87 using os.path.split() and only its first component is kept.
88 88
89 89 files : string or list
90 90 One or more files.
91 91
92 92 Examples
93 93 --------
94 94
95 95 >>> full_path('/foo/bar.py',['a.txt','b.txt'])
96 96 ['/foo/a.txt', '/foo/b.txt']
97 97
98 98 >>> full_path('/foo',['a.txt','b.txt'])
99 99 ['/a.txt', '/b.txt']
100 100
101 101 If a single file is given, the output is still a list:
102 102 >>> full_path('/foo','a.txt')
103 103 ['/a.txt']
104 104 """
105 105
106 106 files = list_strings(files)
107 107 base = os.path.split(startPath)[0]
108 108 return [ os.path.join(base,f) for f in files ]
109 109
110 110
111 111 def parse_test_output(txt):
112 112 """Parse the output of a test run and return errors, failures.
113 113
114 114 Parameters
115 115 ----------
116 116 txt : str
117 117 Text output of a test run, assumed to contain a line of one of the
118 118 following forms::
119 119 'FAILED (errors=1)'
120 120 'FAILED (failures=1)'
121 121 'FAILED (errors=1, failures=1)'
122 122
123 123 Returns
124 124 -------
125 125 nerr, nfail: number of errors and failures.
126 126 """
127 127
128 128 err_m = re.search(r'^FAILED \(errors=(\d+)\)', txt, re.MULTILINE)
129 129 if err_m:
130 130 nerr = int(err_m.group(1))
131 131 nfail = 0
132 132 return nerr, nfail
133 133
134 134 fail_m = re.search(r'^FAILED \(failures=(\d+)\)', txt, re.MULTILINE)
135 135 if fail_m:
136 136 nerr = 0
137 137 nfail = int(fail_m.group(1))
138 138 return nerr, nfail
139 139
140 140 both_m = re.search(r'^FAILED \(errors=(\d+), failures=(\d+)\)', txt,
141 141 re.MULTILINE)
142 142 if both_m:
143 143 nerr = int(both_m.group(1))
144 144 nfail = int(both_m.group(2))
145 145 return nerr, nfail
146 146
147 147 # If the input didn't match any of these forms, assume no error/failures
148 148 return 0, 0
149 149
150 150
151 151 # So nose doesn't think this is a test
152 152 parse_test_output.__test__ = False
153 153
154 154
155 155 def default_argv():
156 156 """Return a valid default argv for creating testing instances of ipython"""
157 157
158 158 return ['--quick', # so no config file is loaded
159 159 # Other defaults to minimize side effects on stdout
160 160 '--colors=NoColor', '--no-term-title','--no-banner',
161 161 '--autocall=0']
162 162
163 163
164 164 def default_config():
165 165 """Return a config object with good defaults for testing."""
166 166 config = Config()
167 config.InteractiveShell.colors = 'NoColor'
168 config.InteractiveShell.term_title = False,
169 config.InteractiveShell.autocall = 0
167 config.TerminalInteractiveShell.colors = 'NoColor'
168 config.TerminalTerminalInteractiveShell.term_title = False,
169 config.TerminalInteractiveShell.autocall = 0
170 170 return config
171 171
172 172
173 173 def ipexec(fname, options=None):
174 174 """Utility to call 'ipython filename'.
175 175
176 176 Starts IPython witha minimal and safe configuration to make startup as fast
177 177 as possible.
178 178
179 179 Note that this starts IPython in a subprocess!
180 180
181 181 Parameters
182 182 ----------
183 183 fname : str
184 184 Name of file to be executed (should have .py or .ipy extension).
185 185
186 186 options : optional, list
187 187 Extra command-line flags to be passed to IPython.
188 188
189 189 Returns
190 190 -------
191 191 (stdout, stderr) of ipython subprocess.
192 192 """
193 193 if options is None: options = []
194 194
195 195 # For these subprocess calls, eliminate all prompt printing so we only see
196 196 # output from script execution
197 197 prompt_opts = ['--prompt-in1=""', '--prompt-in2=""', '--prompt-out=""']
198 198 cmdargs = ' '.join(default_argv() + prompt_opts + options)
199 199
200 200 _ip = get_ipython()
201 201 test_dir = os.path.dirname(__file__)
202 202
203 203 ipython_cmd = find_cmd('ipython')
204 204 # Absolute path for filename
205 205 full_fname = os.path.join(test_dir, fname)
206 206 full_cmd = '%s %s %s' % (ipython_cmd, cmdargs, full_fname)
207 207 #print >> sys.stderr, 'FULL CMD:', full_cmd # dbg
208 208 return getoutputerror(full_cmd)
209 209
210 210
211 211 def ipexec_validate(fname, expected_out, expected_err='',
212 212 options=None):
213 213 """Utility to call 'ipython filename' and validate output/error.
214 214
215 215 This function raises an AssertionError if the validation fails.
216 216
217 217 Note that this starts IPython in a subprocess!
218 218
219 219 Parameters
220 220 ----------
221 221 fname : str
222 222 Name of the file to be executed (should have .py or .ipy extension).
223 223
224 224 expected_out : str
225 225 Expected stdout of the process.
226 226
227 227 expected_err : optional, str
228 228 Expected stderr of the process.
229 229
230 230 options : optional, list
231 231 Extra command-line flags to be passed to IPython.
232 232
233 233 Returns
234 234 -------
235 235 None
236 236 """
237 237
238 238 import nose.tools as nt
239 239
240 240 out, err = ipexec(fname)
241 241 #print 'OUT', out # dbg
242 242 #print 'ERR', err # dbg
243 243 # If there are any errors, we must check those befor stdout, as they may be
244 244 # more informative than simply having an empty stdout.
245 245 if err:
246 246 if expected_err:
247 247 nt.assert_equals(err.strip(), expected_err.strip())
248 248 else:
249 249 raise ValueError('Running file %r produced error: %r' %
250 250 (fname, err))
251 251 # If no errors or output on stderr was expected, match stdout
252 252 nt.assert_equals(out.strip(), expected_out.strip())
253 253
254 254
255 255 class TempFileMixin(object):
256 256 """Utility class to create temporary Python/IPython files.
257 257
258 258 Meant as a mixin class for test cases."""
259 259
260 260 def mktmp(self, src, ext='.py'):
261 261 """Make a valid python temp file."""
262 262 fname, f = temp_pyfile(src, ext)
263 263 self.tmpfile = f
264 264 self.fname = fname
265 265
266 266 def teardown(self):
267 267 if hasattr(self, 'tmpfile'):
268 268 # If the tmpfile wasn't made because of skipped tests, like in
269 269 # win32, there's nothing to cleanup.
270 270 self.tmpfile.close()
271 271 try:
272 272 os.unlink(self.fname)
273 273 except:
274 274 # On Windows, even though we close the file, we still can't
275 275 # delete it. I have no clue why
276 276 pass
277 277
@@ -1,473 +1,484 b''
1 1 # encoding: utf-8
2 2 """
3 3 Utilities for working with strings and text.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2009 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import __main__
18 18
19 19 import os
20 20 import re
21 21 import shutil
22 22 import types
23 23
24 24 from IPython.external.path import path
25 25
26 26 from IPython.utils.generics import result_display
27 27 from IPython.utils.io import nlprint
28 28 from IPython.utils.data import flatten
29 29
30 30 #-----------------------------------------------------------------------------
31 31 # Code
32 32 #-----------------------------------------------------------------------------
33 33
34 34 StringTypes = types.StringTypes
35 35
36 36
37 37 def unquote_ends(istr):
38 38 """Remove a single pair of quotes from the endpoints of a string."""
39 39
40 40 if not istr:
41 41 return istr
42 42 if (istr[0]=="'" and istr[-1]=="'") or \
43 43 (istr[0]=='"' and istr[-1]=='"'):
44 44 return istr[1:-1]
45 45 else:
46 46 return istr
47 47
48 48
49 49 class LSString(str):
50 50 """String derivative with a special access attributes.
51 51
52 52 These are normal strings, but with the special attributes:
53 53
54 54 .l (or .list) : value as list (split on newlines).
55 55 .n (or .nlstr): original value (the string itself).
56 56 .s (or .spstr): value as whitespace-separated string.
57 57 .p (or .paths): list of path objects
58 58
59 59 Any values which require transformations are computed only once and
60 60 cached.
61 61
62 62 Such strings are very useful to efficiently interact with the shell, which
63 63 typically only understands whitespace-separated options for commands."""
64 64
65 65 def get_list(self):
66 66 try:
67 67 return self.__list
68 68 except AttributeError:
69 69 self.__list = self.split('\n')
70 70 return self.__list
71 71
72 72 l = list = property(get_list)
73 73
74 74 def get_spstr(self):
75 75 try:
76 76 return self.__spstr
77 77 except AttributeError:
78 78 self.__spstr = self.replace('\n',' ')
79 79 return self.__spstr
80 80
81 81 s = spstr = property(get_spstr)
82 82
83 83 def get_nlstr(self):
84 84 return self
85 85
86 86 n = nlstr = property(get_nlstr)
87 87
88 88 def get_paths(self):
89 89 try:
90 90 return self.__paths
91 91 except AttributeError:
92 92 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
93 93 return self.__paths
94 94
95 95 p = paths = property(get_paths)
96 96
97 97
98 98 def print_lsstring(arg):
99 99 """ Prettier (non-repr-like) and more informative printer for LSString """
100 100 print "LSString (.p, .n, .l, .s available). Value:"
101 101 print arg
102 102
103 103
104 104 print_lsstring = result_display.when_type(LSString)(print_lsstring)
105 105
106 106
107 107 class SList(list):
108 108 """List derivative with a special access attributes.
109 109
110 110 These are normal lists, but with the special attributes:
111 111
112 112 .l (or .list) : value as list (the list itself).
113 113 .n (or .nlstr): value as a string, joined on newlines.
114 114 .s (or .spstr): value as a string, joined on spaces.
115 115 .p (or .paths): list of path objects
116 116
117 117 Any values which require transformations are computed only once and
118 118 cached."""
119 119
120 120 def get_list(self):
121 121 return self
122 122
123 123 l = list = property(get_list)
124 124
125 125 def get_spstr(self):
126 126 try:
127 127 return self.__spstr
128 128 except AttributeError:
129 129 self.__spstr = ' '.join(self)
130 130 return self.__spstr
131 131
132 132 s = spstr = property(get_spstr)
133 133
134 134 def get_nlstr(self):
135 135 try:
136 136 return self.__nlstr
137 137 except AttributeError:
138 138 self.__nlstr = '\n'.join(self)
139 139 return self.__nlstr
140 140
141 141 n = nlstr = property(get_nlstr)
142 142
143 143 def get_paths(self):
144 144 try:
145 145 return self.__paths
146 146 except AttributeError:
147 147 self.__paths = [path(p) for p in self if os.path.exists(p)]
148 148 return self.__paths
149 149
150 150 p = paths = property(get_paths)
151 151
152 152 def grep(self, pattern, prune = False, field = None):
153 153 """ Return all strings matching 'pattern' (a regex or callable)
154 154
155 155 This is case-insensitive. If prune is true, return all items
156 156 NOT matching the pattern.
157 157
158 158 If field is specified, the match must occur in the specified
159 159 whitespace-separated field.
160 160
161 161 Examples::
162 162
163 163 a.grep( lambda x: x.startswith('C') )
164 164 a.grep('Cha.*log', prune=1)
165 165 a.grep('chm', field=-1)
166 166 """
167 167
168 168 def match_target(s):
169 169 if field is None:
170 170 return s
171 171 parts = s.split()
172 172 try:
173 173 tgt = parts[field]
174 174 return tgt
175 175 except IndexError:
176 176 return ""
177 177
178 178 if isinstance(pattern, basestring):
179 179 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
180 180 else:
181 181 pred = pattern
182 182 if not prune:
183 183 return SList([el for el in self if pred(match_target(el))])
184 184 else:
185 185 return SList([el for el in self if not pred(match_target(el))])
186 186
187 187 def fields(self, *fields):
188 188 """ Collect whitespace-separated fields from string list
189 189
190 190 Allows quick awk-like usage of string lists.
191 191
192 192 Example data (in var a, created by 'a = !ls -l')::
193 193 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
194 194 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
195 195
196 196 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
197 197 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
198 198 (note the joining by space).
199 199 a.fields(-1) is ['ChangeLog', 'IPython']
200 200
201 201 IndexErrors are ignored.
202 202
203 203 Without args, fields() just split()'s the strings.
204 204 """
205 205 if len(fields) == 0:
206 206 return [el.split() for el in self]
207 207
208 208 res = SList()
209 209 for el in [f.split() for f in self]:
210 210 lineparts = []
211 211
212 212 for fd in fields:
213 213 try:
214 214 lineparts.append(el[fd])
215 215 except IndexError:
216 216 pass
217 217 if lineparts:
218 218 res.append(" ".join(lineparts))
219 219
220 220 return res
221 221
222 222 def sort(self,field= None, nums = False):
223 223 """ sort by specified fields (see fields())
224 224
225 225 Example::
226 226 a.sort(1, nums = True)
227 227
228 228 Sorts a by second field, in numerical order (so that 21 > 3)
229 229
230 230 """
231 231
232 232 #decorate, sort, undecorate
233 233 if field is not None:
234 234 dsu = [[SList([line]).fields(field), line] for line in self]
235 235 else:
236 236 dsu = [[line, line] for line in self]
237 237 if nums:
238 238 for i in range(len(dsu)):
239 239 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
240 240 try:
241 241 n = int(numstr)
242 242 except ValueError:
243 243 n = 0;
244 244 dsu[i][0] = n
245 245
246 246
247 247 dsu.sort()
248 248 return SList([t[1] for t in dsu])
249 249
250 250
251 251 def print_slist(arg):
252 252 """ Prettier (non-repr-like) and more informative printer for SList """
253 253 print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
254 254 if hasattr(arg, 'hideonce') and arg.hideonce:
255 255 arg.hideonce = False
256 256 return
257 257
258 258 nlprint(arg)
259 259
260 260
261 261 print_slist = result_display.when_type(SList)(print_slist)
262 262
263 263
264 264 def esc_quotes(strng):
265 265 """Return the input string with single and double quotes escaped out"""
266 266
267 267 return strng.replace('"','\\"').replace("'","\\'")
268 268
269 269
270 270 def make_quoted_expr(s):
271 271 """Return string s in appropriate quotes, using raw string if possible.
272 272
273 273 XXX - example removed because it caused encoding errors in documentation
274 274 generation. We need a new example that doesn't contain invalid chars.
275 275
276 276 Note the use of raw string and padding at the end to allow trailing
277 277 backslash.
278 278 """
279 279
280 280 tail = ''
281 281 tailpadding = ''
282 282 raw = ''
283 283 if "\\" in s:
284 284 raw = 'r'
285 285 if s.endswith('\\'):
286 286 tail = '[:-1]'
287 287 tailpadding = '_'
288 288 if '"' not in s:
289 289 quote = '"'
290 290 elif "'" not in s:
291 291 quote = "'"
292 292 elif '"""' not in s and not s.endswith('"'):
293 293 quote = '"""'
294 294 elif "'''" not in s and not s.endswith("'"):
295 295 quote = "'''"
296 296 else:
297 297 # give up, backslash-escaped string will do
298 298 return '"%s"' % esc_quotes(s)
299 299 res = raw + quote + s + tailpadding + quote + tail
300 300 return res
301 301
302 302
303 303 def qw(words,flat=0,sep=None,maxsplit=-1):
304 304 """Similar to Perl's qw() operator, but with some more options.
305 305
306 306 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
307 307
308 308 words can also be a list itself, and with flat=1, the output will be
309 309 recursively flattened.
310 310
311 311 Examples:
312 312
313 313 >>> qw('1 2')
314 314 ['1', '2']
315 315
316 316 >>> qw(['a b','1 2',['m n','p q']])
317 317 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
318 318
319 319 >>> qw(['a b','1 2',['m n','p q']],flat=1)
320 320 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
321 321 """
322 322
323 323 if type(words) in StringTypes:
324 324 return [word.strip() for word in words.split(sep,maxsplit)
325 325 if word and not word.isspace() ]
326 326 if flat:
327 327 return flatten(map(qw,words,[1]*len(words)))
328 328 return map(qw,words)
329 329
330 330
331 331 def qwflat(words,sep=None,maxsplit=-1):
332 332 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
333 333 return qw(words,1,sep,maxsplit)
334 334
335 335
336 336 def qw_lol(indata):
337 337 """qw_lol('a b') -> [['a','b']],
338 338 otherwise it's just a call to qw().
339 339
340 340 We need this to make sure the modules_some keys *always* end up as a
341 341 list of lists."""
342 342
343 343 if type(indata) in StringTypes:
344 344 return [qw(indata)]
345 345 else:
346 346 return qw(indata)
347 347
348 348
349 349 def grep(pat,list,case=1):
350 350 """Simple minded grep-like function.
351 351 grep(pat,list) returns occurrences of pat in list, None on failure.
352 352
353 353 It only does simple string matching, with no support for regexps. Use the
354 354 option case=0 for case-insensitive matching."""
355 355
356 356 # This is pretty crude. At least it should implement copying only references
357 357 # to the original data in case it's big. Now it copies the data for output.
358 358 out=[]
359 359 if case:
360 360 for term in list:
361 361 if term.find(pat)>-1: out.append(term)
362 362 else:
363 363 lpat=pat.lower()
364 364 for term in list:
365 365 if term.lower().find(lpat)>-1: out.append(term)
366 366
367 367 if len(out): return out
368 368 else: return None
369 369
370 370
371 371 def dgrep(pat,*opts):
372 372 """Return grep() on dir()+dir(__builtins__).
373 373
374 374 A very common use of grep() when working interactively."""
375 375
376 376 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
377 377
378 378
379 379 def idgrep(pat):
380 380 """Case-insensitive dgrep()"""
381 381
382 382 return dgrep(pat,0)
383 383
384 384
385 385 def igrep(pat,list):
386 386 """Synonym for case-insensitive grep."""
387 387
388 388 return grep(pat,list,case=0)
389 389
390 390
391 391 def indent(str,nspaces=4,ntabs=0):
392 392 """Indent a string a given number of spaces or tabstops.
393 393
394 394 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
395 395 """
396 396 if str is None:
397 397 return
398 398 ind = '\t'*ntabs+' '*nspaces
399 399 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
400 400 if outstr.endswith(os.linesep+ind):
401 401 return outstr[:-len(ind)]
402 402 else:
403 403 return outstr
404 404
405 405 def native_line_ends(filename,backup=1):
406 406 """Convert (in-place) a file to line-ends native to the current OS.
407 407
408 408 If the optional backup argument is given as false, no backup of the
409 409 original file is left. """
410 410
411 411 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
412 412
413 413 bak_filename = filename + backup_suffixes[os.name]
414 414
415 415 original = open(filename).read()
416 416 shutil.copy2(filename,bak_filename)
417 417 try:
418 418 new = open(filename,'wb')
419 419 new.write(os.linesep.join(original.splitlines()))
420 420 new.write(os.linesep) # ALWAYS put an eol at the end of the file
421 421 new.close()
422 422 except:
423 423 os.rename(bak_filename,filename)
424 424 if not backup:
425 425 try:
426 426 os.remove(bak_filename)
427 427 except:
428 428 pass
429 429
430 430
431 431 def list_strings(arg):
432 432 """Always return a list of strings, given a string or list of strings
433 433 as input.
434 434
435 435 :Examples:
436 436
437 437 In [7]: list_strings('A single string')
438 438 Out[7]: ['A single string']
439 439
440 440 In [8]: list_strings(['A single string in a list'])
441 441 Out[8]: ['A single string in a list']
442 442
443 443 In [9]: list_strings(['A','list','of','strings'])
444 444 Out[9]: ['A', 'list', 'of', 'strings']
445 445 """
446 446
447 447 if isinstance(arg,basestring): return [arg]
448 448 else: return arg
449 449
450 450
451 451 def marquee(txt='',width=78,mark='*'):
452 452 """Return the input string centered in a 'marquee'.
453 453
454 454 :Examples:
455 455
456 456 In [16]: marquee('A test',40)
457 457 Out[16]: '**************** A test ****************'
458 458
459 459 In [17]: marquee('A test',40,'-')
460 460 Out[17]: '---------------- A test ----------------'
461 461
462 462 In [18]: marquee('A test',40,' ')
463 463 Out[18]: ' A test '
464 464
465 465 """
466 466 if not txt:
467 467 return (mark*width)[:width]
468 468 nmark = (width-len(txt)-2)/len(mark)/2
469 469 if nmark < 0: nmark =0
470 470 marks = mark*nmark
471 471 return '%s %s %s' % (marks,txt,marks)
472 472
473 473
474 ini_spaces_re = re.compile(r'^(\s+)')
475
476 def num_ini_spaces(strng):
477 """Return the number of initial spaces in a string"""
478
479 ini_spaces = ini_spaces_re.match(strng)
480 if ini_spaces:
481 return ini_spaces.end()
482 else:
483 return 0
484
General Comments 0
You need to be logged in to leave comments. Login now