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