##// END OF EJS Templates
Remove shell hook and system_verbose magic....
Fernando Perez -
Show More
@@ -1,148 +1,144 b''
1 # Get the config being loaded so we can set attributes on it
1 # Get the config being loaded so we can set attributes on it
2 c = get_config()
2 c = get_config()
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Global options
5 # Global options
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7
7
8 # c.Global.display_banner = True
8 # c.Global.display_banner = True
9
9
10 # c.Global.classic = False
10 # c.Global.classic = False
11
11
12 # c.Global.nosep = True
12 # c.Global.nosep = True
13
13
14 # Set this to determine the detail of what is logged at startup.
14 # Set this to determine the detail of what is logged at startup.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 # c.Global.log_level = 20
16 # c.Global.log_level = 20
17
17
18 # This should be a list of importable Python modules that have an
18 # This should be a list of importable Python modules that have an
19 # load_in_ipython(ip) method. This method gets called when the extension
19 # load_in_ipython(ip) method. This method gets called when the extension
20 # is loaded. You can put your extensions anywhere they can be imported
20 # is loaded. You can put your extensions anywhere they can be imported
21 # but we add the extensions subdir of the ipython directory to sys.path
21 # but we add the extensions subdir of the ipython directory to sys.path
22 # during extension loading, so you can put them there as well.
22 # during extension loading, so you can put them there as well.
23 # c.Global.extensions = [
23 # c.Global.extensions = [
24 # 'myextension'
24 # 'myextension'
25 # ]
25 # ]
26
26
27 # These lines are run in IPython in the user's namespace after extensions
27 # These lines are run in IPython in the user's namespace after extensions
28 # are loaded. They can contain full IPython syntax with magics etc.
28 # are loaded. They can contain full IPython syntax with magics etc.
29 # c.Global.exec_lines = [
29 # c.Global.exec_lines = [
30 # 'import numpy',
30 # 'import numpy',
31 # 'a = 10; b = 20',
31 # 'a = 10; b = 20',
32 # '1/0'
32 # '1/0'
33 # ]
33 # ]
34
34
35 # These files are run in IPython in the user's namespace. Files with a .py
35 # These files are run in IPython in the user's namespace. Files with a .py
36 # extension need to be pure Python. Files with a .ipy extension can have
36 # extension need to be pure Python. Files with a .ipy extension can have
37 # custom IPython syntax (like magics, etc.).
37 # custom IPython syntax (like magics, etc.).
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 # c.Global.exec_files = [
39 # c.Global.exec_files = [
40 # 'mycode.py',
40 # 'mycode.py',
41 # 'fancy.ipy'
41 # 'fancy.ipy'
42 # ]
42 # ]
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # InteractiveShell options
45 # InteractiveShell options
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 # c.InteractiveShell.autocall = 1
48 # c.InteractiveShell.autocall = 1
49
49
50 # c.TerminalInteractiveShell.autoedit_syntax = False
50 # c.TerminalInteractiveShell.autoedit_syntax = False
51
51
52 # c.InteractiveShell.autoindent = True
52 # c.InteractiveShell.autoindent = True
53
53
54 # c.InteractiveShell.automagic = False
54 # c.InteractiveShell.automagic = False
55
55
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57
57
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59
59
60 # c.InteractiveShell.cache_size = 1000
60 # c.InteractiveShell.cache_size = 1000
61
61
62 # c.InteractiveShell.colors = 'LightBG'
62 # c.InteractiveShell.colors = 'LightBG'
63
63
64 # c.InteractiveShell.color_info = True
64 # c.InteractiveShell.color_info = True
65
65
66 # c.TerminalInteractiveShell.confirm_exit = True
66 # c.TerminalInteractiveShell.confirm_exit = True
67
67
68 # c.InteractiveShell.deep_reload = False
68 # c.InteractiveShell.deep_reload = False
69
69
70 # c.TerminalInteractiveShell.editor = 'nano'
70 # c.TerminalInteractiveShell.editor = 'nano'
71
71
72 # c.InteractiveShell.logstart = True
72 # c.InteractiveShell.logstart = True
73
73
74 # c.InteractiveShell.logfile = u'ipython_log.py'
74 # c.InteractiveShell.logfile = u'ipython_log.py'
75
75
76 # c.InteractiveShell.logappend = u'mylog.py'
76 # c.InteractiveShell.logappend = u'mylog.py'
77
77
78 # c.InteractiveShell.object_info_string_level = 0
78 # c.InteractiveShell.object_info_string_level = 0
79
79
80 # c.TerminalInteractiveShell.pager = 'less'
80 # c.TerminalInteractiveShell.pager = 'less'
81
81
82 # c.InteractiveShell.pdb = False
82 # c.InteractiveShell.pdb = False
83
83
84 # c.InteractiveShell.pprint = True
84 # c.InteractiveShell.pprint = True
85
85
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
89 # c.InteractiveShell.prompts_pad_left = True
89 # c.InteractiveShell.prompts_pad_left = True
90
90
91 # c.InteractiveShell.quiet = False
91 # c.InteractiveShell.quiet = False
92
92
93 # Readline
93 # Readline
94 # c.InteractiveShell.readline_use = True
94 # c.InteractiveShell.readline_use = True
95
95
96 # c.InteractiveShell.readline_parse_and_bind = [
96 # c.InteractiveShell.readline_parse_and_bind = [
97 # 'tab: complete',
97 # 'tab: complete',
98 # '"\C-l": possible-completions',
98 # '"\C-l": possible-completions',
99 # 'set show-all-if-ambiguous on',
99 # 'set show-all-if-ambiguous on',
100 # '"\C-o": tab-insert',
100 # '"\C-o": tab-insert',
101 # '"\M-i": " "',
101 # '"\M-i": " "',
102 # '"\M-o": "\d\d\d\d"',
102 # '"\M-o": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
104 # '"\C-r": reverse-search-history',
104 # '"\C-r": reverse-search-history',
105 # '"\C-s": forward-search-history',
105 # '"\C-s": forward-search-history',
106 # '"\C-p": history-search-backward',
106 # '"\C-p": history-search-backward',
107 # '"\C-n": history-search-forward',
107 # '"\C-n": history-search-forward',
108 # '"\e[A": history-search-backward',
108 # '"\e[A": history-search-backward',
109 # '"\e[B": history-search-forward',
109 # '"\e[B": history-search-forward',
110 # '"\C-k": kill-line',
110 # '"\C-k": kill-line',
111 # '"\C-u": unix-line-discard',
111 # '"\C-u": unix-line-discard',
112 # ]
112 # ]
113 # c.InteractiveShell.readline_remove_delims = '-/~'
113 # c.InteractiveShell.readline_remove_delims = '-/~'
114 # c.InteractiveShell.readline_merge_completions = True
114 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit__names = 0
115 # c.InteractiveShell.readline_omit__names = 0
116
116
117 # c.TerminalInteractiveShell.screen_length = 0
117 # c.TerminalInteractiveShell.screen_length = 0
118
118
119 # c.InteractiveShell.separate_in = '\n'
119 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
120 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
121 # c.InteractiveShell.separate_out2 = ''
122
122
123 # c.InteractiveShell.system_header = "IPython system call: "
124
125 # c.InteractiveShell.system_verbose = True
126
127 # c.TerminalInteractiveShell.term_title = False
123 # c.TerminalInteractiveShell.term_title = False
128
124
129 # c.InteractiveShell.wildcards_case_sensitive = True
125 # c.InteractiveShell.wildcards_case_sensitive = True
130
126
131 # c.InteractiveShell.xmode = 'Context'
127 # c.InteractiveShell.xmode = 'Context'
132
128
133 #-----------------------------------------------------------------------------
129 #-----------------------------------------------------------------------------
134 # PrefilterManager options
130 # PrefilterManager options
135 #-----------------------------------------------------------------------------
131 #-----------------------------------------------------------------------------
136
132
137 # c.PrefilterManager.multi_line_specials = True
133 # c.PrefilterManager.multi_line_specials = True
138
134
139 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
140 # AliasManager options
136 # AliasManager options
141 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
142
138
143 # Do this to disable all defaults
139 # Do this to disable all defaults
144 # c.AliasManager.default_aliases = []
140 # c.AliasManager.default_aliases = []
145
141
146 # c.AliasManager.user_aliases = [
142 # c.AliasManager.user_aliases = [
147 # ('foo', 'echo Hi')
143 # ('foo', 'echo Hi')
148 # ]
144 # ]
@@ -1,267 +1,259 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 from IPython.core import ipapi
22 from IPython.core import ipapi
23 ip = ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
33 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
34 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
35 """
35 """
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 import os, bisect
44 import os, bisect
45 import sys
45 import sys
46
46
47 from IPython.core.error import TryNext
47 from IPython.core.error import TryNext
48 import IPython.utils.io
48 import IPython.utils.io
49 from IPython.utils.process import shell
50
49
51 # List here all the default hooks. For now it's just the editor functions
50 # List here all the default hooks. For now it's just the editor functions
52 # but over time we'll move here all the public API for user-accessible things.
51 # but over time we'll move here all the public API for user-accessible things.
53
52
54 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
53 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
55 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
54 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
56 'generate_prompt','shell_hook',
55 'generate_prompt', 'show_in_pager','pre_prompt_hook',
57 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
56 'pre_runcode_hook', 'clipboard_get']
58 'clipboard_get']
59
57
60 def editor(self,filename, linenum=None):
58 def editor(self,filename, linenum=None):
61 """Open the default editor at the given filename and linenumber.
59 """Open the default editor at the given filename and linenumber.
62
60
63 This is IPython's default editor hook, you can use it as an example to
61 This is IPython's default editor hook, you can use it as an example to
64 write your own modified one. To set your own editor function as the
62 write your own modified one. To set your own editor function as the
65 new editor hook, call ip.set_hook('editor',yourfunc)."""
63 new editor hook, call ip.set_hook('editor',yourfunc)."""
66
64
67 # IPython configures a default editor at startup by reading $EDITOR from
65 # IPython configures a default editor at startup by reading $EDITOR from
68 # the environment, and falling back on vi (unix) or notepad (win32).
66 # the environment, and falling back on vi (unix) or notepad (win32).
69 editor = self.editor
67 editor = self.editor
70
68
71 # marker for at which line to open the file (for existing objects)
69 # marker for at which line to open the file (for existing objects)
72 if linenum is None or editor=='notepad':
70 if linenum is None or editor=='notepad':
73 linemark = ''
71 linemark = ''
74 else:
72 else:
75 linemark = '+%d' % int(linenum)
73 linemark = '+%d' % int(linenum)
76
74
77 # Enclose in quotes if necessary and legal
75 # Enclose in quotes if necessary and legal
78 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
76 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
79 editor = '"%s"' % editor
77 editor = '"%s"' % editor
80
78
81 # Call the actual editor
79 # Call the actual editor
82 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
80 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
83 raise TryNext()
81 raise TryNext()
84
82
85 import tempfile
83 import tempfile
86 def fix_error_editor(self,filename,linenum,column,msg):
84 def fix_error_editor(self,filename,linenum,column,msg):
87 """Open the editor at the given filename, linenumber, column and
85 """Open the editor at the given filename, linenumber, column and
88 show an error message. This is used for correcting syntax errors.
86 show an error message. This is used for correcting syntax errors.
89 The current implementation only has special support for the VIM editor,
87 The current implementation only has special support for the VIM editor,
90 and falls back on the 'editor' hook if VIM is not used.
88 and falls back on the 'editor' hook if VIM is not used.
91
89
92 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
90 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
93 """
91 """
94 def vim_quickfix_file():
92 def vim_quickfix_file():
95 t = tempfile.NamedTemporaryFile()
93 t = tempfile.NamedTemporaryFile()
96 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
94 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
97 t.flush()
95 t.flush()
98 return t
96 return t
99 if os.path.basename(self.editor) != 'vim':
97 if os.path.basename(self.editor) != 'vim':
100 self.hooks.editor(filename,linenum)
98 self.hooks.editor(filename,linenum)
101 return
99 return
102 t = vim_quickfix_file()
100 t = vim_quickfix_file()
103 try:
101 try:
104 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
102 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
105 raise TryNext()
103 raise TryNext()
106 finally:
104 finally:
107 t.close()
105 t.close()
108
106
109
107
110 def synchronize_with_editor(self, filename, linenum, column):
108 def synchronize_with_editor(self, filename, linenum, column):
111 pass
109 pass
112
110
113
111
114 class CommandChainDispatcher:
112 class CommandChainDispatcher:
115 """ Dispatch calls to a chain of commands until some func can handle it
113 """ Dispatch calls to a chain of commands until some func can handle it
116
114
117 Usage: instantiate, execute "add" to add commands (with optional
115 Usage: instantiate, execute "add" to add commands (with optional
118 priority), execute normally via f() calling mechanism.
116 priority), execute normally via f() calling mechanism.
119
117
120 """
118 """
121 def __init__(self,commands=None):
119 def __init__(self,commands=None):
122 if commands is None:
120 if commands is None:
123 self.chain = []
121 self.chain = []
124 else:
122 else:
125 self.chain = commands
123 self.chain = commands
126
124
127
125
128 def __call__(self,*args, **kw):
126 def __call__(self,*args, **kw):
129 """ Command chain is called just like normal func.
127 """ Command chain is called just like normal func.
130
128
131 This will call all funcs in chain with the same args as were given to this
129 This will call all funcs in chain with the same args as were given to this
132 function, and return the result of first func that didn't raise
130 function, and return the result of first func that didn't raise
133 TryNext """
131 TryNext """
134
132
135 for prio,cmd in self.chain:
133 for prio,cmd in self.chain:
136 #print "prio",prio,"cmd",cmd #dbg
134 #print "prio",prio,"cmd",cmd #dbg
137 try:
135 try:
138 return cmd(*args, **kw)
136 return cmd(*args, **kw)
139 except TryNext, exc:
137 except TryNext, exc:
140 if exc.args or exc.kwargs:
138 if exc.args or exc.kwargs:
141 args = exc.args
139 args = exc.args
142 kw = exc.kwargs
140 kw = exc.kwargs
143 # if no function will accept it, raise TryNext up to the caller
141 # if no function will accept it, raise TryNext up to the caller
144 raise TryNext
142 raise TryNext
145
143
146 def __str__(self):
144 def __str__(self):
147 return str(self.chain)
145 return str(self.chain)
148
146
149 def add(self, func, priority=0):
147 def add(self, func, priority=0):
150 """ Add a func to the cmd chain with given priority """
148 """ Add a func to the cmd chain with given priority """
151 bisect.insort(self.chain,(priority,func))
149 bisect.insort(self.chain,(priority,func))
152
150
153 def __iter__(self):
151 def __iter__(self):
154 """ Return all objects in chain.
152 """ Return all objects in chain.
155
153
156 Handy if the objects are not callable.
154 Handy if the objects are not callable.
157 """
155 """
158 return iter(self.chain)
156 return iter(self.chain)
159
157
160
158
161 def result_display(self,arg):
159 def result_display(self,arg):
162 """ Default display hook.
160 """ Default display hook.
163
161
164 Called for displaying the result to the user.
162 Called for displaying the result to the user.
165 """
163 """
166
164
167 if self.pprint:
165 if self.pprint:
168 out = pformat(arg)
166 out = pformat(arg)
169 if '\n' in out:
167 if '\n' in out:
170 # So that multi-line strings line up with the left column of
168 # So that multi-line strings line up with the left column of
171 # the screen, instead of having the output prompt mess up
169 # the screen, instead of having the output prompt mess up
172 # their first line.
170 # their first line.
173 IPython.utils.io.Term.cout.write('\n')
171 IPython.utils.io.Term.cout.write('\n')
174 print >>IPython.utils.io.Term.cout, out
172 print >>IPython.utils.io.Term.cout, out
175 else:
173 else:
176 # By default, the interactive prompt uses repr() to display results,
174 # By default, the interactive prompt uses repr() to display results,
177 # so we should honor this. Users who'd rather use a different
175 # so we should honor this. Users who'd rather use a different
178 # mechanism can easily override this hook.
176 # mechanism can easily override this hook.
179 print >>IPython.utils.io.Term.cout, repr(arg)
177 print >>IPython.utils.io.Term.cout, repr(arg)
180 # the default display hook doesn't manipulate the value to put in history
178 # the default display hook doesn't manipulate the value to put in history
181 return None
179 return None
182
180
183
181
184 def input_prefilter(self,line):
182 def input_prefilter(self,line):
185 """ Default input prefilter
183 """ Default input prefilter
186
184
187 This returns the line as unchanged, so that the interpreter
185 This returns the line as unchanged, so that the interpreter
188 knows that nothing was done and proceeds with "classic" prefiltering
186 knows that nothing was done and proceeds with "classic" prefiltering
189 (%magics, !shell commands etc.).
187 (%magics, !shell commands etc.).
190
188
191 Note that leading whitespace is not passed to this hook. Prefilter
189 Note that leading whitespace is not passed to this hook. Prefilter
192 can't alter indentation.
190 can't alter indentation.
193
191
194 """
192 """
195 #print "attempt to rewrite",line #dbg
193 #print "attempt to rewrite",line #dbg
196 return line
194 return line
197
195
198
196
199 def shutdown_hook(self):
197 def shutdown_hook(self):
200 """ default shutdown hook
198 """ default shutdown hook
201
199
202 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
200 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
203 """
201 """
204
202
205 #print "default shutdown hook ok" # dbg
203 #print "default shutdown hook ok" # dbg
206 return
204 return
207
205
208
206
209 def late_startup_hook(self):
207 def late_startup_hook(self):
210 """ Executed after ipython has been constructed and configured
208 """ Executed after ipython has been constructed and configured
211
209
212 """
210 """
213 #print "default startup hook ok" # dbg
211 #print "default startup hook ok" # dbg
214
212
215
213
216 def generate_prompt(self, is_continuation):
214 def generate_prompt(self, is_continuation):
217 """ calculate and return a string with the prompt to display """
215 """ calculate and return a string with the prompt to display """
218 if is_continuation:
216 if is_continuation:
219 return str(self.displayhook.prompt2)
217 return str(self.displayhook.prompt2)
220 return str(self.displayhook.prompt1)
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 def show_in_pager(self,s):
221 def show_in_pager(self,s):
230 """ Run a string through pager """
222 """ Run a string through pager """
231 # raising TryNext here will use the default paging functionality
223 # raising TryNext here will use the default paging functionality
232 raise TryNext
224 raise TryNext
233
225
234
226
235 def pre_prompt_hook(self):
227 def pre_prompt_hook(self):
236 """ Run before displaying the next prompt
228 """ Run before displaying the next prompt
237
229
238 Use this e.g. to display output from asynchronous operations (in order
230 Use this e.g. to display output from asynchronous operations (in order
239 to not mess up text entry)
231 to not mess up text entry)
240 """
232 """
241
233
242 return None
234 return None
243
235
244
236
245 def pre_runcode_hook(self):
237 def pre_runcode_hook(self):
246 """ Executed before running the (prefiltered) code in IPython """
238 """ Executed before running the (prefiltered) code in IPython """
247 return None
239 return None
248
240
249
241
250 def clipboard_get(self):
242 def clipboard_get(self):
251 """ Get text from the clipboard.
243 """ Get text from the clipboard.
252 """
244 """
253 from IPython.lib.clipboard import (
245 from IPython.lib.clipboard import (
254 osx_clipboard_get, tkinter_clipboard_get,
246 osx_clipboard_get, tkinter_clipboard_get,
255 win32_clipboard_get
247 win32_clipboard_get
256 )
248 )
257 if sys.platform == 'win32':
249 if sys.platform == 'win32':
258 chain = [win32_clipboard_get, tkinter_clipboard_get]
250 chain = [win32_clipboard_get, tkinter_clipboard_get]
259 elif sys.platform == 'darwin':
251 elif sys.platform == 'darwin':
260 chain = [osx_clipboard_get, tkinter_clipboard_get]
252 chain = [osx_clipboard_get, tkinter_clipboard_get]
261 else:
253 else:
262 chain = [tkinter_clipboard_get]
254 chain = [tkinter_clipboard_get]
263 dispatcher = CommandChainDispatcher()
255 dispatcher = CommandChainDispatcher()
264 for func in chain:
256 for func in chain:
265 dispatcher.add(func)
257 dispatcher.add(func)
266 text = dispatcher()
258 text = dispatcher()
267 return text
259 return text
@@ -1,2156 +1,2162 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import abc
21 import abc
22 import codeop
22 import codeop
23 import exceptions
23 import exceptions
24 import new
24 import new
25 import os
25 import os
26 import re
26 import re
27 import string
27 import string
28 import sys
28 import sys
29 import tempfile
29 import tempfile
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33 from IPython.core import debugger, oinspect
33 from IPython.core import debugger, oinspect
34 from IPython.core import history as ipcorehist
34 from IPython.core import history as ipcorehist
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import ultratb
38 from IPython.core import ultratb
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.displayhook import DisplayHook
42 from IPython.core.displayhook import DisplayHook
43 from IPython.core.error import UsageError
43 from IPython.core.error import UsageError
44 from IPython.core.extensions import ExtensionManager
44 from IPython.core.extensions import ExtensionManager
45 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
45 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
46 from IPython.core.inputlist import InputList
46 from IPython.core.inputlist import InputList
47 from IPython.core.logger import Logger
47 from IPython.core.logger import Logger
48 from IPython.core.magic import Magic
48 from IPython.core.magic import Magic
49 from IPython.core.payload import PayloadManager
49 from IPython.core.payload import PayloadManager
50 from IPython.core.plugin import PluginManager
50 from IPython.core.plugin import PluginManager
51 from IPython.core.prefilter import PrefilterManager
51 from IPython.core.prefilter import PrefilterManager
52 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
53 from IPython.utils import PyColorize
53 from IPython.utils import PyColorize
54 from IPython.utils import io
54 from IPython.utils import io
55 from IPython.utils import pickleshare
55 from IPython.utils import pickleshare
56 from IPython.utils.doctestreload import doctest_reload
56 from IPython.utils.doctestreload import doctest_reload
57 from IPython.utils.io import ask_yes_no, rprint
57 from IPython.utils.io import ask_yes_no, rprint
58 from IPython.utils.ipstruct import Struct
58 from IPython.utils.ipstruct import Struct
59 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
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 from IPython.utils.strdispatch import StrDispatch
61 from IPython.utils.strdispatch import StrDispatch
62 from IPython.utils.syspathcontext import prepended_to_syspath
62 from IPython.utils.syspathcontext import prepended_to_syspath
63 from IPython.utils.text import num_ini_spaces
63 from IPython.utils.text import num_ini_spaces
64 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
64 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
65 List, Unicode, Instance, Type)
65 List, Unicode, Instance, Type)
66 from IPython.utils.warn import warn, error, fatal
66 from IPython.utils.warn import warn, error, fatal
67 import IPython.core.hooks
67 import IPython.core.hooks
68
68
69 # from IPython.utils import growl
69 # from IPython.utils import growl
70 # growl.start("IPython")
70 # growl.start("IPython")
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Globals
73 # Globals
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Utilities
80 # Utilities
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
85 raw_input_original = raw_input
86
86
87 def softspace(file, newvalue):
87 def softspace(file, newvalue):
88 """Copied from code.py, to remove the dependency"""
88 """Copied from code.py, to remove the dependency"""
89
89
90 oldvalue = 0
90 oldvalue = 0
91 try:
91 try:
92 oldvalue = file.softspace
92 oldvalue = file.softspace
93 except AttributeError:
93 except AttributeError:
94 pass
94 pass
95 try:
95 try:
96 file.softspace = newvalue
96 file.softspace = newvalue
97 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
98 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
99 pass
99 pass
100 return oldvalue
100 return oldvalue
101
101
102
102
103 def no_op(*a, **kw): pass
103 def no_op(*a, **kw): pass
104
104
105 class SpaceInInput(exceptions.Exception): pass
105 class SpaceInInput(exceptions.Exception): pass
106
106
107 class Bunch: pass
107 class Bunch: pass
108
108
109
109
110 def get_default_colors():
110 def get_default_colors():
111 if sys.platform=='darwin':
111 if sys.platform=='darwin':
112 return "LightBG"
112 return "LightBG"
113 elif os.name=='nt':
113 elif os.name=='nt':
114 return 'Linux'
114 return 'Linux'
115 else:
115 else:
116 return 'Linux'
116 return 'Linux'
117
117
118
118
119 class SeparateStr(Str):
119 class SeparateStr(Str):
120 """A Str subclass to validate separate_in, separate_out, etc.
120 """A Str subclass to validate separate_in, separate_out, etc.
121
121
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 """
123 """
124
124
125 def validate(self, obj, value):
125 def validate(self, obj, value):
126 if value == '0': value = ''
126 if value == '0': value = ''
127 value = value.replace('\\n','\n')
127 value = value.replace('\\n','\n')
128 return super(SeparateStr, self).validate(obj, value)
128 return super(SeparateStr, self).validate(obj, value)
129
129
130 class MultipleInstanceError(Exception):
130 class MultipleInstanceError(Exception):
131 pass
131 pass
132
132
133
133
134 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
135 # Main IPython class
135 # Main IPython class
136 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
137
137
138
138
139 class InteractiveShell(Configurable, Magic):
139 class InteractiveShell(Configurable, Magic):
140 """An enhanced, interactive shell for Python."""
140 """An enhanced, interactive shell for Python."""
141
141
142 _instance = None
142 _instance = None
143 autocall = Enum((0,1,2), default_value=1, config=True)
143 autocall = Enum((0,1,2), default_value=1, config=True)
144 # TODO: remove all autoindent logic and put into frontends.
144 # TODO: remove all autoindent logic and put into frontends.
145 # We can't do this yet because even runlines uses the autoindent.
145 # We can't do this yet because even runlines uses the autoindent.
146 autoindent = CBool(True, config=True)
146 autoindent = CBool(True, config=True)
147 automagic = CBool(True, config=True)
147 automagic = CBool(True, config=True)
148 cache_size = Int(1000, config=True)
148 cache_size = Int(1000, config=True)
149 color_info = CBool(True, config=True)
149 color_info = CBool(True, config=True)
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 default_value=get_default_colors(), config=True)
151 default_value=get_default_colors(), config=True)
152 debug = CBool(False, config=True)
152 debug = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
154 displayhook_class = Type(DisplayHook)
154 displayhook_class = Type(DisplayHook)
155 filename = Str("<ipython console>")
155 filename = Str("<ipython console>")
156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 logstart = CBool(False, config=True)
157 logstart = CBool(False, config=True)
158 logfile = Str('', config=True)
158 logfile = Str('', config=True)
159 logappend = Str('', config=True)
159 logappend = Str('', config=True)
160 object_info_string_level = Enum((0,1,2), default_value=0,
160 object_info_string_level = Enum((0,1,2), default_value=0,
161 config=True)
161 config=True)
162 pdb = CBool(False, config=True)
162 pdb = CBool(False, config=True)
163 pprint = CBool(True, config=True)
163 pprint = CBool(True, config=True)
164 profile = Str('', config=True)
164 profile = Str('', config=True)
165 prompt_in1 = Str('In [\\#]: ', config=True)
165 prompt_in1 = Str('In [\\#]: ', config=True)
166 prompt_in2 = Str(' .\\D.: ', config=True)
166 prompt_in2 = Str(' .\\D.: ', config=True)
167 prompt_out = Str('Out[\\#]: ', config=True)
167 prompt_out = Str('Out[\\#]: ', config=True)
168 prompts_pad_left = CBool(True, config=True)
168 prompts_pad_left = CBool(True, config=True)
169 quiet = CBool(False, config=True)
169 quiet = CBool(False, config=True)
170
170
171 # The readline stuff will eventually be moved to the terminal subclass
171 # The readline stuff will eventually be moved to the terminal subclass
172 # but for now, we can't do that as readline is welded in everywhere.
172 # but for now, we can't do that as readline is welded in everywhere.
173 readline_use = CBool(True, config=True)
173 readline_use = CBool(True, config=True)
174 readline_merge_completions = CBool(True, config=True)
174 readline_merge_completions = CBool(True, config=True)
175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
176 readline_remove_delims = Str('-/~', config=True)
176 readline_remove_delims = Str('-/~', config=True)
177 readline_parse_and_bind = List([
177 readline_parse_and_bind = List([
178 'tab: complete',
178 'tab: complete',
179 '"\C-l": clear-screen',
179 '"\C-l": clear-screen',
180 'set show-all-if-ambiguous on',
180 'set show-all-if-ambiguous on',
181 '"\C-o": tab-insert',
181 '"\C-o": tab-insert',
182 '"\M-i": " "',
182 '"\M-i": " "',
183 '"\M-o": "\d\d\d\d"',
183 '"\M-o": "\d\d\d\d"',
184 '"\M-I": "\d\d\d\d"',
184 '"\M-I": "\d\d\d\d"',
185 '"\C-r": reverse-search-history',
185 '"\C-r": reverse-search-history',
186 '"\C-s": forward-search-history',
186 '"\C-s": forward-search-history',
187 '"\C-p": history-search-backward',
187 '"\C-p": history-search-backward',
188 '"\C-n": history-search-forward',
188 '"\C-n": history-search-forward',
189 '"\e[A": history-search-backward',
189 '"\e[A": history-search-backward',
190 '"\e[B": history-search-forward',
190 '"\e[B": history-search-forward',
191 '"\C-k": kill-line',
191 '"\C-k": kill-line',
192 '"\C-u": unix-line-discard',
192 '"\C-u": unix-line-discard',
193 ], allow_none=False, config=True)
193 ], allow_none=False, config=True)
194
194
195 # TODO: this part of prompt management should be moved to the frontends.
195 # TODO: this part of prompt management should be moved to the frontends.
196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
197 separate_in = SeparateStr('\n', config=True)
197 separate_in = SeparateStr('\n', config=True)
198 separate_out = SeparateStr('', config=True)
198 separate_out = SeparateStr('', config=True)
199 separate_out2 = SeparateStr('', config=True)
199 separate_out2 = SeparateStr('', config=True)
200 system_header = Str('IPython system call: ', config=True)
201 system_verbose = CBool(False, config=True)
202 wildcards_case_sensitive = CBool(True, config=True)
200 wildcards_case_sensitive = CBool(True, config=True)
203 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
204 default_value='Context', config=True)
202 default_value='Context', config=True)
205
203
206 # Subcomponents of InteractiveShell
204 # Subcomponents of InteractiveShell
207 alias_manager = Instance('IPython.core.alias.AliasManager')
205 alias_manager = Instance('IPython.core.alias.AliasManager')
208 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
209 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
210 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
211 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
212 plugin_manager = Instance('IPython.core.plugin.PluginManager')
210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
213 payload_manager = Instance('IPython.core.payload.PayloadManager')
211 payload_manager = Instance('IPython.core.payload.PayloadManager')
214
212
215 def __init__(self, config=None, ipython_dir=None,
213 def __init__(self, config=None, ipython_dir=None,
216 user_ns=None, user_global_ns=None,
214 user_ns=None, user_global_ns=None,
217 custom_exceptions=((),None)):
215 custom_exceptions=((),None)):
218
216
219 # This is where traits with a config_key argument are updated
217 # This is where traits with a config_key argument are updated
220 # from the values on config.
218 # from the values on config.
221 super(InteractiveShell, self).__init__(config=config)
219 super(InteractiveShell, self).__init__(config=config)
222
220
223 # These are relatively independent and stateless
221 # These are relatively independent and stateless
224 self.init_ipython_dir(ipython_dir)
222 self.init_ipython_dir(ipython_dir)
225 self.init_instance_attrs()
223 self.init_instance_attrs()
226
224
227 # Create namespaces (user_ns, user_global_ns, etc.)
225 # Create namespaces (user_ns, user_global_ns, etc.)
228 self.init_create_namespaces(user_ns, user_global_ns)
226 self.init_create_namespaces(user_ns, user_global_ns)
229 # This has to be done after init_create_namespaces because it uses
227 # This has to be done after init_create_namespaces because it uses
230 # something in self.user_ns, but before init_sys_modules, which
228 # something in self.user_ns, but before init_sys_modules, which
231 # is the first thing to modify sys.
229 # is the first thing to modify sys.
232 # TODO: When we override sys.stdout and sys.stderr before this class
230 # TODO: When we override sys.stdout and sys.stderr before this class
233 # is created, we are saving the overridden ones here. Not sure if this
231 # is created, we are saving the overridden ones here. Not sure if this
234 # is what we want to do.
232 # is what we want to do.
235 self.save_sys_module_state()
233 self.save_sys_module_state()
236 self.init_sys_modules()
234 self.init_sys_modules()
237
235
238 self.init_history()
236 self.init_history()
239 self.init_encoding()
237 self.init_encoding()
240 self.init_prefilter()
238 self.init_prefilter()
241
239
242 Magic.__init__(self, self)
240 Magic.__init__(self, self)
243
241
244 self.init_syntax_highlighting()
242 self.init_syntax_highlighting()
245 self.init_hooks()
243 self.init_hooks()
246 self.init_pushd_popd_magic()
244 self.init_pushd_popd_magic()
247 # self.init_traceback_handlers use to be here, but we moved it below
245 # self.init_traceback_handlers use to be here, but we moved it below
248 # because it and init_io have to come after init_readline.
246 # because it and init_io have to come after init_readline.
249 self.init_user_ns()
247 self.init_user_ns()
250 self.init_logger()
248 self.init_logger()
251 self.init_alias()
249 self.init_alias()
252 self.init_builtins()
250 self.init_builtins()
253
251
254 # pre_config_initialization
252 # pre_config_initialization
255 self.init_shadow_hist()
253 self.init_shadow_hist()
256
254
257 # The next section should contain averything that was in ipmaker.
255 # The next section should contain averything that was in ipmaker.
258 self.init_logstart()
256 self.init_logstart()
259
257
260 # The following was in post_config_initialization
258 # The following was in post_config_initialization
261 self.init_inspector()
259 self.init_inspector()
262 # init_readline() must come before init_io(), because init_io uses
260 # init_readline() must come before init_io(), because init_io uses
263 # readline related things.
261 # readline related things.
264 self.init_readline()
262 self.init_readline()
265 # TODO: init_io() needs to happen before init_traceback handlers
263 # TODO: init_io() needs to happen before init_traceback handlers
266 # because the traceback handlers hardcode the stdout/stderr streams.
264 # because the traceback handlers hardcode the stdout/stderr streams.
267 # This logic in in debugger.Pdb and should eventually be changed.
265 # This logic in in debugger.Pdb and should eventually be changed.
268 self.init_io()
266 self.init_io()
269 self.init_traceback_handlers(custom_exceptions)
267 self.init_traceback_handlers(custom_exceptions)
270 self.init_prompts()
268 self.init_prompts()
271 self.init_displayhook()
269 self.init_displayhook()
272 self.init_reload_doctest()
270 self.init_reload_doctest()
273 self.init_magics()
271 self.init_magics()
274 self.init_pdb()
272 self.init_pdb()
275 self.init_extension_manager()
273 self.init_extension_manager()
276 self.init_plugin_manager()
274 self.init_plugin_manager()
277 self.init_payload()
275 self.init_payload()
278 self.hooks.late_startup_hook()
276 self.hooks.late_startup_hook()
279
277
280 @classmethod
278 @classmethod
281 def instance(cls, *args, **kwargs):
279 def instance(cls, *args, **kwargs):
282 """Returns a global InteractiveShell instance."""
280 """Returns a global InteractiveShell instance."""
283 if cls._instance is None:
281 if cls._instance is None:
284 inst = cls(*args, **kwargs)
282 inst = cls(*args, **kwargs)
285 # Now make sure that the instance will also be returned by
283 # Now make sure that the instance will also be returned by
286 # the subclasses instance attribute.
284 # the subclasses instance attribute.
287 for subclass in cls.mro():
285 for subclass in cls.mro():
288 if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell):
286 if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell):
289 subclass._instance = inst
287 subclass._instance = inst
290 else:
288 else:
291 break
289 break
292 if isinstance(cls._instance, cls):
290 if isinstance(cls._instance, cls):
293 return cls._instance
291 return cls._instance
294 else:
292 else:
295 raise MultipleInstanceError(
293 raise MultipleInstanceError(
296 'Multiple incompatible subclass instances of '
294 'Multiple incompatible subclass instances of '
297 'InteractiveShell are being created.'
295 'InteractiveShell are being created.'
298 )
296 )
299
297
300 @classmethod
298 @classmethod
301 def initialized(cls):
299 def initialized(cls):
302 return hasattr(cls, "_instance")
300 return hasattr(cls, "_instance")
303
301
304 def get_ipython(self):
302 def get_ipython(self):
305 """Return the currently running IPython instance."""
303 """Return the currently running IPython instance."""
306 return self
304 return self
307
305
308 #-------------------------------------------------------------------------
306 #-------------------------------------------------------------------------
309 # Trait changed handlers
307 # Trait changed handlers
310 #-------------------------------------------------------------------------
308 #-------------------------------------------------------------------------
311
309
312 def _ipython_dir_changed(self, name, new):
310 def _ipython_dir_changed(self, name, new):
313 if not os.path.isdir(new):
311 if not os.path.isdir(new):
314 os.makedirs(new, mode = 0777)
312 os.makedirs(new, mode = 0777)
315
313
316 def set_autoindent(self,value=None):
314 def set_autoindent(self,value=None):
317 """Set the autoindent flag, checking for readline support.
315 """Set the autoindent flag, checking for readline support.
318
316
319 If called with no arguments, it acts as a toggle."""
317 If called with no arguments, it acts as a toggle."""
320
318
321 if not self.has_readline:
319 if not self.has_readline:
322 if os.name == 'posix':
320 if os.name == 'posix':
323 warn("The auto-indent feature requires the readline library")
321 warn("The auto-indent feature requires the readline library")
324 self.autoindent = 0
322 self.autoindent = 0
325 return
323 return
326 if value is None:
324 if value is None:
327 self.autoindent = not self.autoindent
325 self.autoindent = not self.autoindent
328 else:
326 else:
329 self.autoindent = value
327 self.autoindent = value
330
328
331 #-------------------------------------------------------------------------
329 #-------------------------------------------------------------------------
332 # init_* methods called by __init__
330 # init_* methods called by __init__
333 #-------------------------------------------------------------------------
331 #-------------------------------------------------------------------------
334
332
335 def init_ipython_dir(self, ipython_dir):
333 def init_ipython_dir(self, ipython_dir):
336 if ipython_dir is not None:
334 if ipython_dir is not None:
337 self.ipython_dir = ipython_dir
335 self.ipython_dir = ipython_dir
338 self.config.Global.ipython_dir = self.ipython_dir
336 self.config.Global.ipython_dir = self.ipython_dir
339 return
337 return
340
338
341 if hasattr(self.config.Global, 'ipython_dir'):
339 if hasattr(self.config.Global, 'ipython_dir'):
342 self.ipython_dir = self.config.Global.ipython_dir
340 self.ipython_dir = self.config.Global.ipython_dir
343 else:
341 else:
344 self.ipython_dir = get_ipython_dir()
342 self.ipython_dir = get_ipython_dir()
345
343
346 # All children can just read this
344 # All children can just read this
347 self.config.Global.ipython_dir = self.ipython_dir
345 self.config.Global.ipython_dir = self.ipython_dir
348
346
349 def init_instance_attrs(self):
347 def init_instance_attrs(self):
350 self.more = False
348 self.more = False
351
349
352 # command compiler
350 # command compiler
353 self.compile = codeop.CommandCompiler()
351 self.compile = codeop.CommandCompiler()
354
352
355 # User input buffer
353 # User input buffer
356 self.buffer = []
354 self.buffer = []
357
355
358 # Make an empty namespace, which extension writers can rely on both
356 # Make an empty namespace, which extension writers can rely on both
359 # existing and NEVER being used by ipython itself. This gives them a
357 # existing and NEVER being used by ipython itself. This gives them a
360 # convenient location for storing additional information and state
358 # convenient location for storing additional information and state
361 # their extensions may require, without fear of collisions with other
359 # their extensions may require, without fear of collisions with other
362 # ipython names that may develop later.
360 # ipython names that may develop later.
363 self.meta = Struct()
361 self.meta = Struct()
364
362
365 # Object variable to store code object waiting execution. This is
363 # Object variable to store code object waiting execution. This is
366 # used mainly by the multithreaded shells, but it can come in handy in
364 # used mainly by the multithreaded shells, but it can come in handy in
367 # other situations. No need to use a Queue here, since it's a single
365 # other situations. No need to use a Queue here, since it's a single
368 # item which gets cleared once run.
366 # item which gets cleared once run.
369 self.code_to_run = None
367 self.code_to_run = None
370
368
371 # Temporary files used for various purposes. Deleted at exit.
369 # Temporary files used for various purposes. Deleted at exit.
372 self.tempfiles = []
370 self.tempfiles = []
373
371
374 # Keep track of readline usage (later set by init_readline)
372 # Keep track of readline usage (later set by init_readline)
375 self.has_readline = False
373 self.has_readline = False
376
374
377 # keep track of where we started running (mainly for crash post-mortem)
375 # keep track of where we started running (mainly for crash post-mortem)
378 # This is not being used anywhere currently.
376 # This is not being used anywhere currently.
379 self.starting_dir = os.getcwd()
377 self.starting_dir = os.getcwd()
380
378
381 # Indentation management
379 # Indentation management
382 self.indent_current_nsp = 0
380 self.indent_current_nsp = 0
383
381
384 def init_encoding(self):
382 def init_encoding(self):
385 # Get system encoding at startup time. Certain terminals (like Emacs
383 # Get system encoding at startup time. Certain terminals (like Emacs
386 # under Win32 have it set to None, and we need to have a known valid
384 # under Win32 have it set to None, and we need to have a known valid
387 # encoding to use in the raw_input() method
385 # encoding to use in the raw_input() method
388 try:
386 try:
389 self.stdin_encoding = sys.stdin.encoding or 'ascii'
387 self.stdin_encoding = sys.stdin.encoding or 'ascii'
390 except AttributeError:
388 except AttributeError:
391 self.stdin_encoding = 'ascii'
389 self.stdin_encoding = 'ascii'
392
390
393 def init_syntax_highlighting(self):
391 def init_syntax_highlighting(self):
394 # Python source parser/formatter for syntax highlighting
392 # Python source parser/formatter for syntax highlighting
395 pyformat = PyColorize.Parser().format
393 pyformat = PyColorize.Parser().format
396 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
394 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
397
395
398 def init_pushd_popd_magic(self):
396 def init_pushd_popd_magic(self):
399 # for pushd/popd management
397 # for pushd/popd management
400 try:
398 try:
401 self.home_dir = get_home_dir()
399 self.home_dir = get_home_dir()
402 except HomeDirError, msg:
400 except HomeDirError, msg:
403 fatal(msg)
401 fatal(msg)
404
402
405 self.dir_stack = []
403 self.dir_stack = []
406
404
407 def init_logger(self):
405 def init_logger(self):
408 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
406 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
409 # local shortcut, this is used a LOT
407 # local shortcut, this is used a LOT
410 self.log = self.logger.log
408 self.log = self.logger.log
411
409
412 def init_logstart(self):
410 def init_logstart(self):
413 if self.logappend:
411 if self.logappend:
414 self.magic_logstart(self.logappend + ' append')
412 self.magic_logstart(self.logappend + ' append')
415 elif self.logfile:
413 elif self.logfile:
416 self.magic_logstart(self.logfile)
414 self.magic_logstart(self.logfile)
417 elif self.logstart:
415 elif self.logstart:
418 self.magic_logstart()
416 self.magic_logstart()
419
417
420 def init_builtins(self):
418 def init_builtins(self):
421 self.builtin_trap = BuiltinTrap(shell=self)
419 self.builtin_trap = BuiltinTrap(shell=self)
422
420
423 def init_inspector(self):
421 def init_inspector(self):
424 # Object inspector
422 # Object inspector
425 self.inspector = oinspect.Inspector(oinspect.InspectColors,
423 self.inspector = oinspect.Inspector(oinspect.InspectColors,
426 PyColorize.ANSICodeColors,
424 PyColorize.ANSICodeColors,
427 'NoColor',
425 'NoColor',
428 self.object_info_string_level)
426 self.object_info_string_level)
429
427
430 def init_io(self):
428 def init_io(self):
431 import IPython.utils.io
429 import IPython.utils.io
432 if sys.platform == 'win32' and self.has_readline:
430 if sys.platform == 'win32' and self.has_readline:
433 Term = io.IOTerm(
431 Term = io.IOTerm(
434 cout=self.readline._outputfile,cerr=self.readline._outputfile
432 cout=self.readline._outputfile,cerr=self.readline._outputfile
435 )
433 )
436 else:
434 else:
437 Term = io.IOTerm()
435 Term = io.IOTerm()
438 io.Term = Term
436 io.Term = Term
439
437
440 def init_prompts(self):
438 def init_prompts(self):
441 # TODO: This is a pass for now because the prompts are managed inside
439 # TODO: This is a pass for now because the prompts are managed inside
442 # the DisplayHook. Once there is a separate prompt manager, this
440 # the DisplayHook. Once there is a separate prompt manager, this
443 # will initialize that object and all prompt related information.
441 # will initialize that object and all prompt related information.
444 pass
442 pass
445
443
446 def init_displayhook(self):
444 def init_displayhook(self):
447 # Initialize displayhook, set in/out prompts and printing system
445 # Initialize displayhook, set in/out prompts and printing system
448 self.displayhook = self.displayhook_class(
446 self.displayhook = self.displayhook_class(
449 shell=self,
447 shell=self,
450 cache_size=self.cache_size,
448 cache_size=self.cache_size,
451 input_sep = self.separate_in,
449 input_sep = self.separate_in,
452 output_sep = self.separate_out,
450 output_sep = self.separate_out,
453 output_sep2 = self.separate_out2,
451 output_sep2 = self.separate_out2,
454 ps1 = self.prompt_in1,
452 ps1 = self.prompt_in1,
455 ps2 = self.prompt_in2,
453 ps2 = self.prompt_in2,
456 ps_out = self.prompt_out,
454 ps_out = self.prompt_out,
457 pad_left = self.prompts_pad_left
455 pad_left = self.prompts_pad_left
458 )
456 )
459 # This is a context manager that installs/revmoes the displayhook at
457 # This is a context manager that installs/revmoes the displayhook at
460 # the appropriate time.
458 # the appropriate time.
461 self.display_trap = DisplayTrap(hook=self.displayhook)
459 self.display_trap = DisplayTrap(hook=self.displayhook)
462
460
463 def init_reload_doctest(self):
461 def init_reload_doctest(self):
464 # Do a proper resetting of doctest, including the necessary displayhook
462 # Do a proper resetting of doctest, including the necessary displayhook
465 # monkeypatching
463 # monkeypatching
466 try:
464 try:
467 doctest_reload()
465 doctest_reload()
468 except ImportError:
466 except ImportError:
469 warn("doctest module does not exist.")
467 warn("doctest module does not exist.")
470
468
471 #-------------------------------------------------------------------------
469 #-------------------------------------------------------------------------
472 # Things related to injections into the sys module
470 # Things related to injections into the sys module
473 #-------------------------------------------------------------------------
471 #-------------------------------------------------------------------------
474
472
475 def save_sys_module_state(self):
473 def save_sys_module_state(self):
476 """Save the state of hooks in the sys module.
474 """Save the state of hooks in the sys module.
477
475
478 This has to be called after self.user_ns is created.
476 This has to be called after self.user_ns is created.
479 """
477 """
480 self._orig_sys_module_state = {}
478 self._orig_sys_module_state = {}
481 self._orig_sys_module_state['stdin'] = sys.stdin
479 self._orig_sys_module_state['stdin'] = sys.stdin
482 self._orig_sys_module_state['stdout'] = sys.stdout
480 self._orig_sys_module_state['stdout'] = sys.stdout
483 self._orig_sys_module_state['stderr'] = sys.stderr
481 self._orig_sys_module_state['stderr'] = sys.stderr
484 self._orig_sys_module_state['excepthook'] = sys.excepthook
482 self._orig_sys_module_state['excepthook'] = sys.excepthook
485 try:
483 try:
486 self._orig_sys_modules_main_name = self.user_ns['__name__']
484 self._orig_sys_modules_main_name = self.user_ns['__name__']
487 except KeyError:
485 except KeyError:
488 pass
486 pass
489
487
490 def restore_sys_module_state(self):
488 def restore_sys_module_state(self):
491 """Restore the state of the sys module."""
489 """Restore the state of the sys module."""
492 try:
490 try:
493 for k, v in self._orig_sys_module_state.items():
491 for k, v in self._orig_sys_module_state.items():
494 setattr(sys, k, v)
492 setattr(sys, k, v)
495 except AttributeError:
493 except AttributeError:
496 pass
494 pass
497 try:
495 try:
498 delattr(sys, 'ipcompleter')
496 delattr(sys, 'ipcompleter')
499 except AttributeError:
497 except AttributeError:
500 pass
498 pass
501 # Reset what what done in self.init_sys_modules
499 # Reset what what done in self.init_sys_modules
502 try:
500 try:
503 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
501 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
504 except (AttributeError, KeyError):
502 except (AttributeError, KeyError):
505 pass
503 pass
506
504
507 #-------------------------------------------------------------------------
505 #-------------------------------------------------------------------------
508 # Things related to hooks
506 # Things related to hooks
509 #-------------------------------------------------------------------------
507 #-------------------------------------------------------------------------
510
508
511 def init_hooks(self):
509 def init_hooks(self):
512 # hooks holds pointers used for user-side customizations
510 # hooks holds pointers used for user-side customizations
513 self.hooks = Struct()
511 self.hooks = Struct()
514
512
515 self.strdispatchers = {}
513 self.strdispatchers = {}
516
514
517 # Set all default hooks, defined in the IPython.hooks module.
515 # Set all default hooks, defined in the IPython.hooks module.
518 hooks = IPython.core.hooks
516 hooks = IPython.core.hooks
519 for hook_name in hooks.__all__:
517 for hook_name in hooks.__all__:
520 # default hooks have priority 100, i.e. low; user hooks should have
518 # default hooks have priority 100, i.e. low; user hooks should have
521 # 0-100 priority
519 # 0-100 priority
522 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
520 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
523
521
524 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
522 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
525 """set_hook(name,hook) -> sets an internal IPython hook.
523 """set_hook(name,hook) -> sets an internal IPython hook.
526
524
527 IPython exposes some of its internal API as user-modifiable hooks. By
525 IPython exposes some of its internal API as user-modifiable hooks. By
528 adding your function to one of these hooks, you can modify IPython's
526 adding your function to one of these hooks, you can modify IPython's
529 behavior to call at runtime your own routines."""
527 behavior to call at runtime your own routines."""
530
528
531 # At some point in the future, this should validate the hook before it
529 # At some point in the future, this should validate the hook before it
532 # accepts it. Probably at least check that the hook takes the number
530 # accepts it. Probably at least check that the hook takes the number
533 # of args it's supposed to.
531 # of args it's supposed to.
534
532
535 f = new.instancemethod(hook,self,self.__class__)
533 f = new.instancemethod(hook,self,self.__class__)
536
534
537 # check if the hook is for strdispatcher first
535 # check if the hook is for strdispatcher first
538 if str_key is not None:
536 if str_key is not None:
539 sdp = self.strdispatchers.get(name, StrDispatch())
537 sdp = self.strdispatchers.get(name, StrDispatch())
540 sdp.add_s(str_key, f, priority )
538 sdp.add_s(str_key, f, priority )
541 self.strdispatchers[name] = sdp
539 self.strdispatchers[name] = sdp
542 return
540 return
543 if re_key is not None:
541 if re_key is not None:
544 sdp = self.strdispatchers.get(name, StrDispatch())
542 sdp = self.strdispatchers.get(name, StrDispatch())
545 sdp.add_re(re.compile(re_key), f, priority )
543 sdp.add_re(re.compile(re_key), f, priority )
546 self.strdispatchers[name] = sdp
544 self.strdispatchers[name] = sdp
547 return
545 return
548
546
549 dp = getattr(self.hooks, name, None)
547 dp = getattr(self.hooks, name, None)
550 if name not in IPython.core.hooks.__all__:
548 if name not in IPython.core.hooks.__all__:
551 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
549 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
552 if not dp:
550 if not dp:
553 dp = IPython.core.hooks.CommandChainDispatcher()
551 dp = IPython.core.hooks.CommandChainDispatcher()
554
552
555 try:
553 try:
556 dp.add(f,priority)
554 dp.add(f,priority)
557 except AttributeError:
555 except AttributeError:
558 # it was not commandchain, plain old func - replace
556 # it was not commandchain, plain old func - replace
559 dp = f
557 dp = f
560
558
561 setattr(self.hooks,name, dp)
559 setattr(self.hooks,name, dp)
562
560
563 #-------------------------------------------------------------------------
561 #-------------------------------------------------------------------------
564 # Things related to the "main" module
562 # Things related to the "main" module
565 #-------------------------------------------------------------------------
563 #-------------------------------------------------------------------------
566
564
567 def new_main_mod(self,ns=None):
565 def new_main_mod(self,ns=None):
568 """Return a new 'main' module object for user code execution.
566 """Return a new 'main' module object for user code execution.
569 """
567 """
570 main_mod = self._user_main_module
568 main_mod = self._user_main_module
571 init_fakemod_dict(main_mod,ns)
569 init_fakemod_dict(main_mod,ns)
572 return main_mod
570 return main_mod
573
571
574 def cache_main_mod(self,ns,fname):
572 def cache_main_mod(self,ns,fname):
575 """Cache a main module's namespace.
573 """Cache a main module's namespace.
576
574
577 When scripts are executed via %run, we must keep a reference to the
575 When scripts are executed via %run, we must keep a reference to the
578 namespace of their __main__ module (a FakeModule instance) around so
576 namespace of their __main__ module (a FakeModule instance) around so
579 that Python doesn't clear it, rendering objects defined therein
577 that Python doesn't clear it, rendering objects defined therein
580 useless.
578 useless.
581
579
582 This method keeps said reference in a private dict, keyed by the
580 This method keeps said reference in a private dict, keyed by the
583 absolute path of the module object (which corresponds to the script
581 absolute path of the module object (which corresponds to the script
584 path). This way, for multiple executions of the same script we only
582 path). This way, for multiple executions of the same script we only
585 keep one copy of the namespace (the last one), thus preventing memory
583 keep one copy of the namespace (the last one), thus preventing memory
586 leaks from old references while allowing the objects from the last
584 leaks from old references while allowing the objects from the last
587 execution to be accessible.
585 execution to be accessible.
588
586
589 Note: we can not allow the actual FakeModule instances to be deleted,
587 Note: we can not allow the actual FakeModule instances to be deleted,
590 because of how Python tears down modules (it hard-sets all their
588 because of how Python tears down modules (it hard-sets all their
591 references to None without regard for reference counts). This method
589 references to None without regard for reference counts). This method
592 must therefore make a *copy* of the given namespace, to allow the
590 must therefore make a *copy* of the given namespace, to allow the
593 original module's __dict__ to be cleared and reused.
591 original module's __dict__ to be cleared and reused.
594
592
595
593
596 Parameters
594 Parameters
597 ----------
595 ----------
598 ns : a namespace (a dict, typically)
596 ns : a namespace (a dict, typically)
599
597
600 fname : str
598 fname : str
601 Filename associated with the namespace.
599 Filename associated with the namespace.
602
600
603 Examples
601 Examples
604 --------
602 --------
605
603
606 In [10]: import IPython
604 In [10]: import IPython
607
605
608 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
606 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
609
607
610 In [12]: IPython.__file__ in _ip._main_ns_cache
608 In [12]: IPython.__file__ in _ip._main_ns_cache
611 Out[12]: True
609 Out[12]: True
612 """
610 """
613 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
611 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
614
612
615 def clear_main_mod_cache(self):
613 def clear_main_mod_cache(self):
616 """Clear the cache of main modules.
614 """Clear the cache of main modules.
617
615
618 Mainly for use by utilities like %reset.
616 Mainly for use by utilities like %reset.
619
617
620 Examples
618 Examples
621 --------
619 --------
622
620
623 In [15]: import IPython
621 In [15]: import IPython
624
622
625 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
623 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
626
624
627 In [17]: len(_ip._main_ns_cache) > 0
625 In [17]: len(_ip._main_ns_cache) > 0
628 Out[17]: True
626 Out[17]: True
629
627
630 In [18]: _ip.clear_main_mod_cache()
628 In [18]: _ip.clear_main_mod_cache()
631
629
632 In [19]: len(_ip._main_ns_cache) == 0
630 In [19]: len(_ip._main_ns_cache) == 0
633 Out[19]: True
631 Out[19]: True
634 """
632 """
635 self._main_ns_cache.clear()
633 self._main_ns_cache.clear()
636
634
637 #-------------------------------------------------------------------------
635 #-------------------------------------------------------------------------
638 # Things related to debugging
636 # Things related to debugging
639 #-------------------------------------------------------------------------
637 #-------------------------------------------------------------------------
640
638
641 def init_pdb(self):
639 def init_pdb(self):
642 # Set calling of pdb on exceptions
640 # Set calling of pdb on exceptions
643 # self.call_pdb is a property
641 # self.call_pdb is a property
644 self.call_pdb = self.pdb
642 self.call_pdb = self.pdb
645
643
646 def _get_call_pdb(self):
644 def _get_call_pdb(self):
647 return self._call_pdb
645 return self._call_pdb
648
646
649 def _set_call_pdb(self,val):
647 def _set_call_pdb(self,val):
650
648
651 if val not in (0,1,False,True):
649 if val not in (0,1,False,True):
652 raise ValueError,'new call_pdb value must be boolean'
650 raise ValueError,'new call_pdb value must be boolean'
653
651
654 # store value in instance
652 # store value in instance
655 self._call_pdb = val
653 self._call_pdb = val
656
654
657 # notify the actual exception handlers
655 # notify the actual exception handlers
658 self.InteractiveTB.call_pdb = val
656 self.InteractiveTB.call_pdb = val
659
657
660 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
658 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
661 'Control auto-activation of pdb at exceptions')
659 'Control auto-activation of pdb at exceptions')
662
660
663 def debugger(self,force=False):
661 def debugger(self,force=False):
664 """Call the pydb/pdb debugger.
662 """Call the pydb/pdb debugger.
665
663
666 Keywords:
664 Keywords:
667
665
668 - force(False): by default, this routine checks the instance call_pdb
666 - force(False): by default, this routine checks the instance call_pdb
669 flag and does not actually invoke the debugger if the flag is false.
667 flag and does not actually invoke the debugger if the flag is false.
670 The 'force' option forces the debugger to activate even if the flag
668 The 'force' option forces the debugger to activate even if the flag
671 is false.
669 is false.
672 """
670 """
673
671
674 if not (force or self.call_pdb):
672 if not (force or self.call_pdb):
675 return
673 return
676
674
677 if not hasattr(sys,'last_traceback'):
675 if not hasattr(sys,'last_traceback'):
678 error('No traceback has been produced, nothing to debug.')
676 error('No traceback has been produced, nothing to debug.')
679 return
677 return
680
678
681 # use pydb if available
679 # use pydb if available
682 if debugger.has_pydb:
680 if debugger.has_pydb:
683 from pydb import pm
681 from pydb import pm
684 else:
682 else:
685 # fallback to our internal debugger
683 # fallback to our internal debugger
686 pm = lambda : self.InteractiveTB.debugger(force=True)
684 pm = lambda : self.InteractiveTB.debugger(force=True)
687 self.history_saving_wrapper(pm)()
685 self.history_saving_wrapper(pm)()
688
686
689 #-------------------------------------------------------------------------
687 #-------------------------------------------------------------------------
690 # Things related to IPython's various namespaces
688 # Things related to IPython's various namespaces
691 #-------------------------------------------------------------------------
689 #-------------------------------------------------------------------------
692
690
693 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
691 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
694 # Create the namespace where the user will operate. user_ns is
692 # Create the namespace where the user will operate. user_ns is
695 # normally the only one used, and it is passed to the exec calls as
693 # normally the only one used, and it is passed to the exec calls as
696 # the locals argument. But we do carry a user_global_ns namespace
694 # the locals argument. But we do carry a user_global_ns namespace
697 # given as the exec 'globals' argument, This is useful in embedding
695 # given as the exec 'globals' argument, This is useful in embedding
698 # situations where the ipython shell opens in a context where the
696 # situations where the ipython shell opens in a context where the
699 # distinction between locals and globals is meaningful. For
697 # distinction between locals and globals is meaningful. For
700 # non-embedded contexts, it is just the same object as the user_ns dict.
698 # non-embedded contexts, it is just the same object as the user_ns dict.
701
699
702 # FIXME. For some strange reason, __builtins__ is showing up at user
700 # FIXME. For some strange reason, __builtins__ is showing up at user
703 # level as a dict instead of a module. This is a manual fix, but I
701 # level as a dict instead of a module. This is a manual fix, but I
704 # should really track down where the problem is coming from. Alex
702 # should really track down where the problem is coming from. Alex
705 # Schmolck reported this problem first.
703 # Schmolck reported this problem first.
706
704
707 # A useful post by Alex Martelli on this topic:
705 # A useful post by Alex Martelli on this topic:
708 # Re: inconsistent value from __builtins__
706 # Re: inconsistent value from __builtins__
709 # Von: Alex Martelli <aleaxit@yahoo.com>
707 # Von: Alex Martelli <aleaxit@yahoo.com>
710 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
708 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
711 # Gruppen: comp.lang.python
709 # Gruppen: comp.lang.python
712
710
713 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
711 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
714 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
712 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
715 # > <type 'dict'>
713 # > <type 'dict'>
716 # > >>> print type(__builtins__)
714 # > >>> print type(__builtins__)
717 # > <type 'module'>
715 # > <type 'module'>
718 # > Is this difference in return value intentional?
716 # > Is this difference in return value intentional?
719
717
720 # Well, it's documented that '__builtins__' can be either a dictionary
718 # Well, it's documented that '__builtins__' can be either a dictionary
721 # or a module, and it's been that way for a long time. Whether it's
719 # or a module, and it's been that way for a long time. Whether it's
722 # intentional (or sensible), I don't know. In any case, the idea is
720 # intentional (or sensible), I don't know. In any case, the idea is
723 # that if you need to access the built-in namespace directly, you
721 # that if you need to access the built-in namespace directly, you
724 # should start with "import __builtin__" (note, no 's') which will
722 # should start with "import __builtin__" (note, no 's') which will
725 # definitely give you a module. Yeah, it's somewhat confusing:-(.
723 # definitely give you a module. Yeah, it's somewhat confusing:-(.
726
724
727 # These routines return properly built dicts as needed by the rest of
725 # These routines return properly built dicts as needed by the rest of
728 # the code, and can also be used by extension writers to generate
726 # the code, and can also be used by extension writers to generate
729 # properly initialized namespaces.
727 # properly initialized namespaces.
730 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
728 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
731
729
732 # Assign namespaces
730 # Assign namespaces
733 # This is the namespace where all normal user variables live
731 # This is the namespace where all normal user variables live
734 self.user_ns = user_ns
732 self.user_ns = user_ns
735 self.user_global_ns = user_global_ns
733 self.user_global_ns = user_global_ns
736
734
737 # An auxiliary namespace that checks what parts of the user_ns were
735 # An auxiliary namespace that checks what parts of the user_ns were
738 # loaded at startup, so we can list later only variables defined in
736 # loaded at startup, so we can list later only variables defined in
739 # actual interactive use. Since it is always a subset of user_ns, it
737 # actual interactive use. Since it is always a subset of user_ns, it
740 # doesn't need to be separately tracked in the ns_table.
738 # doesn't need to be separately tracked in the ns_table.
741 self.user_ns_hidden = {}
739 self.user_ns_hidden = {}
742
740
743 # A namespace to keep track of internal data structures to prevent
741 # A namespace to keep track of internal data structures to prevent
744 # them from cluttering user-visible stuff. Will be updated later
742 # them from cluttering user-visible stuff. Will be updated later
745 self.internal_ns = {}
743 self.internal_ns = {}
746
744
747 # Now that FakeModule produces a real module, we've run into a nasty
745 # Now that FakeModule produces a real module, we've run into a nasty
748 # problem: after script execution (via %run), the module where the user
746 # problem: after script execution (via %run), the module where the user
749 # code ran is deleted. Now that this object is a true module (needed
747 # code ran is deleted. Now that this object is a true module (needed
750 # so docetst and other tools work correctly), the Python module
748 # so docetst and other tools work correctly), the Python module
751 # teardown mechanism runs over it, and sets to None every variable
749 # teardown mechanism runs over it, and sets to None every variable
752 # present in that module. Top-level references to objects from the
750 # present in that module. Top-level references to objects from the
753 # script survive, because the user_ns is updated with them. However,
751 # script survive, because the user_ns is updated with them. However,
754 # calling functions defined in the script that use other things from
752 # calling functions defined in the script that use other things from
755 # the script will fail, because the function's closure had references
753 # the script will fail, because the function's closure had references
756 # to the original objects, which are now all None. So we must protect
754 # to the original objects, which are now all None. So we must protect
757 # these modules from deletion by keeping a cache.
755 # these modules from deletion by keeping a cache.
758 #
756 #
759 # To avoid keeping stale modules around (we only need the one from the
757 # To avoid keeping stale modules around (we only need the one from the
760 # last run), we use a dict keyed with the full path to the script, so
758 # last run), we use a dict keyed with the full path to the script, so
761 # only the last version of the module is held in the cache. Note,
759 # only the last version of the module is held in the cache. Note,
762 # however, that we must cache the module *namespace contents* (their
760 # however, that we must cache the module *namespace contents* (their
763 # __dict__). Because if we try to cache the actual modules, old ones
761 # __dict__). Because if we try to cache the actual modules, old ones
764 # (uncached) could be destroyed while still holding references (such as
762 # (uncached) could be destroyed while still holding references (such as
765 # those held by GUI objects that tend to be long-lived)>
763 # those held by GUI objects that tend to be long-lived)>
766 #
764 #
767 # The %reset command will flush this cache. See the cache_main_mod()
765 # The %reset command will flush this cache. See the cache_main_mod()
768 # and clear_main_mod_cache() methods for details on use.
766 # and clear_main_mod_cache() methods for details on use.
769
767
770 # This is the cache used for 'main' namespaces
768 # This is the cache used for 'main' namespaces
771 self._main_ns_cache = {}
769 self._main_ns_cache = {}
772 # And this is the single instance of FakeModule whose __dict__ we keep
770 # And this is the single instance of FakeModule whose __dict__ we keep
773 # copying and clearing for reuse on each %run
771 # copying and clearing for reuse on each %run
774 self._user_main_module = FakeModule()
772 self._user_main_module = FakeModule()
775
773
776 # A table holding all the namespaces IPython deals with, so that
774 # A table holding all the namespaces IPython deals with, so that
777 # introspection facilities can search easily.
775 # introspection facilities can search easily.
778 self.ns_table = {'user':user_ns,
776 self.ns_table = {'user':user_ns,
779 'user_global':user_global_ns,
777 'user_global':user_global_ns,
780 'internal':self.internal_ns,
778 'internal':self.internal_ns,
781 'builtin':__builtin__.__dict__
779 'builtin':__builtin__.__dict__
782 }
780 }
783
781
784 # Similarly, track all namespaces where references can be held and that
782 # Similarly, track all namespaces where references can be held and that
785 # we can safely clear (so it can NOT include builtin). This one can be
783 # we can safely clear (so it can NOT include builtin). This one can be
786 # a simple list.
784 # a simple list.
787 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
785 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
788 self.internal_ns, self._main_ns_cache ]
786 self.internal_ns, self._main_ns_cache ]
789
787
790 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
788 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
791 """Return a valid local and global user interactive namespaces.
789 """Return a valid local and global user interactive namespaces.
792
790
793 This builds a dict with the minimal information needed to operate as a
791 This builds a dict with the minimal information needed to operate as a
794 valid IPython user namespace, which you can pass to the various
792 valid IPython user namespace, which you can pass to the various
795 embedding classes in ipython. The default implementation returns the
793 embedding classes in ipython. The default implementation returns the
796 same dict for both the locals and the globals to allow functions to
794 same dict for both the locals and the globals to allow functions to
797 refer to variables in the namespace. Customized implementations can
795 refer to variables in the namespace. Customized implementations can
798 return different dicts. The locals dictionary can actually be anything
796 return different dicts. The locals dictionary can actually be anything
799 following the basic mapping protocol of a dict, but the globals dict
797 following the basic mapping protocol of a dict, but the globals dict
800 must be a true dict, not even a subclass. It is recommended that any
798 must be a true dict, not even a subclass. It is recommended that any
801 custom object for the locals namespace synchronize with the globals
799 custom object for the locals namespace synchronize with the globals
802 dict somehow.
800 dict somehow.
803
801
804 Raises TypeError if the provided globals namespace is not a true dict.
802 Raises TypeError if the provided globals namespace is not a true dict.
805
803
806 Parameters
804 Parameters
807 ----------
805 ----------
808 user_ns : dict-like, optional
806 user_ns : dict-like, optional
809 The current user namespace. The items in this namespace should
807 The current user namespace. The items in this namespace should
810 be included in the output. If None, an appropriate blank
808 be included in the output. If None, an appropriate blank
811 namespace should be created.
809 namespace should be created.
812 user_global_ns : dict, optional
810 user_global_ns : dict, optional
813 The current user global namespace. The items in this namespace
811 The current user global namespace. The items in this namespace
814 should be included in the output. If None, an appropriate
812 should be included in the output. If None, an appropriate
815 blank namespace should be created.
813 blank namespace should be created.
816
814
817 Returns
815 Returns
818 -------
816 -------
819 A pair of dictionary-like object to be used as the local namespace
817 A pair of dictionary-like object to be used as the local namespace
820 of the interpreter and a dict to be used as the global namespace.
818 of the interpreter and a dict to be used as the global namespace.
821 """
819 """
822
820
823
821
824 # We must ensure that __builtin__ (without the final 's') is always
822 # We must ensure that __builtin__ (without the final 's') is always
825 # available and pointing to the __builtin__ *module*. For more details:
823 # available and pointing to the __builtin__ *module*. For more details:
826 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
824 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
827
825
828 if user_ns is None:
826 if user_ns is None:
829 # Set __name__ to __main__ to better match the behavior of the
827 # Set __name__ to __main__ to better match the behavior of the
830 # normal interpreter.
828 # normal interpreter.
831 user_ns = {'__name__' :'__main__',
829 user_ns = {'__name__' :'__main__',
832 '__builtin__' : __builtin__,
830 '__builtin__' : __builtin__,
833 '__builtins__' : __builtin__,
831 '__builtins__' : __builtin__,
834 }
832 }
835 else:
833 else:
836 user_ns.setdefault('__name__','__main__')
834 user_ns.setdefault('__name__','__main__')
837 user_ns.setdefault('__builtin__',__builtin__)
835 user_ns.setdefault('__builtin__',__builtin__)
838 user_ns.setdefault('__builtins__',__builtin__)
836 user_ns.setdefault('__builtins__',__builtin__)
839
837
840 if user_global_ns is None:
838 if user_global_ns is None:
841 user_global_ns = user_ns
839 user_global_ns = user_ns
842 if type(user_global_ns) is not dict:
840 if type(user_global_ns) is not dict:
843 raise TypeError("user_global_ns must be a true dict; got %r"
841 raise TypeError("user_global_ns must be a true dict; got %r"
844 % type(user_global_ns))
842 % type(user_global_ns))
845
843
846 return user_ns, user_global_ns
844 return user_ns, user_global_ns
847
845
848 def init_sys_modules(self):
846 def init_sys_modules(self):
849 # We need to insert into sys.modules something that looks like a
847 # We need to insert into sys.modules something that looks like a
850 # module but which accesses the IPython namespace, for shelve and
848 # module but which accesses the IPython namespace, for shelve and
851 # pickle to work interactively. Normally they rely on getting
849 # pickle to work interactively. Normally they rely on getting
852 # everything out of __main__, but for embedding purposes each IPython
850 # everything out of __main__, but for embedding purposes each IPython
853 # instance has its own private namespace, so we can't go shoving
851 # instance has its own private namespace, so we can't go shoving
854 # everything into __main__.
852 # everything into __main__.
855
853
856 # note, however, that we should only do this for non-embedded
854 # note, however, that we should only do this for non-embedded
857 # ipythons, which really mimic the __main__.__dict__ with their own
855 # ipythons, which really mimic the __main__.__dict__ with their own
858 # namespace. Embedded instances, on the other hand, should not do
856 # namespace. Embedded instances, on the other hand, should not do
859 # this because they need to manage the user local/global namespaces
857 # this because they need to manage the user local/global namespaces
860 # only, but they live within a 'normal' __main__ (meaning, they
858 # only, but they live within a 'normal' __main__ (meaning, they
861 # shouldn't overtake the execution environment of the script they're
859 # shouldn't overtake the execution environment of the script they're
862 # embedded in).
860 # embedded in).
863
861
864 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
862 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
865
863
866 try:
864 try:
867 main_name = self.user_ns['__name__']
865 main_name = self.user_ns['__name__']
868 except KeyError:
866 except KeyError:
869 raise KeyError('user_ns dictionary MUST have a "__name__" key')
867 raise KeyError('user_ns dictionary MUST have a "__name__" key')
870 else:
868 else:
871 sys.modules[main_name] = FakeModule(self.user_ns)
869 sys.modules[main_name] = FakeModule(self.user_ns)
872
870
873 def init_user_ns(self):
871 def init_user_ns(self):
874 """Initialize all user-visible namespaces to their minimum defaults.
872 """Initialize all user-visible namespaces to their minimum defaults.
875
873
876 Certain history lists are also initialized here, as they effectively
874 Certain history lists are also initialized here, as they effectively
877 act as user namespaces.
875 act as user namespaces.
878
876
879 Notes
877 Notes
880 -----
878 -----
881 All data structures here are only filled in, they are NOT reset by this
879 All data structures here are only filled in, they are NOT reset by this
882 method. If they were not empty before, data will simply be added to
880 method. If they were not empty before, data will simply be added to
883 therm.
881 therm.
884 """
882 """
885 # This function works in two parts: first we put a few things in
883 # This function works in two parts: first we put a few things in
886 # user_ns, and we sync that contents into user_ns_hidden so that these
884 # user_ns, and we sync that contents into user_ns_hidden so that these
887 # initial variables aren't shown by %who. After the sync, we add the
885 # initial variables aren't shown by %who. After the sync, we add the
888 # rest of what we *do* want the user to see with %who even on a new
886 # rest of what we *do* want the user to see with %who even on a new
889 # session (probably nothing, so theye really only see their own stuff)
887 # session (probably nothing, so theye really only see their own stuff)
890
888
891 # The user dict must *always* have a __builtin__ reference to the
889 # The user dict must *always* have a __builtin__ reference to the
892 # Python standard __builtin__ namespace, which must be imported.
890 # Python standard __builtin__ namespace, which must be imported.
893 # This is so that certain operations in prompt evaluation can be
891 # This is so that certain operations in prompt evaluation can be
894 # reliably executed with builtins. Note that we can NOT use
892 # reliably executed with builtins. Note that we can NOT use
895 # __builtins__ (note the 's'), because that can either be a dict or a
893 # __builtins__ (note the 's'), because that can either be a dict or a
896 # module, and can even mutate at runtime, depending on the context
894 # module, and can even mutate at runtime, depending on the context
897 # (Python makes no guarantees on it). In contrast, __builtin__ is
895 # (Python makes no guarantees on it). In contrast, __builtin__ is
898 # always a module object, though it must be explicitly imported.
896 # always a module object, though it must be explicitly imported.
899
897
900 # For more details:
898 # For more details:
901 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
899 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
902 ns = dict(__builtin__ = __builtin__)
900 ns = dict(__builtin__ = __builtin__)
903
901
904 # Put 'help' in the user namespace
902 # Put 'help' in the user namespace
905 try:
903 try:
906 from site import _Helper
904 from site import _Helper
907 ns['help'] = _Helper()
905 ns['help'] = _Helper()
908 except ImportError:
906 except ImportError:
909 warn('help() not available - check site.py')
907 warn('help() not available - check site.py')
910
908
911 # make global variables for user access to the histories
909 # make global variables for user access to the histories
912 ns['_ih'] = self.input_hist
910 ns['_ih'] = self.input_hist
913 ns['_oh'] = self.output_hist
911 ns['_oh'] = self.output_hist
914 ns['_dh'] = self.dir_hist
912 ns['_dh'] = self.dir_hist
915
913
916 ns['_sh'] = shadowns
914 ns['_sh'] = shadowns
917
915
918 # user aliases to input and output histories. These shouldn't show up
916 # user aliases to input and output histories. These shouldn't show up
919 # in %who, as they can have very large reprs.
917 # in %who, as they can have very large reprs.
920 ns['In'] = self.input_hist
918 ns['In'] = self.input_hist
921 ns['Out'] = self.output_hist
919 ns['Out'] = self.output_hist
922
920
923 # Store myself as the public api!!!
921 # Store myself as the public api!!!
924 ns['get_ipython'] = self.get_ipython
922 ns['get_ipython'] = self.get_ipython
925
923
926 # Sync what we've added so far to user_ns_hidden so these aren't seen
924 # Sync what we've added so far to user_ns_hidden so these aren't seen
927 # by %who
925 # by %who
928 self.user_ns_hidden.update(ns)
926 self.user_ns_hidden.update(ns)
929
927
930 # Anything put into ns now would show up in %who. Think twice before
928 # Anything put into ns now would show up in %who. Think twice before
931 # putting anything here, as we really want %who to show the user their
929 # putting anything here, as we really want %who to show the user their
932 # stuff, not our variables.
930 # stuff, not our variables.
933
931
934 # Finally, update the real user's namespace
932 # Finally, update the real user's namespace
935 self.user_ns.update(ns)
933 self.user_ns.update(ns)
936
934
937
935
938 def reset(self):
936 def reset(self):
939 """Clear all internal namespaces.
937 """Clear all internal namespaces.
940
938
941 Note that this is much more aggressive than %reset, since it clears
939 Note that this is much more aggressive than %reset, since it clears
942 fully all namespaces, as well as all input/output lists.
940 fully all namespaces, as well as all input/output lists.
943 """
941 """
944 for ns in self.ns_refs_table:
942 for ns in self.ns_refs_table:
945 ns.clear()
943 ns.clear()
946
944
947 self.alias_manager.clear_aliases()
945 self.alias_manager.clear_aliases()
948
946
949 # Clear input and output histories
947 # Clear input and output histories
950 self.input_hist[:] = []
948 self.input_hist[:] = []
951 self.input_hist_raw[:] = []
949 self.input_hist_raw[:] = []
952 self.output_hist.clear()
950 self.output_hist.clear()
953
951
954 # Restore the user namespaces to minimal usability
952 # Restore the user namespaces to minimal usability
955 self.init_user_ns()
953 self.init_user_ns()
956
954
957 # Restore the default and user aliases
955 # Restore the default and user aliases
958 self.alias_manager.init_aliases()
956 self.alias_manager.init_aliases()
959
957
960 def reset_selective(self, regex=None):
958 def reset_selective(self, regex=None):
961 """Clear selective variables from internal namespaces based on a specified regular expression.
959 """Clear selective variables from internal namespaces based on a specified regular expression.
962
960
963 Parameters
961 Parameters
964 ----------
962 ----------
965 regex : string or compiled pattern, optional
963 regex : string or compiled pattern, optional
966 A regular expression pattern that will be used in searching variable names in the users
964 A regular expression pattern that will be used in searching variable names in the users
967 namespaces.
965 namespaces.
968 """
966 """
969 if regex is not None:
967 if regex is not None:
970 try:
968 try:
971 m = re.compile(regex)
969 m = re.compile(regex)
972 except TypeError:
970 except TypeError:
973 raise TypeError('regex must be a string or compiled pattern')
971 raise TypeError('regex must be a string or compiled pattern')
974 # Search for keys in each namespace that match the given regex
972 # Search for keys in each namespace that match the given regex
975 # If a match is found, delete the key/value pair.
973 # If a match is found, delete the key/value pair.
976 for ns in self.ns_refs_table:
974 for ns in self.ns_refs_table:
977 for var in ns:
975 for var in ns:
978 if m.search(var):
976 if m.search(var):
979 del ns[var]
977 del ns[var]
980
978
981 def push(self, variables, interactive=True):
979 def push(self, variables, interactive=True):
982 """Inject a group of variables into the IPython user namespace.
980 """Inject a group of variables into the IPython user namespace.
983
981
984 Parameters
982 Parameters
985 ----------
983 ----------
986 variables : dict, str or list/tuple of str
984 variables : dict, str or list/tuple of str
987 The variables to inject into the user's namespace. If a dict,
985 The variables to inject into the user's namespace. If a dict,
988 a simple update is done. If a str, the string is assumed to
986 a simple update is done. If a str, the string is assumed to
989 have variable names separated by spaces. A list/tuple of str
987 have variable names separated by spaces. A list/tuple of str
990 can also be used to give the variable names. If just the variable
988 can also be used to give the variable names. If just the variable
991 names are give (list/tuple/str) then the variable values looked
989 names are give (list/tuple/str) then the variable values looked
992 up in the callers frame.
990 up in the callers frame.
993 interactive : bool
991 interactive : bool
994 If True (default), the variables will be listed with the ``who``
992 If True (default), the variables will be listed with the ``who``
995 magic.
993 magic.
996 """
994 """
997 vdict = None
995 vdict = None
998
996
999 # We need a dict of name/value pairs to do namespace updates.
997 # We need a dict of name/value pairs to do namespace updates.
1000 if isinstance(variables, dict):
998 if isinstance(variables, dict):
1001 vdict = variables
999 vdict = variables
1002 elif isinstance(variables, (basestring, list, tuple)):
1000 elif isinstance(variables, (basestring, list, tuple)):
1003 if isinstance(variables, basestring):
1001 if isinstance(variables, basestring):
1004 vlist = variables.split()
1002 vlist = variables.split()
1005 else:
1003 else:
1006 vlist = variables
1004 vlist = variables
1007 vdict = {}
1005 vdict = {}
1008 cf = sys._getframe(1)
1006 cf = sys._getframe(1)
1009 for name in vlist:
1007 for name in vlist:
1010 try:
1008 try:
1011 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1009 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1012 except:
1010 except:
1013 print ('Could not get variable %s from %s' %
1011 print ('Could not get variable %s from %s' %
1014 (name,cf.f_code.co_name))
1012 (name,cf.f_code.co_name))
1015 else:
1013 else:
1016 raise ValueError('variables must be a dict/str/list/tuple')
1014 raise ValueError('variables must be a dict/str/list/tuple')
1017
1015
1018 # Propagate variables to user namespace
1016 # Propagate variables to user namespace
1019 self.user_ns.update(vdict)
1017 self.user_ns.update(vdict)
1020
1018
1021 # And configure interactive visibility
1019 # And configure interactive visibility
1022 config_ns = self.user_ns_hidden
1020 config_ns = self.user_ns_hidden
1023 if interactive:
1021 if interactive:
1024 for name, val in vdict.iteritems():
1022 for name, val in vdict.iteritems():
1025 config_ns.pop(name, None)
1023 config_ns.pop(name, None)
1026 else:
1024 else:
1027 for name,val in vdict.iteritems():
1025 for name,val in vdict.iteritems():
1028 config_ns[name] = val
1026 config_ns[name] = val
1029
1027
1030 #-------------------------------------------------------------------------
1028 #-------------------------------------------------------------------------
1031 # Things related to history management
1029 # Things related to history management
1032 #-------------------------------------------------------------------------
1030 #-------------------------------------------------------------------------
1033
1031
1034 def init_history(self):
1032 def init_history(self):
1035 # List of input with multi-line handling.
1033 # List of input with multi-line handling.
1036 self.input_hist = InputList()
1034 self.input_hist = InputList()
1037 # This one will hold the 'raw' input history, without any
1035 # This one will hold the 'raw' input history, without any
1038 # pre-processing. This will allow users to retrieve the input just as
1036 # pre-processing. This will allow users to retrieve the input just as
1039 # it was exactly typed in by the user, with %hist -r.
1037 # it was exactly typed in by the user, with %hist -r.
1040 self.input_hist_raw = InputList()
1038 self.input_hist_raw = InputList()
1041
1039
1042 # list of visited directories
1040 # list of visited directories
1043 try:
1041 try:
1044 self.dir_hist = [os.getcwd()]
1042 self.dir_hist = [os.getcwd()]
1045 except OSError:
1043 except OSError:
1046 self.dir_hist = []
1044 self.dir_hist = []
1047
1045
1048 # dict of output history
1046 # dict of output history
1049 self.output_hist = {}
1047 self.output_hist = {}
1050
1048
1051 # Now the history file
1049 # Now the history file
1052 if self.profile:
1050 if self.profile:
1053 histfname = 'history-%s' % self.profile
1051 histfname = 'history-%s' % self.profile
1054 else:
1052 else:
1055 histfname = 'history'
1053 histfname = 'history'
1056 self.histfile = os.path.join(self.ipython_dir, histfname)
1054 self.histfile = os.path.join(self.ipython_dir, histfname)
1057
1055
1058 # Fill the history zero entry, user counter starts at 1
1056 # Fill the history zero entry, user counter starts at 1
1059 self.input_hist.append('\n')
1057 self.input_hist.append('\n')
1060 self.input_hist_raw.append('\n')
1058 self.input_hist_raw.append('\n')
1061
1059
1062 def init_shadow_hist(self):
1060 def init_shadow_hist(self):
1063 try:
1061 try:
1064 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1062 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1065 except exceptions.UnicodeDecodeError:
1063 except exceptions.UnicodeDecodeError:
1066 print "Your ipython_dir can't be decoded to unicode!"
1064 print "Your ipython_dir can't be decoded to unicode!"
1067 print "Please set HOME environment variable to something that"
1065 print "Please set HOME environment variable to something that"
1068 print r"only has ASCII characters, e.g. c:\home"
1066 print r"only has ASCII characters, e.g. c:\home"
1069 print "Now it is", self.ipython_dir
1067 print "Now it is", self.ipython_dir
1070 sys.exit()
1068 sys.exit()
1071 self.shadowhist = ipcorehist.ShadowHist(self.db)
1069 self.shadowhist = ipcorehist.ShadowHist(self.db)
1072
1070
1073 def savehist(self):
1071 def savehist(self):
1074 """Save input history to a file (via readline library)."""
1072 """Save input history to a file (via readline library)."""
1075
1073
1076 try:
1074 try:
1077 self.readline.write_history_file(self.histfile)
1075 self.readline.write_history_file(self.histfile)
1078 except:
1076 except:
1079 print 'Unable to save IPython command history to file: ' + \
1077 print 'Unable to save IPython command history to file: ' + \
1080 `self.histfile`
1078 `self.histfile`
1081
1079
1082 def reloadhist(self):
1080 def reloadhist(self):
1083 """Reload the input history from disk file."""
1081 """Reload the input history from disk file."""
1084
1082
1085 try:
1083 try:
1086 self.readline.clear_history()
1084 self.readline.clear_history()
1087 self.readline.read_history_file(self.shell.histfile)
1085 self.readline.read_history_file(self.shell.histfile)
1088 except AttributeError:
1086 except AttributeError:
1089 pass
1087 pass
1090
1088
1091 def history_saving_wrapper(self, func):
1089 def history_saving_wrapper(self, func):
1092 """ Wrap func for readline history saving
1090 """ Wrap func for readline history saving
1093
1091
1094 Convert func into callable that saves & restores
1092 Convert func into callable that saves & restores
1095 history around the call """
1093 history around the call """
1096
1094
1097 if self.has_readline:
1095 if self.has_readline:
1098 from IPython.utils import rlineimpl as readline
1096 from IPython.utils import rlineimpl as readline
1099 else:
1097 else:
1100 return func
1098 return func
1101
1099
1102 def wrapper():
1100 def wrapper():
1103 self.savehist()
1101 self.savehist()
1104 try:
1102 try:
1105 func()
1103 func()
1106 finally:
1104 finally:
1107 readline.read_history_file(self.histfile)
1105 readline.read_history_file(self.histfile)
1108 return wrapper
1106 return wrapper
1109
1107
1110 def get_history(self, index=None, raw=False, output=True):
1108 def get_history(self, index=None, raw=False, output=True):
1111 """Get the history list.
1109 """Get the history list.
1112
1110
1113 Get the input and output history.
1111 Get the input and output history.
1114
1112
1115 Parameters
1113 Parameters
1116 ----------
1114 ----------
1117 index : n or (n1, n2) or None
1115 index : n or (n1, n2) or None
1118 If n, then the last entries. If a tuple, then all in
1116 If n, then the last entries. If a tuple, then all in
1119 range(n1, n2). If None, then all entries. Raises IndexError if
1117 range(n1, n2). If None, then all entries. Raises IndexError if
1120 the format of index is incorrect.
1118 the format of index is incorrect.
1121 raw : bool
1119 raw : bool
1122 If True, return the raw input.
1120 If True, return the raw input.
1123 output : bool
1121 output : bool
1124 If True, then return the output as well.
1122 If True, then return the output as well.
1125
1123
1126 Returns
1124 Returns
1127 -------
1125 -------
1128 If output is True, then return a dict of tuples, keyed by the prompt
1126 If output is True, then return a dict of tuples, keyed by the prompt
1129 numbers and with values of (input, output). If output is False, then
1127 numbers and with values of (input, output). If output is False, then
1130 a dict, keyed by the prompt number with the values of input. Raises
1128 a dict, keyed by the prompt number with the values of input. Raises
1131 IndexError if no history is found.
1129 IndexError if no history is found.
1132 """
1130 """
1133 if raw:
1131 if raw:
1134 input_hist = self.input_hist_raw
1132 input_hist = self.input_hist_raw
1135 else:
1133 else:
1136 input_hist = self.input_hist
1134 input_hist = self.input_hist
1137 if output:
1135 if output:
1138 output_hist = self.user_ns['Out']
1136 output_hist = self.user_ns['Out']
1139 n = len(input_hist)
1137 n = len(input_hist)
1140 if index is None:
1138 if index is None:
1141 start=0; stop=n
1139 start=0; stop=n
1142 elif isinstance(index, int):
1140 elif isinstance(index, int):
1143 start=n-index; stop=n
1141 start=n-index; stop=n
1144 elif isinstance(index, tuple) and len(index) == 2:
1142 elif isinstance(index, tuple) and len(index) == 2:
1145 start=index[0]; stop=index[1]
1143 start=index[0]; stop=index[1]
1146 else:
1144 else:
1147 raise IndexError('Not a valid index for the input history: %r' % index)
1145 raise IndexError('Not a valid index for the input history: %r' % index)
1148 hist = {}
1146 hist = {}
1149 for i in range(start, stop):
1147 for i in range(start, stop):
1150 if output:
1148 if output:
1151 hist[i] = (input_hist[i], output_hist.get(i))
1149 hist[i] = (input_hist[i], output_hist.get(i))
1152 else:
1150 else:
1153 hist[i] = input_hist[i]
1151 hist[i] = input_hist[i]
1154 if len(hist)==0:
1152 if len(hist)==0:
1155 raise IndexError('No history for range of indices: %r' % index)
1153 raise IndexError('No history for range of indices: %r' % index)
1156 return hist
1154 return hist
1157
1155
1158 #-------------------------------------------------------------------------
1156 #-------------------------------------------------------------------------
1159 # Things related to exception handling and tracebacks (not debugging)
1157 # Things related to exception handling and tracebacks (not debugging)
1160 #-------------------------------------------------------------------------
1158 #-------------------------------------------------------------------------
1161
1159
1162 def init_traceback_handlers(self, custom_exceptions):
1160 def init_traceback_handlers(self, custom_exceptions):
1163 # Syntax error handler.
1161 # Syntax error handler.
1164 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1162 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1165
1163
1166 # The interactive one is initialized with an offset, meaning we always
1164 # The interactive one is initialized with an offset, meaning we always
1167 # want to remove the topmost item in the traceback, which is our own
1165 # want to remove the topmost item in the traceback, which is our own
1168 # internal code. Valid modes: ['Plain','Context','Verbose']
1166 # internal code. Valid modes: ['Plain','Context','Verbose']
1169 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1167 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1170 color_scheme='NoColor',
1168 color_scheme='NoColor',
1171 tb_offset = 1)
1169 tb_offset = 1)
1172
1170
1173 # The instance will store a pointer to the system-wide exception hook,
1171 # The instance will store a pointer to the system-wide exception hook,
1174 # so that runtime code (such as magics) can access it. This is because
1172 # so that runtime code (such as magics) can access it. This is because
1175 # during the read-eval loop, it may get temporarily overwritten.
1173 # during the read-eval loop, it may get temporarily overwritten.
1176 self.sys_excepthook = sys.excepthook
1174 self.sys_excepthook = sys.excepthook
1177
1175
1178 # and add any custom exception handlers the user may have specified
1176 # and add any custom exception handlers the user may have specified
1179 self.set_custom_exc(*custom_exceptions)
1177 self.set_custom_exc(*custom_exceptions)
1180
1178
1181 # Set the exception mode
1179 # Set the exception mode
1182 self.InteractiveTB.set_mode(mode=self.xmode)
1180 self.InteractiveTB.set_mode(mode=self.xmode)
1183
1181
1184 def set_custom_exc(self, exc_tuple, handler):
1182 def set_custom_exc(self, exc_tuple, handler):
1185 """set_custom_exc(exc_tuple,handler)
1183 """set_custom_exc(exc_tuple,handler)
1186
1184
1187 Set a custom exception handler, which will be called if any of the
1185 Set a custom exception handler, which will be called if any of the
1188 exceptions in exc_tuple occur in the mainloop (specifically, in the
1186 exceptions in exc_tuple occur in the mainloop (specifically, in the
1189 runcode() method.
1187 runcode() method.
1190
1188
1191 Inputs:
1189 Inputs:
1192
1190
1193 - exc_tuple: a *tuple* of valid exceptions to call the defined
1191 - exc_tuple: a *tuple* of valid exceptions to call the defined
1194 handler for. It is very important that you use a tuple, and NOT A
1192 handler for. It is very important that you use a tuple, and NOT A
1195 LIST here, because of the way Python's except statement works. If
1193 LIST here, because of the way Python's except statement works. If
1196 you only want to trap a single exception, use a singleton tuple:
1194 you only want to trap a single exception, use a singleton tuple:
1197
1195
1198 exc_tuple == (MyCustomException,)
1196 exc_tuple == (MyCustomException,)
1199
1197
1200 - handler: this must be defined as a function with the following
1198 - handler: this must be defined as a function with the following
1201 basic interface::
1199 basic interface::
1202
1200
1203 def my_handler(self, etype, value, tb, tb_offset=None)
1201 def my_handler(self, etype, value, tb, tb_offset=None)
1204 ...
1202 ...
1205 # The return value must be
1203 # The return value must be
1206 return structured_traceback
1204 return structured_traceback
1207
1205
1208 This will be made into an instance method (via new.instancemethod)
1206 This will be made into an instance method (via new.instancemethod)
1209 of IPython itself, and it will be called if any of the exceptions
1207 of IPython itself, and it will be called if any of the exceptions
1210 listed in the exc_tuple are caught. If the handler is None, an
1208 listed in the exc_tuple are caught. If the handler is None, an
1211 internal basic one is used, which just prints basic info.
1209 internal basic one is used, which just prints basic info.
1212
1210
1213 WARNING: by putting in your own exception handler into IPython's main
1211 WARNING: by putting in your own exception handler into IPython's main
1214 execution loop, you run a very good chance of nasty crashes. This
1212 execution loop, you run a very good chance of nasty crashes. This
1215 facility should only be used if you really know what you are doing."""
1213 facility should only be used if you really know what you are doing."""
1216
1214
1217 assert type(exc_tuple)==type(()) , \
1215 assert type(exc_tuple)==type(()) , \
1218 "The custom exceptions must be given AS A TUPLE."
1216 "The custom exceptions must be given AS A TUPLE."
1219
1217
1220 def dummy_handler(self,etype,value,tb):
1218 def dummy_handler(self,etype,value,tb):
1221 print '*** Simple custom exception handler ***'
1219 print '*** Simple custom exception handler ***'
1222 print 'Exception type :',etype
1220 print 'Exception type :',etype
1223 print 'Exception value:',value
1221 print 'Exception value:',value
1224 print 'Traceback :',tb
1222 print 'Traceback :',tb
1225 print 'Source code :','\n'.join(self.buffer)
1223 print 'Source code :','\n'.join(self.buffer)
1226
1224
1227 if handler is None: handler = dummy_handler
1225 if handler is None: handler = dummy_handler
1228
1226
1229 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1227 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1230 self.custom_exceptions = exc_tuple
1228 self.custom_exceptions = exc_tuple
1231
1229
1232 def excepthook(self, etype, value, tb):
1230 def excepthook(self, etype, value, tb):
1233 """One more defense for GUI apps that call sys.excepthook.
1231 """One more defense for GUI apps that call sys.excepthook.
1234
1232
1235 GUI frameworks like wxPython trap exceptions and call
1233 GUI frameworks like wxPython trap exceptions and call
1236 sys.excepthook themselves. I guess this is a feature that
1234 sys.excepthook themselves. I guess this is a feature that
1237 enables them to keep running after exceptions that would
1235 enables them to keep running after exceptions that would
1238 otherwise kill their mainloop. This is a bother for IPython
1236 otherwise kill their mainloop. This is a bother for IPython
1239 which excepts to catch all of the program exceptions with a try:
1237 which excepts to catch all of the program exceptions with a try:
1240 except: statement.
1238 except: statement.
1241
1239
1242 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1240 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1243 any app directly invokes sys.excepthook, it will look to the user like
1241 any app directly invokes sys.excepthook, it will look to the user like
1244 IPython crashed. In order to work around this, we can disable the
1242 IPython crashed. In order to work around this, we can disable the
1245 CrashHandler and replace it with this excepthook instead, which prints a
1243 CrashHandler and replace it with this excepthook instead, which prints a
1246 regular traceback using our InteractiveTB. In this fashion, apps which
1244 regular traceback using our InteractiveTB. In this fashion, apps which
1247 call sys.excepthook will generate a regular-looking exception from
1245 call sys.excepthook will generate a regular-looking exception from
1248 IPython, and the CrashHandler will only be triggered by real IPython
1246 IPython, and the CrashHandler will only be triggered by real IPython
1249 crashes.
1247 crashes.
1250
1248
1251 This hook should be used sparingly, only in places which are not likely
1249 This hook should be used sparingly, only in places which are not likely
1252 to be true IPython errors.
1250 to be true IPython errors.
1253 """
1251 """
1254 self.showtraceback((etype,value,tb),tb_offset=0)
1252 self.showtraceback((etype,value,tb),tb_offset=0)
1255
1253
1256 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1254 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1257 exception_only=False):
1255 exception_only=False):
1258 """Display the exception that just occurred.
1256 """Display the exception that just occurred.
1259
1257
1260 If nothing is known about the exception, this is the method which
1258 If nothing is known about the exception, this is the method which
1261 should be used throughout the code for presenting user tracebacks,
1259 should be used throughout the code for presenting user tracebacks,
1262 rather than directly invoking the InteractiveTB object.
1260 rather than directly invoking the InteractiveTB object.
1263
1261
1264 A specific showsyntaxerror() also exists, but this method can take
1262 A specific showsyntaxerror() also exists, but this method can take
1265 care of calling it if needed, so unless you are explicitly catching a
1263 care of calling it if needed, so unless you are explicitly catching a
1266 SyntaxError exception, don't try to analyze the stack manually and
1264 SyntaxError exception, don't try to analyze the stack manually and
1267 simply call this method."""
1265 simply call this method."""
1268
1266
1269 try:
1267 try:
1270 if exc_tuple is None:
1268 if exc_tuple is None:
1271 etype, value, tb = sys.exc_info()
1269 etype, value, tb = sys.exc_info()
1272 else:
1270 else:
1273 etype, value, tb = exc_tuple
1271 etype, value, tb = exc_tuple
1274
1272
1275 if etype is None:
1273 if etype is None:
1276 if hasattr(sys, 'last_type'):
1274 if hasattr(sys, 'last_type'):
1277 etype, value, tb = sys.last_type, sys.last_value, \
1275 etype, value, tb = sys.last_type, sys.last_value, \
1278 sys.last_traceback
1276 sys.last_traceback
1279 else:
1277 else:
1280 self.write_err('No traceback available to show.\n')
1278 self.write_err('No traceback available to show.\n')
1281 return
1279 return
1282
1280
1283 if etype is SyntaxError:
1281 if etype is SyntaxError:
1284 # Though this won't be called by syntax errors in the input
1282 # Though this won't be called by syntax errors in the input
1285 # line, there may be SyntaxError cases whith imported code.
1283 # line, there may be SyntaxError cases whith imported code.
1286 self.showsyntaxerror(filename)
1284 self.showsyntaxerror(filename)
1287 elif etype is UsageError:
1285 elif etype is UsageError:
1288 print "UsageError:", value
1286 print "UsageError:", value
1289 else:
1287 else:
1290 # WARNING: these variables are somewhat deprecated and not
1288 # WARNING: these variables are somewhat deprecated and not
1291 # necessarily safe to use in a threaded environment, but tools
1289 # necessarily safe to use in a threaded environment, but tools
1292 # like pdb depend on their existence, so let's set them. If we
1290 # like pdb depend on their existence, so let's set them. If we
1293 # find problems in the field, we'll need to revisit their use.
1291 # find problems in the field, we'll need to revisit their use.
1294 sys.last_type = etype
1292 sys.last_type = etype
1295 sys.last_value = value
1293 sys.last_value = value
1296 sys.last_traceback = tb
1294 sys.last_traceback = tb
1297
1295
1298 if etype in self.custom_exceptions:
1296 if etype in self.custom_exceptions:
1299 # FIXME: Old custom traceback objects may just return a
1297 # FIXME: Old custom traceback objects may just return a
1300 # string, in that case we just put it into a list
1298 # string, in that case we just put it into a list
1301 stb = self.CustomTB(etype, value, tb, tb_offset)
1299 stb = self.CustomTB(etype, value, tb, tb_offset)
1302 if isinstance(ctb, basestring):
1300 if isinstance(ctb, basestring):
1303 stb = [stb]
1301 stb = [stb]
1304 else:
1302 else:
1305 if exception_only:
1303 if exception_only:
1306 stb = ['An exception has occurred, use %tb to see '
1304 stb = ['An exception has occurred, use %tb to see '
1307 'the full traceback.\n']
1305 'the full traceback.\n']
1308 stb.extend(self.InteractiveTB.get_exception_only(etype,
1306 stb.extend(self.InteractiveTB.get_exception_only(etype,
1309 value))
1307 value))
1310 else:
1308 else:
1311 stb = self.InteractiveTB.structured_traceback(etype,
1309 stb = self.InteractiveTB.structured_traceback(etype,
1312 value, tb, tb_offset=tb_offset)
1310 value, tb, tb_offset=tb_offset)
1313 # FIXME: the pdb calling should be done by us, not by
1311 # FIXME: the pdb calling should be done by us, not by
1314 # the code computing the traceback.
1312 # the code computing the traceback.
1315 if self.InteractiveTB.call_pdb:
1313 if self.InteractiveTB.call_pdb:
1316 # pdb mucks up readline, fix it back
1314 # pdb mucks up readline, fix it back
1317 self.set_completer()
1315 self.set_completer()
1318
1316
1319 # Actually show the traceback
1317 # Actually show the traceback
1320 self._showtraceback(etype, value, stb)
1318 self._showtraceback(etype, value, stb)
1321
1319
1322 except KeyboardInterrupt:
1320 except KeyboardInterrupt:
1323 self.write_err("\nKeyboardInterrupt\n")
1321 self.write_err("\nKeyboardInterrupt\n")
1324
1322
1325 def _showtraceback(self, etype, evalue, stb):
1323 def _showtraceback(self, etype, evalue, stb):
1326 """Actually show a traceback.
1324 """Actually show a traceback.
1327
1325
1328 Subclasses may override this method to put the traceback on a different
1326 Subclasses may override this method to put the traceback on a different
1329 place, like a side channel.
1327 place, like a side channel.
1330 """
1328 """
1331 # FIXME: this should use the proper write channels, but our test suite
1329 # FIXME: this should use the proper write channels, but our test suite
1332 # relies on it coming out of stdout...
1330 # relies on it coming out of stdout...
1333 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1331 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1334
1332
1335 def showsyntaxerror(self, filename=None):
1333 def showsyntaxerror(self, filename=None):
1336 """Display the syntax error that just occurred.
1334 """Display the syntax error that just occurred.
1337
1335
1338 This doesn't display a stack trace because there isn't one.
1336 This doesn't display a stack trace because there isn't one.
1339
1337
1340 If a filename is given, it is stuffed in the exception instead
1338 If a filename is given, it is stuffed in the exception instead
1341 of what was there before (because Python's parser always uses
1339 of what was there before (because Python's parser always uses
1342 "<string>" when reading from a string).
1340 "<string>" when reading from a string).
1343 """
1341 """
1344 etype, value, last_traceback = sys.exc_info()
1342 etype, value, last_traceback = sys.exc_info()
1345
1343
1346 # See note about these variables in showtraceback() above
1344 # See note about these variables in showtraceback() above
1347 sys.last_type = etype
1345 sys.last_type = etype
1348 sys.last_value = value
1346 sys.last_value = value
1349 sys.last_traceback = last_traceback
1347 sys.last_traceback = last_traceback
1350
1348
1351 if filename and etype is SyntaxError:
1349 if filename and etype is SyntaxError:
1352 # Work hard to stuff the correct filename in the exception
1350 # Work hard to stuff the correct filename in the exception
1353 try:
1351 try:
1354 msg, (dummy_filename, lineno, offset, line) = value
1352 msg, (dummy_filename, lineno, offset, line) = value
1355 except:
1353 except:
1356 # Not the format we expect; leave it alone
1354 # Not the format we expect; leave it alone
1357 pass
1355 pass
1358 else:
1356 else:
1359 # Stuff in the right filename
1357 # Stuff in the right filename
1360 try:
1358 try:
1361 # Assume SyntaxError is a class exception
1359 # Assume SyntaxError is a class exception
1362 value = SyntaxError(msg, (filename, lineno, offset, line))
1360 value = SyntaxError(msg, (filename, lineno, offset, line))
1363 except:
1361 except:
1364 # If that failed, assume SyntaxError is a string
1362 # If that failed, assume SyntaxError is a string
1365 value = msg, (filename, lineno, offset, line)
1363 value = msg, (filename, lineno, offset, line)
1366 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1364 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1367 self._showtraceback(etype, value, stb)
1365 self._showtraceback(etype, value, stb)
1368
1366
1369 #-------------------------------------------------------------------------
1367 #-------------------------------------------------------------------------
1370 # Things related to tab completion
1368 # Things related to tab completion
1371 #-------------------------------------------------------------------------
1369 #-------------------------------------------------------------------------
1372
1370
1373 def complete(self, text, line=None, cursor_pos=None):
1371 def complete(self, text, line=None, cursor_pos=None):
1374 """Return the completed text and a list of completions.
1372 """Return the completed text and a list of completions.
1375
1373
1376 Parameters
1374 Parameters
1377 ----------
1375 ----------
1378
1376
1379 text : string
1377 text : string
1380 A string of text to be completed on. It can be given as empty and
1378 A string of text to be completed on. It can be given as empty and
1381 instead a line/position pair are given. In this case, the
1379 instead a line/position pair are given. In this case, the
1382 completer itself will split the line like readline does.
1380 completer itself will split the line like readline does.
1383
1381
1384 line : string, optional
1382 line : string, optional
1385 The complete line that text is part of.
1383 The complete line that text is part of.
1386
1384
1387 cursor_pos : int, optional
1385 cursor_pos : int, optional
1388 The position of the cursor on the input line.
1386 The position of the cursor on the input line.
1389
1387
1390 Returns
1388 Returns
1391 -------
1389 -------
1392 text : string
1390 text : string
1393 The actual text that was completed.
1391 The actual text that was completed.
1394
1392
1395 matches : list
1393 matches : list
1396 A sorted list with all possible completions.
1394 A sorted list with all possible completions.
1397
1395
1398 The optional arguments allow the completion to take more context into
1396 The optional arguments allow the completion to take more context into
1399 account, and are part of the low-level completion API.
1397 account, and are part of the low-level completion API.
1400
1398
1401 This is a wrapper around the completion mechanism, similar to what
1399 This is a wrapper around the completion mechanism, similar to what
1402 readline does at the command line when the TAB key is hit. By
1400 readline does at the command line when the TAB key is hit. By
1403 exposing it as a method, it can be used by other non-readline
1401 exposing it as a method, it can be used by other non-readline
1404 environments (such as GUIs) for text completion.
1402 environments (such as GUIs) for text completion.
1405
1403
1406 Simple usage example:
1404 Simple usage example:
1407
1405
1408 In [1]: x = 'hello'
1406 In [1]: x = 'hello'
1409
1407
1410 In [2]: _ip.complete('x.l')
1408 In [2]: _ip.complete('x.l')
1411 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1409 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1412 """
1410 """
1413
1411
1414 # Inject names into __builtin__ so we can complete on the added names.
1412 # Inject names into __builtin__ so we can complete on the added names.
1415 with self.builtin_trap:
1413 with self.builtin_trap:
1416 return self.Completer.complete(text, line, cursor_pos)
1414 return self.Completer.complete(text, line, cursor_pos)
1417
1415
1418 def set_custom_completer(self, completer, pos=0):
1416 def set_custom_completer(self, completer, pos=0):
1419 """Adds a new custom completer function.
1417 """Adds a new custom completer function.
1420
1418
1421 The position argument (defaults to 0) is the index in the completers
1419 The position argument (defaults to 0) is the index in the completers
1422 list where you want the completer to be inserted."""
1420 list where you want the completer to be inserted."""
1423
1421
1424 newcomp = new.instancemethod(completer,self.Completer,
1422 newcomp = new.instancemethod(completer,self.Completer,
1425 self.Completer.__class__)
1423 self.Completer.__class__)
1426 self.Completer.matchers.insert(pos,newcomp)
1424 self.Completer.matchers.insert(pos,newcomp)
1427
1425
1428 def set_completer(self):
1426 def set_completer(self):
1429 """Reset readline's completer to be our own."""
1427 """Reset readline's completer to be our own."""
1430 self.readline.set_completer(self.Completer.rlcomplete)
1428 self.readline.set_completer(self.Completer.rlcomplete)
1431
1429
1432 def set_completer_frame(self, frame=None):
1430 def set_completer_frame(self, frame=None):
1433 """Set the frame of the completer."""
1431 """Set the frame of the completer."""
1434 if frame:
1432 if frame:
1435 self.Completer.namespace = frame.f_locals
1433 self.Completer.namespace = frame.f_locals
1436 self.Completer.global_namespace = frame.f_globals
1434 self.Completer.global_namespace = frame.f_globals
1437 else:
1435 else:
1438 self.Completer.namespace = self.user_ns
1436 self.Completer.namespace = self.user_ns
1439 self.Completer.global_namespace = self.user_global_ns
1437 self.Completer.global_namespace = self.user_global_ns
1440
1438
1441 #-------------------------------------------------------------------------
1439 #-------------------------------------------------------------------------
1442 # Things related to readline
1440 # Things related to readline
1443 #-------------------------------------------------------------------------
1441 #-------------------------------------------------------------------------
1444
1442
1445 def init_readline(self):
1443 def init_readline(self):
1446 """Command history completion/saving/reloading."""
1444 """Command history completion/saving/reloading."""
1447
1445
1448 if self.readline_use:
1446 if self.readline_use:
1449 import IPython.utils.rlineimpl as readline
1447 import IPython.utils.rlineimpl as readline
1450
1448
1451 self.rl_next_input = None
1449 self.rl_next_input = None
1452 self.rl_do_indent = False
1450 self.rl_do_indent = False
1453
1451
1454 if not self.readline_use or not readline.have_readline:
1452 if not self.readline_use or not readline.have_readline:
1455 self.has_readline = False
1453 self.has_readline = False
1456 self.readline = None
1454 self.readline = None
1457 # Set a number of methods that depend on readline to be no-op
1455 # Set a number of methods that depend on readline to be no-op
1458 self.savehist = no_op
1456 self.savehist = no_op
1459 self.reloadhist = no_op
1457 self.reloadhist = no_op
1460 self.set_completer = no_op
1458 self.set_completer = no_op
1461 self.set_custom_completer = no_op
1459 self.set_custom_completer = no_op
1462 self.set_completer_frame = no_op
1460 self.set_completer_frame = no_op
1463 warn('Readline services not available or not loaded.')
1461 warn('Readline services not available or not loaded.')
1464 else:
1462 else:
1465 self.has_readline = True
1463 self.has_readline = True
1466 self.readline = readline
1464 self.readline = readline
1467 sys.modules['readline'] = readline
1465 sys.modules['readline'] = readline
1468 import atexit
1466 import atexit
1469 from IPython.core.completer import IPCompleter
1467 from IPython.core.completer import IPCompleter
1470 self.Completer = IPCompleter(self,
1468 self.Completer = IPCompleter(self,
1471 self.user_ns,
1469 self.user_ns,
1472 self.user_global_ns,
1470 self.user_global_ns,
1473 self.readline_omit__names,
1471 self.readline_omit__names,
1474 self.alias_manager.alias_table)
1472 self.alias_manager.alias_table)
1475 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1473 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1476 self.strdispatchers['complete_command'] = sdisp
1474 self.strdispatchers['complete_command'] = sdisp
1477 self.Completer.custom_completers = sdisp
1475 self.Completer.custom_completers = sdisp
1478 # Platform-specific configuration
1476 # Platform-specific configuration
1479 if os.name == 'nt':
1477 if os.name == 'nt':
1480 self.readline_startup_hook = readline.set_pre_input_hook
1478 self.readline_startup_hook = readline.set_pre_input_hook
1481 else:
1479 else:
1482 self.readline_startup_hook = readline.set_startup_hook
1480 self.readline_startup_hook = readline.set_startup_hook
1483
1481
1484 # Load user's initrc file (readline config)
1482 # Load user's initrc file (readline config)
1485 # Or if libedit is used, load editrc.
1483 # Or if libedit is used, load editrc.
1486 inputrc_name = os.environ.get('INPUTRC')
1484 inputrc_name = os.environ.get('INPUTRC')
1487 if inputrc_name is None:
1485 if inputrc_name is None:
1488 home_dir = get_home_dir()
1486 home_dir = get_home_dir()
1489 if home_dir is not None:
1487 if home_dir is not None:
1490 inputrc_name = '.inputrc'
1488 inputrc_name = '.inputrc'
1491 if readline.uses_libedit:
1489 if readline.uses_libedit:
1492 inputrc_name = '.editrc'
1490 inputrc_name = '.editrc'
1493 inputrc_name = os.path.join(home_dir, inputrc_name)
1491 inputrc_name = os.path.join(home_dir, inputrc_name)
1494 if os.path.isfile(inputrc_name):
1492 if os.path.isfile(inputrc_name):
1495 try:
1493 try:
1496 readline.read_init_file(inputrc_name)
1494 readline.read_init_file(inputrc_name)
1497 except:
1495 except:
1498 warn('Problems reading readline initialization file <%s>'
1496 warn('Problems reading readline initialization file <%s>'
1499 % inputrc_name)
1497 % inputrc_name)
1500
1498
1501 # save this in sys so embedded copies can restore it properly
1499 # save this in sys so embedded copies can restore it properly
1502 sys.ipcompleter = self.Completer.rlcomplete
1500 sys.ipcompleter = self.Completer.rlcomplete
1503 self.set_completer()
1501 self.set_completer()
1504
1502
1505 # Configure readline according to user's prefs
1503 # Configure readline according to user's prefs
1506 # This is only done if GNU readline is being used. If libedit
1504 # This is only done if GNU readline is being used. If libedit
1507 # is being used (as on Leopard) the readline config is
1505 # is being used (as on Leopard) the readline config is
1508 # not run as the syntax for libedit is different.
1506 # not run as the syntax for libedit is different.
1509 if not readline.uses_libedit:
1507 if not readline.uses_libedit:
1510 for rlcommand in self.readline_parse_and_bind:
1508 for rlcommand in self.readline_parse_and_bind:
1511 #print "loading rl:",rlcommand # dbg
1509 #print "loading rl:",rlcommand # dbg
1512 readline.parse_and_bind(rlcommand)
1510 readline.parse_and_bind(rlcommand)
1513
1511
1514 # Remove some chars from the delimiters list. If we encounter
1512 # Remove some chars from the delimiters list. If we encounter
1515 # unicode chars, discard them.
1513 # unicode chars, discard them.
1516 delims = readline.get_completer_delims().encode("ascii", "ignore")
1514 delims = readline.get_completer_delims().encode("ascii", "ignore")
1517 delims = delims.translate(string._idmap,
1515 delims = delims.translate(string._idmap,
1518 self.readline_remove_delims)
1516 self.readline_remove_delims)
1519 readline.set_completer_delims(delims)
1517 readline.set_completer_delims(delims)
1520 # otherwise we end up with a monster history after a while:
1518 # otherwise we end up with a monster history after a while:
1521 readline.set_history_length(1000)
1519 readline.set_history_length(1000)
1522 try:
1520 try:
1523 #print '*** Reading readline history' # dbg
1521 #print '*** Reading readline history' # dbg
1524 readline.read_history_file(self.histfile)
1522 readline.read_history_file(self.histfile)
1525 except IOError:
1523 except IOError:
1526 pass # It doesn't exist yet.
1524 pass # It doesn't exist yet.
1527
1525
1528 atexit.register(self.atexit_operations)
1526 atexit.register(self.atexit_operations)
1529 del atexit
1527 del atexit
1530
1528
1531 # Configure auto-indent for all platforms
1529 # Configure auto-indent for all platforms
1532 self.set_autoindent(self.autoindent)
1530 self.set_autoindent(self.autoindent)
1533
1531
1534 def set_next_input(self, s):
1532 def set_next_input(self, s):
1535 """ Sets the 'default' input string for the next command line.
1533 """ Sets the 'default' input string for the next command line.
1536
1534
1537 Requires readline.
1535 Requires readline.
1538
1536
1539 Example:
1537 Example:
1540
1538
1541 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1539 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1542 [D:\ipython]|2> Hello Word_ # cursor is here
1540 [D:\ipython]|2> Hello Word_ # cursor is here
1543 """
1541 """
1544
1542
1545 self.rl_next_input = s
1543 self.rl_next_input = s
1546
1544
1547 # Maybe move this to the terminal subclass?
1545 # Maybe move this to the terminal subclass?
1548 def pre_readline(self):
1546 def pre_readline(self):
1549 """readline hook to be used at the start of each line.
1547 """readline hook to be used at the start of each line.
1550
1548
1551 Currently it handles auto-indent only."""
1549 Currently it handles auto-indent only."""
1552
1550
1553 if self.rl_do_indent:
1551 if self.rl_do_indent:
1554 self.readline.insert_text(self._indent_current_str())
1552 self.readline.insert_text(self._indent_current_str())
1555 if self.rl_next_input is not None:
1553 if self.rl_next_input is not None:
1556 self.readline.insert_text(self.rl_next_input)
1554 self.readline.insert_text(self.rl_next_input)
1557 self.rl_next_input = None
1555 self.rl_next_input = None
1558
1556
1559 def _indent_current_str(self):
1557 def _indent_current_str(self):
1560 """return the current level of indentation as a string"""
1558 """return the current level of indentation as a string"""
1561 return self.indent_current_nsp * ' '
1559 return self.indent_current_nsp * ' '
1562
1560
1563 #-------------------------------------------------------------------------
1561 #-------------------------------------------------------------------------
1564 # Things related to magics
1562 # Things related to magics
1565 #-------------------------------------------------------------------------
1563 #-------------------------------------------------------------------------
1566
1564
1567 def init_magics(self):
1565 def init_magics(self):
1568 # FIXME: Move the color initialization to the DisplayHook, which
1566 # FIXME: Move the color initialization to the DisplayHook, which
1569 # should be split into a prompt manager and displayhook. We probably
1567 # should be split into a prompt manager and displayhook. We probably
1570 # even need a centralize colors management object.
1568 # even need a centralize colors management object.
1571 self.magic_colors(self.colors)
1569 self.magic_colors(self.colors)
1572 # History was moved to a separate module
1570 # History was moved to a separate module
1573 from . import history
1571 from . import history
1574 history.init_ipython(self)
1572 history.init_ipython(self)
1575
1573
1576 def magic(self,arg_s):
1574 def magic(self,arg_s):
1577 """Call a magic function by name.
1575 """Call a magic function by name.
1578
1576
1579 Input: a string containing the name of the magic function to call and any
1577 Input: a string containing the name of the magic function to call and any
1580 additional arguments to be passed to the magic.
1578 additional arguments to be passed to the magic.
1581
1579
1582 magic('name -opt foo bar') is equivalent to typing at the ipython
1580 magic('name -opt foo bar') is equivalent to typing at the ipython
1583 prompt:
1581 prompt:
1584
1582
1585 In[1]: %name -opt foo bar
1583 In[1]: %name -opt foo bar
1586
1584
1587 To call a magic without arguments, simply use magic('name').
1585 To call a magic without arguments, simply use magic('name').
1588
1586
1589 This provides a proper Python function to call IPython's magics in any
1587 This provides a proper Python function to call IPython's magics in any
1590 valid Python code you can type at the interpreter, including loops and
1588 valid Python code you can type at the interpreter, including loops and
1591 compound statements.
1589 compound statements.
1592 """
1590 """
1593 args = arg_s.split(' ',1)
1591 args = arg_s.split(' ',1)
1594 magic_name = args[0]
1592 magic_name = args[0]
1595 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1593 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1596
1594
1597 try:
1595 try:
1598 magic_args = args[1]
1596 magic_args = args[1]
1599 except IndexError:
1597 except IndexError:
1600 magic_args = ''
1598 magic_args = ''
1601 fn = getattr(self,'magic_'+magic_name,None)
1599 fn = getattr(self,'magic_'+magic_name,None)
1602 if fn is None:
1600 if fn is None:
1603 error("Magic function `%s` not found." % magic_name)
1601 error("Magic function `%s` not found." % magic_name)
1604 else:
1602 else:
1605 magic_args = self.var_expand(magic_args,1)
1603 magic_args = self.var_expand(magic_args,1)
1606 with nested(self.builtin_trap,):
1604 with nested(self.builtin_trap,):
1607 result = fn(magic_args)
1605 result = fn(magic_args)
1608 return result
1606 return result
1609
1607
1610 def define_magic(self, magicname, func):
1608 def define_magic(self, magicname, func):
1611 """Expose own function as magic function for ipython
1609 """Expose own function as magic function for ipython
1612
1610
1613 def foo_impl(self,parameter_s=''):
1611 def foo_impl(self,parameter_s=''):
1614 'My very own magic!. (Use docstrings, IPython reads them).'
1612 'My very own magic!. (Use docstrings, IPython reads them).'
1615 print 'Magic function. Passed parameter is between < >:'
1613 print 'Magic function. Passed parameter is between < >:'
1616 print '<%s>' % parameter_s
1614 print '<%s>' % parameter_s
1617 print 'The self object is:',self
1615 print 'The self object is:',self
1618
1616
1619 self.define_magic('foo',foo_impl)
1617 self.define_magic('foo',foo_impl)
1620 """
1618 """
1621
1619
1622 import new
1620 import new
1623 im = new.instancemethod(func,self, self.__class__)
1621 im = new.instancemethod(func,self, self.__class__)
1624 old = getattr(self, "magic_" + magicname, None)
1622 old = getattr(self, "magic_" + magicname, None)
1625 setattr(self, "magic_" + magicname, im)
1623 setattr(self, "magic_" + magicname, im)
1626 return old
1624 return old
1627
1625
1628 #-------------------------------------------------------------------------
1626 #-------------------------------------------------------------------------
1629 # Things related to macros
1627 # Things related to macros
1630 #-------------------------------------------------------------------------
1628 #-------------------------------------------------------------------------
1631
1629
1632 def define_macro(self, name, themacro):
1630 def define_macro(self, name, themacro):
1633 """Define a new macro
1631 """Define a new macro
1634
1632
1635 Parameters
1633 Parameters
1636 ----------
1634 ----------
1637 name : str
1635 name : str
1638 The name of the macro.
1636 The name of the macro.
1639 themacro : str or Macro
1637 themacro : str or Macro
1640 The action to do upon invoking the macro. If a string, a new
1638 The action to do upon invoking the macro. If a string, a new
1641 Macro object is created by passing the string to it.
1639 Macro object is created by passing the string to it.
1642 """
1640 """
1643
1641
1644 from IPython.core import macro
1642 from IPython.core import macro
1645
1643
1646 if isinstance(themacro, basestring):
1644 if isinstance(themacro, basestring):
1647 themacro = macro.Macro(themacro)
1645 themacro = macro.Macro(themacro)
1648 if not isinstance(themacro, macro.Macro):
1646 if not isinstance(themacro, macro.Macro):
1649 raise ValueError('A macro must be a string or a Macro instance.')
1647 raise ValueError('A macro must be a string or a Macro instance.')
1650 self.user_ns[name] = themacro
1648 self.user_ns[name] = themacro
1651
1649
1652 #-------------------------------------------------------------------------
1650 #-------------------------------------------------------------------------
1653 # Things related to the running of system commands
1651 # Things related to the running of system commands
1654 #-------------------------------------------------------------------------
1652 #-------------------------------------------------------------------------
1655
1653
1656 def system(self, cmd):
1654 def system(self, cmd):
1657 """Make a system call, using IPython."""
1655 """Call the given cmd in a subprocess."""
1658 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
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 # Things related to aliases
1677 # Things related to aliases
1662 #-------------------------------------------------------------------------
1678 #-------------------------------------------------------------------------
1663
1679
1664 def init_alias(self):
1680 def init_alias(self):
1665 self.alias_manager = AliasManager(shell=self, config=self.config)
1681 self.alias_manager = AliasManager(shell=self, config=self.config)
1666 self.ns_table['alias'] = self.alias_manager.alias_table,
1682 self.ns_table['alias'] = self.alias_manager.alias_table,
1667
1683
1668 #-------------------------------------------------------------------------
1684 #-------------------------------------------------------------------------
1669 # Things related to extensions and plugins
1685 # Things related to extensions and plugins
1670 #-------------------------------------------------------------------------
1686 #-------------------------------------------------------------------------
1671
1687
1672 def init_extension_manager(self):
1688 def init_extension_manager(self):
1673 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1689 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1674
1690
1675 def init_plugin_manager(self):
1691 def init_plugin_manager(self):
1676 self.plugin_manager = PluginManager(config=self.config)
1692 self.plugin_manager = PluginManager(config=self.config)
1677
1693
1678 #-------------------------------------------------------------------------
1694 #-------------------------------------------------------------------------
1679 # Things related to payloads
1695 # Things related to payloads
1680 #-------------------------------------------------------------------------
1696 #-------------------------------------------------------------------------
1681
1697
1682 def init_payload(self):
1698 def init_payload(self):
1683 self.payload_manager = PayloadManager(config=self.config)
1699 self.payload_manager = PayloadManager(config=self.config)
1684
1700
1685 #-------------------------------------------------------------------------
1701 #-------------------------------------------------------------------------
1686 # Things related to the prefilter
1702 # Things related to the prefilter
1687 #-------------------------------------------------------------------------
1703 #-------------------------------------------------------------------------
1688
1704
1689 def init_prefilter(self):
1705 def init_prefilter(self):
1690 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1706 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1691 # Ultimately this will be refactored in the new interpreter code, but
1707 # Ultimately this will be refactored in the new interpreter code, but
1692 # for now, we should expose the main prefilter method (there's legacy
1708 # for now, we should expose the main prefilter method (there's legacy
1693 # code out there that may rely on this).
1709 # code out there that may rely on this).
1694 self.prefilter = self.prefilter_manager.prefilter_lines
1710 self.prefilter = self.prefilter_manager.prefilter_lines
1695
1711
1696 #-------------------------------------------------------------------------
1712 #-------------------------------------------------------------------------
1697 # Things related to the running of code
1713 # Things related to the running of code
1698 #-------------------------------------------------------------------------
1714 #-------------------------------------------------------------------------
1699
1715
1700 def ex(self, cmd):
1716 def ex(self, cmd):
1701 """Execute a normal python statement in user namespace."""
1717 """Execute a normal python statement in user namespace."""
1702 with nested(self.builtin_trap,):
1718 with nested(self.builtin_trap,):
1703 exec cmd in self.user_global_ns, self.user_ns
1719 exec cmd in self.user_global_ns, self.user_ns
1704
1720
1705 def ev(self, expr):
1721 def ev(self, expr):
1706 """Evaluate python expression expr in user namespace.
1722 """Evaluate python expression expr in user namespace.
1707
1723
1708 Returns the result of evaluation
1724 Returns the result of evaluation
1709 """
1725 """
1710 with nested(self.builtin_trap,):
1726 with nested(self.builtin_trap,):
1711 return eval(expr, self.user_global_ns, self.user_ns)
1727 return eval(expr, self.user_global_ns, self.user_ns)
1712
1728
1713 def safe_execfile(self, fname, *where, **kw):
1729 def safe_execfile(self, fname, *where, **kw):
1714 """A safe version of the builtin execfile().
1730 """A safe version of the builtin execfile().
1715
1731
1716 This version will never throw an exception, but instead print
1732 This version will never throw an exception, but instead print
1717 helpful error messages to the screen. This only works on pure
1733 helpful error messages to the screen. This only works on pure
1718 Python files with the .py extension.
1734 Python files with the .py extension.
1719
1735
1720 Parameters
1736 Parameters
1721 ----------
1737 ----------
1722 fname : string
1738 fname : string
1723 The name of the file to be executed.
1739 The name of the file to be executed.
1724 where : tuple
1740 where : tuple
1725 One or two namespaces, passed to execfile() as (globals,locals).
1741 One or two namespaces, passed to execfile() as (globals,locals).
1726 If only one is given, it is passed as both.
1742 If only one is given, it is passed as both.
1727 exit_ignore : bool (False)
1743 exit_ignore : bool (False)
1728 If True, then silence SystemExit for non-zero status (it is always
1744 If True, then silence SystemExit for non-zero status (it is always
1729 silenced for zero status, as it is so common).
1745 silenced for zero status, as it is so common).
1730 """
1746 """
1731 kw.setdefault('exit_ignore', False)
1747 kw.setdefault('exit_ignore', False)
1732
1748
1733 fname = os.path.abspath(os.path.expanduser(fname))
1749 fname = os.path.abspath(os.path.expanduser(fname))
1734
1750
1735 # Make sure we have a .py file
1751 # Make sure we have a .py file
1736 if not fname.endswith('.py'):
1752 if not fname.endswith('.py'):
1737 warn('File must end with .py to be run using execfile: <%s>' % fname)
1753 warn('File must end with .py to be run using execfile: <%s>' % fname)
1738
1754
1739 # Make sure we can open the file
1755 # Make sure we can open the file
1740 try:
1756 try:
1741 with open(fname) as thefile:
1757 with open(fname) as thefile:
1742 pass
1758 pass
1743 except:
1759 except:
1744 warn('Could not open file <%s> for safe execution.' % fname)
1760 warn('Could not open file <%s> for safe execution.' % fname)
1745 return
1761 return
1746
1762
1747 # Find things also in current directory. This is needed to mimic the
1763 # Find things also in current directory. This is needed to mimic the
1748 # behavior of running a script from the system command line, where
1764 # behavior of running a script from the system command line, where
1749 # Python inserts the script's directory into sys.path
1765 # Python inserts the script's directory into sys.path
1750 dname = os.path.dirname(fname)
1766 dname = os.path.dirname(fname)
1751
1767
1752 with prepended_to_syspath(dname):
1768 with prepended_to_syspath(dname):
1753 try:
1769 try:
1754 execfile(fname,*where)
1770 execfile(fname,*where)
1755 except SystemExit, status:
1771 except SystemExit, status:
1756 # If the call was made with 0 or None exit status (sys.exit(0)
1772 # If the call was made with 0 or None exit status (sys.exit(0)
1757 # or sys.exit() ), don't bother showing a traceback, as both of
1773 # or sys.exit() ), don't bother showing a traceback, as both of
1758 # these are considered normal by the OS:
1774 # these are considered normal by the OS:
1759 # > python -c'import sys;sys.exit(0)'; echo $?
1775 # > python -c'import sys;sys.exit(0)'; echo $?
1760 # 0
1776 # 0
1761 # > python -c'import sys;sys.exit()'; echo $?
1777 # > python -c'import sys;sys.exit()'; echo $?
1762 # 0
1778 # 0
1763 # For other exit status, we show the exception unless
1779 # For other exit status, we show the exception unless
1764 # explicitly silenced, but only in short form.
1780 # explicitly silenced, but only in short form.
1765 if status.code not in (0, None) and not kw['exit_ignore']:
1781 if status.code not in (0, None) and not kw['exit_ignore']:
1766 self.showtraceback(exception_only=True)
1782 self.showtraceback(exception_only=True)
1767 except:
1783 except:
1768 self.showtraceback()
1784 self.showtraceback()
1769
1785
1770 def safe_execfile_ipy(self, fname):
1786 def safe_execfile_ipy(self, fname):
1771 """Like safe_execfile, but for .ipy files with IPython syntax.
1787 """Like safe_execfile, but for .ipy files with IPython syntax.
1772
1788
1773 Parameters
1789 Parameters
1774 ----------
1790 ----------
1775 fname : str
1791 fname : str
1776 The name of the file to execute. The filename must have a
1792 The name of the file to execute. The filename must have a
1777 .ipy extension.
1793 .ipy extension.
1778 """
1794 """
1779 fname = os.path.abspath(os.path.expanduser(fname))
1795 fname = os.path.abspath(os.path.expanduser(fname))
1780
1796
1781 # Make sure we have a .py file
1797 # Make sure we have a .py file
1782 if not fname.endswith('.ipy'):
1798 if not fname.endswith('.ipy'):
1783 warn('File must end with .py to be run using execfile: <%s>' % fname)
1799 warn('File must end with .py to be run using execfile: <%s>' % fname)
1784
1800
1785 # Make sure we can open the file
1801 # Make sure we can open the file
1786 try:
1802 try:
1787 with open(fname) as thefile:
1803 with open(fname) as thefile:
1788 pass
1804 pass
1789 except:
1805 except:
1790 warn('Could not open file <%s> for safe execution.' % fname)
1806 warn('Could not open file <%s> for safe execution.' % fname)
1791 return
1807 return
1792
1808
1793 # Find things also in current directory. This is needed to mimic the
1809 # Find things also in current directory. This is needed to mimic the
1794 # behavior of running a script from the system command line, where
1810 # behavior of running a script from the system command line, where
1795 # Python inserts the script's directory into sys.path
1811 # Python inserts the script's directory into sys.path
1796 dname = os.path.dirname(fname)
1812 dname = os.path.dirname(fname)
1797
1813
1798 with prepended_to_syspath(dname):
1814 with prepended_to_syspath(dname):
1799 try:
1815 try:
1800 with open(fname) as thefile:
1816 with open(fname) as thefile:
1801 script = thefile.read()
1817 script = thefile.read()
1802 # self.runlines currently captures all exceptions
1818 # self.runlines currently captures all exceptions
1803 # raise in user code. It would be nice if there were
1819 # raise in user code. It would be nice if there were
1804 # versions of runlines, execfile that did raise, so
1820 # versions of runlines, execfile that did raise, so
1805 # we could catch the errors.
1821 # we could catch the errors.
1806 self.runlines(script, clean=True)
1822 self.runlines(script, clean=True)
1807 except:
1823 except:
1808 self.showtraceback()
1824 self.showtraceback()
1809 warn('Unknown failure executing file: <%s>' % fname)
1825 warn('Unknown failure executing file: <%s>' % fname)
1810
1826
1811 def runlines(self, lines, clean=False):
1827 def runlines(self, lines, clean=False):
1812 """Run a string of one or more lines of source.
1828 """Run a string of one or more lines of source.
1813
1829
1814 This method is capable of running a string containing multiple source
1830 This method is capable of running a string containing multiple source
1815 lines, as if they had been entered at the IPython prompt. Since it
1831 lines, as if they had been entered at the IPython prompt. Since it
1816 exposes IPython's processing machinery, the given strings can contain
1832 exposes IPython's processing machinery, the given strings can contain
1817 magic calls (%magic), special shell access (!cmd), etc.
1833 magic calls (%magic), special shell access (!cmd), etc.
1818 """
1834 """
1819
1835
1820 if isinstance(lines, (list, tuple)):
1836 if isinstance(lines, (list, tuple)):
1821 lines = '\n'.join(lines)
1837 lines = '\n'.join(lines)
1822
1838
1823 if clean:
1839 if clean:
1824 lines = self._cleanup_ipy_script(lines)
1840 lines = self._cleanup_ipy_script(lines)
1825
1841
1826 # We must start with a clean buffer, in case this is run from an
1842 # We must start with a clean buffer, in case this is run from an
1827 # interactive IPython session (via a magic, for example).
1843 # interactive IPython session (via a magic, for example).
1828 self.resetbuffer()
1844 self.resetbuffer()
1829 lines = lines.splitlines()
1845 lines = lines.splitlines()
1830 more = 0
1846 more = 0
1831 with nested(self.builtin_trap, self.display_trap):
1847 with nested(self.builtin_trap, self.display_trap):
1832 for line in lines:
1848 for line in lines:
1833 # skip blank lines so we don't mess up the prompt counter, but do
1849 # skip blank lines so we don't mess up the prompt counter, but do
1834 # NOT skip even a blank line if we are in a code block (more is
1850 # NOT skip even a blank line if we are in a code block (more is
1835 # true)
1851 # true)
1836
1852
1837 if line or more:
1853 if line or more:
1838 # push to raw history, so hist line numbers stay in sync
1854 # push to raw history, so hist line numbers stay in sync
1839 self.input_hist_raw.append(line + '\n')
1855 self.input_hist_raw.append(line + '\n')
1840 prefiltered = self.prefilter_manager.prefilter_lines(line,
1856 prefiltered = self.prefilter_manager.prefilter_lines(line,
1841 more)
1857 more)
1842 more = self.push_line(prefiltered)
1858 more = self.push_line(prefiltered)
1843 # IPython's runsource returns None if there was an error
1859 # IPython's runsource returns None if there was an error
1844 # compiling the code. This allows us to stop processing right
1860 # compiling the code. This allows us to stop processing right
1845 # away, so the user gets the error message at the right place.
1861 # away, so the user gets the error message at the right place.
1846 if more is None:
1862 if more is None:
1847 break
1863 break
1848 else:
1864 else:
1849 self.input_hist_raw.append("\n")
1865 self.input_hist_raw.append("\n")
1850 # final newline in case the input didn't have it, so that the code
1866 # final newline in case the input didn't have it, so that the code
1851 # actually does get executed
1867 # actually does get executed
1852 if more:
1868 if more:
1853 self.push_line('\n')
1869 self.push_line('\n')
1854
1870
1855 def runsource(self, source, filename='<input>', symbol='single'):
1871 def runsource(self, source, filename='<input>', symbol='single'):
1856 """Compile and run some source in the interpreter.
1872 """Compile and run some source in the interpreter.
1857
1873
1858 Arguments are as for compile_command().
1874 Arguments are as for compile_command().
1859
1875
1860 One several things can happen:
1876 One several things can happen:
1861
1877
1862 1) The input is incorrect; compile_command() raised an
1878 1) The input is incorrect; compile_command() raised an
1863 exception (SyntaxError or OverflowError). A syntax traceback
1879 exception (SyntaxError or OverflowError). A syntax traceback
1864 will be printed by calling the showsyntaxerror() method.
1880 will be printed by calling the showsyntaxerror() method.
1865
1881
1866 2) The input is incomplete, and more input is required;
1882 2) The input is incomplete, and more input is required;
1867 compile_command() returned None. Nothing happens.
1883 compile_command() returned None. Nothing happens.
1868
1884
1869 3) The input is complete; compile_command() returned a code
1885 3) The input is complete; compile_command() returned a code
1870 object. The code is executed by calling self.runcode() (which
1886 object. The code is executed by calling self.runcode() (which
1871 also handles run-time exceptions, except for SystemExit).
1887 also handles run-time exceptions, except for SystemExit).
1872
1888
1873 The return value is:
1889 The return value is:
1874
1890
1875 - True in case 2
1891 - True in case 2
1876
1892
1877 - False in the other cases, unless an exception is raised, where
1893 - False in the other cases, unless an exception is raised, where
1878 None is returned instead. This can be used by external callers to
1894 None is returned instead. This can be used by external callers to
1879 know whether to continue feeding input or not.
1895 know whether to continue feeding input or not.
1880
1896
1881 The return value can be used to decide whether to use sys.ps1 or
1897 The return value can be used to decide whether to use sys.ps1 or
1882 sys.ps2 to prompt the next line."""
1898 sys.ps2 to prompt the next line."""
1883
1899
1884 # if the source code has leading blanks, add 'if 1:\n' to it
1900 # if the source code has leading blanks, add 'if 1:\n' to it
1885 # this allows execution of indented pasted code. It is tempting
1901 # this allows execution of indented pasted code. It is tempting
1886 # to add '\n' at the end of source to run commands like ' a=1'
1902 # to add '\n' at the end of source to run commands like ' a=1'
1887 # directly, but this fails for more complicated scenarios
1903 # directly, but this fails for more complicated scenarios
1888 source=source.encode(self.stdin_encoding)
1904 source=source.encode(self.stdin_encoding)
1889 if source[:1] in [' ', '\t']:
1905 if source[:1] in [' ', '\t']:
1890 source = 'if 1:\n%s' % source
1906 source = 'if 1:\n%s' % source
1891
1907
1892 try:
1908 try:
1893 code = self.compile(source,filename,symbol)
1909 code = self.compile(source,filename,symbol)
1894 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1910 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1895 # Case 1
1911 # Case 1
1896 self.showsyntaxerror(filename)
1912 self.showsyntaxerror(filename)
1897 return None
1913 return None
1898
1914
1899 if code is None:
1915 if code is None:
1900 # Case 2
1916 # Case 2
1901 return True
1917 return True
1902
1918
1903 # Case 3
1919 # Case 3
1904 # We store the code object so that threaded shells and
1920 # We store the code object so that threaded shells and
1905 # custom exception handlers can access all this info if needed.
1921 # custom exception handlers can access all this info if needed.
1906 # The source corresponding to this can be obtained from the
1922 # The source corresponding to this can be obtained from the
1907 # buffer attribute as '\n'.join(self.buffer).
1923 # buffer attribute as '\n'.join(self.buffer).
1908 self.code_to_run = code
1924 self.code_to_run = code
1909 # now actually execute the code object
1925 # now actually execute the code object
1910 if self.runcode(code) == 0:
1926 if self.runcode(code) == 0:
1911 return False
1927 return False
1912 else:
1928 else:
1913 return None
1929 return None
1914
1930
1915 def runcode(self,code_obj):
1931 def runcode(self,code_obj):
1916 """Execute a code object.
1932 """Execute a code object.
1917
1933
1918 When an exception occurs, self.showtraceback() is called to display a
1934 When an exception occurs, self.showtraceback() is called to display a
1919 traceback.
1935 traceback.
1920
1936
1921 Return value: a flag indicating whether the code to be run completed
1937 Return value: a flag indicating whether the code to be run completed
1922 successfully:
1938 successfully:
1923
1939
1924 - 0: successful execution.
1940 - 0: successful execution.
1925 - 1: an error occurred.
1941 - 1: an error occurred.
1926 """
1942 """
1927
1943
1928 # Set our own excepthook in case the user code tries to call it
1944 # Set our own excepthook in case the user code tries to call it
1929 # directly, so that the IPython crash handler doesn't get triggered
1945 # directly, so that the IPython crash handler doesn't get triggered
1930 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1946 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1931
1947
1932 # we save the original sys.excepthook in the instance, in case config
1948 # we save the original sys.excepthook in the instance, in case config
1933 # code (such as magics) needs access to it.
1949 # code (such as magics) needs access to it.
1934 self.sys_excepthook = old_excepthook
1950 self.sys_excepthook = old_excepthook
1935 outflag = 1 # happens in more places, so it's easier as default
1951 outflag = 1 # happens in more places, so it's easier as default
1936 try:
1952 try:
1937 try:
1953 try:
1938 self.hooks.pre_runcode_hook()
1954 self.hooks.pre_runcode_hook()
1939 #rprint('Running code') # dbg
1955 #rprint('Running code') # dbg
1940 exec code_obj in self.user_global_ns, self.user_ns
1956 exec code_obj in self.user_global_ns, self.user_ns
1941 finally:
1957 finally:
1942 # Reset our crash handler in place
1958 # Reset our crash handler in place
1943 sys.excepthook = old_excepthook
1959 sys.excepthook = old_excepthook
1944 except SystemExit:
1960 except SystemExit:
1945 self.resetbuffer()
1961 self.resetbuffer()
1946 self.showtraceback(exception_only=True)
1962 self.showtraceback(exception_only=True)
1947 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1963 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1948 except self.custom_exceptions:
1964 except self.custom_exceptions:
1949 etype,value,tb = sys.exc_info()
1965 etype,value,tb = sys.exc_info()
1950 self.CustomTB(etype,value,tb)
1966 self.CustomTB(etype,value,tb)
1951 except:
1967 except:
1952 self.showtraceback()
1968 self.showtraceback()
1953 else:
1969 else:
1954 outflag = 0
1970 outflag = 0
1955 if softspace(sys.stdout, 0):
1971 if softspace(sys.stdout, 0):
1956 print
1972 print
1957 # Flush out code object which has been run (and source)
1973 # Flush out code object which has been run (and source)
1958 self.code_to_run = None
1974 self.code_to_run = None
1959 return outflag
1975 return outflag
1960
1976
1961 def push_line(self, line):
1977 def push_line(self, line):
1962 """Push a line to the interpreter.
1978 """Push a line to the interpreter.
1963
1979
1964 The line should not have a trailing newline; it may have
1980 The line should not have a trailing newline; it may have
1965 internal newlines. The line is appended to a buffer and the
1981 internal newlines. The line is appended to a buffer and the
1966 interpreter's runsource() method is called with the
1982 interpreter's runsource() method is called with the
1967 concatenated contents of the buffer as source. If this
1983 concatenated contents of the buffer as source. If this
1968 indicates that the command was executed or invalid, the buffer
1984 indicates that the command was executed or invalid, the buffer
1969 is reset; otherwise, the command is incomplete, and the buffer
1985 is reset; otherwise, the command is incomplete, and the buffer
1970 is left as it was after the line was appended. The return
1986 is left as it was after the line was appended. The return
1971 value is 1 if more input is required, 0 if the line was dealt
1987 value is 1 if more input is required, 0 if the line was dealt
1972 with in some way (this is the same as runsource()).
1988 with in some way (this is the same as runsource()).
1973 """
1989 """
1974
1990
1975 # autoindent management should be done here, and not in the
1991 # autoindent management should be done here, and not in the
1976 # interactive loop, since that one is only seen by keyboard input. We
1992 # interactive loop, since that one is only seen by keyboard input. We
1977 # need this done correctly even for code run via runlines (which uses
1993 # need this done correctly even for code run via runlines (which uses
1978 # push).
1994 # push).
1979
1995
1980 #print 'push line: <%s>' % line # dbg
1996 #print 'push line: <%s>' % line # dbg
1981 for subline in line.splitlines():
1997 for subline in line.splitlines():
1982 self._autoindent_update(subline)
1998 self._autoindent_update(subline)
1983 self.buffer.append(line)
1999 self.buffer.append(line)
1984 more = self.runsource('\n'.join(self.buffer), self.filename)
2000 more = self.runsource('\n'.join(self.buffer), self.filename)
1985 if not more:
2001 if not more:
1986 self.resetbuffer()
2002 self.resetbuffer()
1987 return more
2003 return more
1988
2004
1989 def resetbuffer(self):
2005 def resetbuffer(self):
1990 """Reset the input buffer."""
2006 """Reset the input buffer."""
1991 self.buffer[:] = []
2007 self.buffer[:] = []
1992
2008
1993 def _is_secondary_block_start(self, s):
2009 def _is_secondary_block_start(self, s):
1994 if not s.endswith(':'):
2010 if not s.endswith(':'):
1995 return False
2011 return False
1996 if (s.startswith('elif') or
2012 if (s.startswith('elif') or
1997 s.startswith('else') or
2013 s.startswith('else') or
1998 s.startswith('except') or
2014 s.startswith('except') or
1999 s.startswith('finally')):
2015 s.startswith('finally')):
2000 return True
2016 return True
2001
2017
2002 def _cleanup_ipy_script(self, script):
2018 def _cleanup_ipy_script(self, script):
2003 """Make a script safe for self.runlines()
2019 """Make a script safe for self.runlines()
2004
2020
2005 Currently, IPython is lines based, with blocks being detected by
2021 Currently, IPython is lines based, with blocks being detected by
2006 empty lines. This is a problem for block based scripts that may
2022 empty lines. This is a problem for block based scripts that may
2007 not have empty lines after blocks. This script adds those empty
2023 not have empty lines after blocks. This script adds those empty
2008 lines to make scripts safe for running in the current line based
2024 lines to make scripts safe for running in the current line based
2009 IPython.
2025 IPython.
2010 """
2026 """
2011 res = []
2027 res = []
2012 lines = script.splitlines()
2028 lines = script.splitlines()
2013 level = 0
2029 level = 0
2014
2030
2015 for l in lines:
2031 for l in lines:
2016 lstripped = l.lstrip()
2032 lstripped = l.lstrip()
2017 stripped = l.strip()
2033 stripped = l.strip()
2018 if not stripped:
2034 if not stripped:
2019 continue
2035 continue
2020 newlevel = len(l) - len(lstripped)
2036 newlevel = len(l) - len(lstripped)
2021 if level > 0 and newlevel == 0 and \
2037 if level > 0 and newlevel == 0 and \
2022 not self._is_secondary_block_start(stripped):
2038 not self._is_secondary_block_start(stripped):
2023 # add empty line
2039 # add empty line
2024 res.append('')
2040 res.append('')
2025 res.append(l)
2041 res.append(l)
2026 level = newlevel
2042 level = newlevel
2027
2043
2028 return '\n'.join(res) + '\n'
2044 return '\n'.join(res) + '\n'
2029
2045
2030 def _autoindent_update(self,line):
2046 def _autoindent_update(self,line):
2031 """Keep track of the indent level."""
2047 """Keep track of the indent level."""
2032
2048
2033 #debugx('line')
2049 #debugx('line')
2034 #debugx('self.indent_current_nsp')
2050 #debugx('self.indent_current_nsp')
2035 if self.autoindent:
2051 if self.autoindent:
2036 if line:
2052 if line:
2037 inisp = num_ini_spaces(line)
2053 inisp = num_ini_spaces(line)
2038 if inisp < self.indent_current_nsp:
2054 if inisp < self.indent_current_nsp:
2039 self.indent_current_nsp = inisp
2055 self.indent_current_nsp = inisp
2040
2056
2041 if line[-1] == ':':
2057 if line[-1] == ':':
2042 self.indent_current_nsp += 4
2058 self.indent_current_nsp += 4
2043 elif dedent_re.match(line):
2059 elif dedent_re.match(line):
2044 self.indent_current_nsp -= 4
2060 self.indent_current_nsp -= 4
2045 else:
2061 else:
2046 self.indent_current_nsp = 0
2062 self.indent_current_nsp = 0
2047
2063
2048 #-------------------------------------------------------------------------
2064 #-------------------------------------------------------------------------
2049 # Things related to GUI support and pylab
2065 # Things related to GUI support and pylab
2050 #-------------------------------------------------------------------------
2066 #-------------------------------------------------------------------------
2051
2067
2052 def enable_pylab(self, gui=None):
2068 def enable_pylab(self, gui=None):
2053 raise NotImplementedError('Implement enable_pylab in a subclass')
2069 raise NotImplementedError('Implement enable_pylab in a subclass')
2054
2070
2055 #-------------------------------------------------------------------------
2071 #-------------------------------------------------------------------------
2056 # Utilities
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 def var_expand(self,cmd,depth=0):
2075 def var_expand(self,cmd,depth=0):
2070 """Expand python variables in a string.
2076 """Expand python variables in a string.
2071
2077
2072 The depth argument indicates how many frames above the caller should
2078 The depth argument indicates how many frames above the caller should
2073 be walked to look for the local namespace where to expand variables.
2079 be walked to look for the local namespace where to expand variables.
2074
2080
2075 The global namespace for expansion is always the user's interactive
2081 The global namespace for expansion is always the user's interactive
2076 namespace.
2082 namespace.
2077 """
2083 """
2078
2084
2079 return str(ItplNS(cmd,
2085 return str(ItplNS(cmd,
2080 self.user_ns, # globals
2086 self.user_ns, # globals
2081 # Skip our own frame in searching for locals:
2087 # Skip our own frame in searching for locals:
2082 sys._getframe(depth+1).f_locals # locals
2088 sys._getframe(depth+1).f_locals # locals
2083 ))
2089 ))
2084
2090
2085 def mktempfile(self,data=None):
2091 def mktempfile(self,data=None):
2086 """Make a new tempfile and return its filename.
2092 """Make a new tempfile and return its filename.
2087
2093
2088 This makes a call to tempfile.mktemp, but it registers the created
2094 This makes a call to tempfile.mktemp, but it registers the created
2089 filename internally so ipython cleans it up at exit time.
2095 filename internally so ipython cleans it up at exit time.
2090
2096
2091 Optional inputs:
2097 Optional inputs:
2092
2098
2093 - data(None): if data is given, it gets written out to the temp file
2099 - data(None): if data is given, it gets written out to the temp file
2094 immediately, and the file is closed again."""
2100 immediately, and the file is closed again."""
2095
2101
2096 filename = tempfile.mktemp('.py','ipython_edit_')
2102 filename = tempfile.mktemp('.py','ipython_edit_')
2097 self.tempfiles.append(filename)
2103 self.tempfiles.append(filename)
2098
2104
2099 if data:
2105 if data:
2100 tmp_file = open(filename,'w')
2106 tmp_file = open(filename,'w')
2101 tmp_file.write(data)
2107 tmp_file.write(data)
2102 tmp_file.close()
2108 tmp_file.close()
2103 return filename
2109 return filename
2104
2110
2105 # TODO: This should be removed when Term is refactored.
2111 # TODO: This should be removed when Term is refactored.
2106 def write(self,data):
2112 def write(self,data):
2107 """Write a string to the default output"""
2113 """Write a string to the default output"""
2108 io.Term.cout.write(data)
2114 io.Term.cout.write(data)
2109
2115
2110 # TODO: This should be removed when Term is refactored.
2116 # TODO: This should be removed when Term is refactored.
2111 def write_err(self,data):
2117 def write_err(self,data):
2112 """Write a string to the default error output"""
2118 """Write a string to the default error output"""
2113 io.Term.cerr.write(data)
2119 io.Term.cerr.write(data)
2114
2120
2115 def ask_yes_no(self,prompt,default=True):
2121 def ask_yes_no(self,prompt,default=True):
2116 if self.quiet:
2122 if self.quiet:
2117 return True
2123 return True
2118 return ask_yes_no(prompt,default)
2124 return ask_yes_no(prompt,default)
2119
2125
2120 def show_usage(self):
2126 def show_usage(self):
2121 """Show a usage message"""
2127 """Show a usage message"""
2122 page.page(IPython.core.usage.interactive_usage)
2128 page.page(IPython.core.usage.interactive_usage)
2123
2129
2124 #-------------------------------------------------------------------------
2130 #-------------------------------------------------------------------------
2125 # Things related to IPython exiting
2131 # Things related to IPython exiting
2126 #-------------------------------------------------------------------------
2132 #-------------------------------------------------------------------------
2127
2133
2128 def atexit_operations(self):
2134 def atexit_operations(self):
2129 """This will be executed at the time of exit.
2135 """This will be executed at the time of exit.
2130
2136
2131 Saving of persistent data should be performed here.
2137 Saving of persistent data should be performed here.
2132 """
2138 """
2133 self.savehist()
2139 self.savehist()
2134
2140
2135 # Cleanup all tempfiles left around
2141 # Cleanup all tempfiles left around
2136 for tfile in self.tempfiles:
2142 for tfile in self.tempfiles:
2137 try:
2143 try:
2138 os.unlink(tfile)
2144 os.unlink(tfile)
2139 except OSError:
2145 except OSError:
2140 pass
2146 pass
2141
2147
2142 # Clear all user namespaces to release all references cleanly.
2148 # Clear all user namespaces to release all references cleanly.
2143 self.reset()
2149 self.reset()
2144
2150
2145 # Run user hooks
2151 # Run user hooks
2146 self.hooks.shutdown_hook()
2152 self.hooks.shutdown_hook()
2147
2153
2148 def cleanup(self):
2154 def cleanup(self):
2149 self.restore_sys_module_state()
2155 self.restore_sys_module_state()
2150
2156
2151
2157
2152 class InteractiveShellABC(object):
2158 class InteractiveShellABC(object):
2153 """An abstract base class for InteractiveShell."""
2159 """An abstract base class for InteractiveShell."""
2154 __metaclass__ = abc.ABCMeta
2160 __metaclass__ = abc.ABCMeta
2155
2161
2156 InteractiveShellABC.register(InteractiveShell)
2162 InteractiveShellABC.register(InteractiveShell)
@@ -1,3648 +1,3631 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 import types
28 import types
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # print_function was added to __future__ in Python2.6, remove this when we drop
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core import page
55 from IPython.core import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.lib.inputhook import enable_gui
58 from IPython.lib.inputhook import enable_gui
59 from IPython.external.Itpl import itpl, printpl
59 from IPython.external.Itpl import itpl, printpl
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import file_read, nlprint
61 from IPython.utils.io import file_read, nlprint
62 import IPython.utils.io
62 import IPython.utils.io
63 from IPython.utils.path import get_py_filename
63 from IPython.utils.path import get_py_filename
64 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.process import arg_split, abbrev_cwd
65 from IPython.utils.terminal import set_term_title
65 from IPython.utils.terminal import set_term_title
66 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.text import LSString, SList, StringTypes
67 from IPython.utils.timing import clock, clock2
67 from IPython.utils.timing import clock, clock2
68 from IPython.utils.warn import warn, error
68 from IPython.utils.warn import warn, error
69 from IPython.utils.ipstruct import Struct
69 from IPython.utils.ipstruct import Struct
70 import IPython.utils.generics
70 import IPython.utils.generics
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Utility functions
73 # Utility functions
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 def on_off(tag):
76 def on_off(tag):
77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
78 return ['OFF','ON'][tag]
78 return ['OFF','ON'][tag]
79
79
80 class Bunch: pass
80 class Bunch: pass
81
81
82 def compress_dhist(dh):
82 def compress_dhist(dh):
83 head, tail = dh[:-10], dh[-10:]
83 head, tail = dh[:-10], dh[-10:]
84
84
85 newhead = []
85 newhead = []
86 done = set()
86 done = set()
87 for h in head:
87 for h in head:
88 if h in done:
88 if h in done:
89 continue
89 continue
90 newhead.append(h)
90 newhead.append(h)
91 done.add(h)
91 done.add(h)
92
92
93 return newhead + tail
93 return newhead + tail
94
94
95
95
96 #***************************************************************************
96 #***************************************************************************
97 # Main class implementing Magic functionality
97 # Main class implementing Magic functionality
98
98
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # on construction of the main InteractiveShell object. Something odd is going
100 # on construction of the main InteractiveShell object. Something odd is going
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # eventually this needs to be clarified.
102 # eventually this needs to be clarified.
103 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # make Magic a configurable that InteractiveShell does not subclass.
105 # make Magic a configurable that InteractiveShell does not subclass.
106
106
107 class Magic:
107 class Magic:
108 """Magic functions for InteractiveShell.
108 """Magic functions for InteractiveShell.
109
109
110 Shell functions which can be reached as %function_name. All magic
110 Shell functions which can be reached as %function_name. All magic
111 functions should accept a string, which they can parse for their own
111 functions should accept a string, which they can parse for their own
112 needs. This can make some functions easier to type, eg `%cd ../`
112 needs. This can make some functions easier to type, eg `%cd ../`
113 vs. `%cd("../")`
113 vs. `%cd("../")`
114
114
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 at the command line, but it is is needed in the definition. """
116 at the command line, but it is is needed in the definition. """
117
117
118 # class globals
118 # class globals
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 'Automagic is ON, % prefix NOT needed for magic functions.']
120 'Automagic is ON, % prefix NOT needed for magic functions.']
121
121
122 #......................................................................
122 #......................................................................
123 # some utility functions
123 # some utility functions
124
124
125 def __init__(self,shell):
125 def __init__(self,shell):
126
126
127 self.options_table = {}
127 self.options_table = {}
128 if profile is None:
128 if profile is None:
129 self.magic_prun = self.profile_missing_notice
129 self.magic_prun = self.profile_missing_notice
130 self.shell = shell
130 self.shell = shell
131
131
132 # namespace for holding state we may need
132 # namespace for holding state we may need
133 self._magic_state = Bunch()
133 self._magic_state = Bunch()
134
134
135 def profile_missing_notice(self, *args, **kwargs):
135 def profile_missing_notice(self, *args, **kwargs):
136 error("""\
136 error("""\
137 The profile module could not be found. It has been removed from the standard
137 The profile module could not be found. It has been removed from the standard
138 python packages because of its non-free license. To use profiling, install the
138 python packages because of its non-free license. To use profiling, install the
139 python-profiler package from non-free.""")
139 python-profiler package from non-free.""")
140
140
141 def default_option(self,fn,optstr):
141 def default_option(self,fn,optstr):
142 """Make an entry in the options_table for fn, with value optstr"""
142 """Make an entry in the options_table for fn, with value optstr"""
143
143
144 if fn not in self.lsmagic():
144 if fn not in self.lsmagic():
145 error("%s is not a magic function" % fn)
145 error("%s is not a magic function" % fn)
146 self.options_table[fn] = optstr
146 self.options_table[fn] = optstr
147
147
148 def lsmagic(self):
148 def lsmagic(self):
149 """Return a list of currently available magic functions.
149 """Return a list of currently available magic functions.
150
150
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 ['magic_ls','magic_cd',...]"""
152 ['magic_ls','magic_cd',...]"""
153
153
154 # FIXME. This needs a cleanup, in the way the magics list is built.
154 # FIXME. This needs a cleanup, in the way the magics list is built.
155
155
156 # magics in class definition
156 # magics in class definition
157 class_magic = lambda fn: fn.startswith('magic_') and \
157 class_magic = lambda fn: fn.startswith('magic_') and \
158 callable(Magic.__dict__[fn])
158 callable(Magic.__dict__[fn])
159 # in instance namespace (run-time user additions)
159 # in instance namespace (run-time user additions)
160 inst_magic = lambda fn: fn.startswith('magic_') and \
160 inst_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__dict__[fn])
161 callable(self.__dict__[fn])
162 # and bound magics by user (so they can access self):
162 # and bound magics by user (so they can access self):
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 callable(self.__class__.__dict__[fn])
164 callable(self.__class__.__dict__[fn])
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 out = []
168 out = []
169 for fn in set(magics):
169 for fn in set(magics):
170 out.append(fn.replace('magic_','',1))
170 out.append(fn.replace('magic_','',1))
171 out.sort()
171 out.sort()
172 return out
172 return out
173
173
174 def extract_input_slices(self,slices,raw=False):
174 def extract_input_slices(self,slices,raw=False):
175 """Return as a string a set of input history slices.
175 """Return as a string a set of input history slices.
176
176
177 Inputs:
177 Inputs:
178
178
179 - slices: the set of slices is given as a list of strings (like
179 - slices: the set of slices is given as a list of strings (like
180 ['1','4:8','9'], since this function is for use by magic functions
180 ['1','4:8','9'], since this function is for use by magic functions
181 which get their arguments as strings.
181 which get their arguments as strings.
182
182
183 Optional inputs:
183 Optional inputs:
184
184
185 - raw(False): by default, the processed input is used. If this is
185 - raw(False): by default, the processed input is used. If this is
186 true, the raw input history is used instead.
186 true, the raw input history is used instead.
187
187
188 Note that slices can be called with two notations:
188 Note that slices can be called with two notations:
189
189
190 N:M -> standard python form, means including items N...(M-1).
190 N:M -> standard python form, means including items N...(M-1).
191
191
192 N-M -> include items N..M (closed endpoint)."""
192 N-M -> include items N..M (closed endpoint)."""
193
193
194 if raw:
194 if raw:
195 hist = self.shell.input_hist_raw
195 hist = self.shell.input_hist_raw
196 else:
196 else:
197 hist = self.shell.input_hist
197 hist = self.shell.input_hist
198
198
199 cmds = []
199 cmds = []
200 for chunk in slices:
200 for chunk in slices:
201 if ':' in chunk:
201 if ':' in chunk:
202 ini,fin = map(int,chunk.split(':'))
202 ini,fin = map(int,chunk.split(':'))
203 elif '-' in chunk:
203 elif '-' in chunk:
204 ini,fin = map(int,chunk.split('-'))
204 ini,fin = map(int,chunk.split('-'))
205 fin += 1
205 fin += 1
206 else:
206 else:
207 ini = int(chunk)
207 ini = int(chunk)
208 fin = ini+1
208 fin = ini+1
209 cmds.append(hist[ini:fin])
209 cmds.append(hist[ini:fin])
210 return cmds
210 return cmds
211
211
212 def _ofind(self, oname, namespaces=None):
212 def _ofind(self, oname, namespaces=None):
213 """Find an object in the available namespaces.
213 """Find an object in the available namespaces.
214
214
215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
216
216
217 Has special code to detect magic functions.
217 Has special code to detect magic functions.
218 """
218 """
219 oname = oname.strip()
219 oname = oname.strip()
220 alias_ns = None
220 alias_ns = None
221 if namespaces is None:
221 if namespaces is None:
222 # Namespaces to search in:
222 # Namespaces to search in:
223 # Put them in a list. The order is important so that we
223 # Put them in a list. The order is important so that we
224 # find things in the same order that Python finds them.
224 # find things in the same order that Python finds them.
225 namespaces = [ ('Interactive', self.shell.user_ns),
225 namespaces = [ ('Interactive', self.shell.user_ns),
226 ('IPython internal', self.shell.internal_ns),
226 ('IPython internal', self.shell.internal_ns),
227 ('Python builtin', __builtin__.__dict__),
227 ('Python builtin', __builtin__.__dict__),
228 ('Alias', self.shell.alias_manager.alias_table),
228 ('Alias', self.shell.alias_manager.alias_table),
229 ]
229 ]
230 alias_ns = self.shell.alias_manager.alias_table
230 alias_ns = self.shell.alias_manager.alias_table
231
231
232 # initialize results to 'null'
232 # initialize results to 'null'
233 found = False; obj = None; ospace = None; ds = None;
233 found = False; obj = None; ospace = None; ds = None;
234 ismagic = False; isalias = False; parent = None
234 ismagic = False; isalias = False; parent = None
235
235
236 # We need to special-case 'print', which as of python2.6 registers as a
236 # We need to special-case 'print', which as of python2.6 registers as a
237 # function but should only be treated as one if print_function was
237 # function but should only be treated as one if print_function was
238 # loaded with a future import. In this case, just bail.
238 # loaded with a future import. In this case, just bail.
239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
240 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 __future__.CO_FUTURE_PRINT_FUNCTION)):
241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
243
243
244 # Look for the given name by splitting it in parts. If the head is
244 # Look for the given name by splitting it in parts. If the head is
245 # found, then we look for all the remaining parts as members, and only
245 # found, then we look for all the remaining parts as members, and only
246 # declare success if we can find them all.
246 # declare success if we can find them all.
247 oname_parts = oname.split('.')
247 oname_parts = oname.split('.')
248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
249 for nsname,ns in namespaces:
249 for nsname,ns in namespaces:
250 try:
250 try:
251 obj = ns[oname_head]
251 obj = ns[oname_head]
252 except KeyError:
252 except KeyError:
253 continue
253 continue
254 else:
254 else:
255 #print 'oname_rest:', oname_rest # dbg
255 #print 'oname_rest:', oname_rest # dbg
256 for part in oname_rest:
256 for part in oname_rest:
257 try:
257 try:
258 parent = obj
258 parent = obj
259 obj = getattr(obj,part)
259 obj = getattr(obj,part)
260 except:
260 except:
261 # Blanket except b/c some badly implemented objects
261 # Blanket except b/c some badly implemented objects
262 # allow __getattr__ to raise exceptions other than
262 # allow __getattr__ to raise exceptions other than
263 # AttributeError, which then crashes IPython.
263 # AttributeError, which then crashes IPython.
264 break
264 break
265 else:
265 else:
266 # If we finish the for loop (no break), we got all members
266 # If we finish the for loop (no break), we got all members
267 found = True
267 found = True
268 ospace = nsname
268 ospace = nsname
269 if ns == alias_ns:
269 if ns == alias_ns:
270 isalias = True
270 isalias = True
271 break # namespace loop
271 break # namespace loop
272
272
273 # Try to see if it's magic
273 # Try to see if it's magic
274 if not found:
274 if not found:
275 if oname.startswith(ESC_MAGIC):
275 if oname.startswith(ESC_MAGIC):
276 oname = oname[1:]
276 oname = oname[1:]
277 obj = getattr(self,'magic_'+oname,None)
277 obj = getattr(self,'magic_'+oname,None)
278 if obj is not None:
278 if obj is not None:
279 found = True
279 found = True
280 ospace = 'IPython internal'
280 ospace = 'IPython internal'
281 ismagic = True
281 ismagic = True
282
282
283 # Last try: special-case some literals like '', [], {}, etc:
283 # Last try: special-case some literals like '', [], {}, etc:
284 if not found and oname_head in ["''",'""','[]','{}','()']:
284 if not found and oname_head in ["''",'""','[]','{}','()']:
285 obj = eval(oname_head)
285 obj = eval(oname_head)
286 found = True
286 found = True
287 ospace = 'Interactive'
287 ospace = 'Interactive'
288
288
289 return {'found':found, 'obj':obj, 'namespace':ospace,
289 return {'found':found, 'obj':obj, 'namespace':ospace,
290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
291
291
292 def arg_err(self,func):
292 def arg_err(self,func):
293 """Print docstring if incorrect arguments were passed"""
293 """Print docstring if incorrect arguments were passed"""
294 print 'Error in arguments:'
294 print 'Error in arguments:'
295 print oinspect.getdoc(func)
295 print oinspect.getdoc(func)
296
296
297 def format_latex(self,strng):
297 def format_latex(self,strng):
298 """Format a string for latex inclusion."""
298 """Format a string for latex inclusion."""
299
299
300 # Characters that need to be escaped for latex:
300 # Characters that need to be escaped for latex:
301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
302 # Magic command names as headers:
302 # Magic command names as headers:
303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
304 re.MULTILINE)
304 re.MULTILINE)
305 # Magic commands
305 # Magic commands
306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
307 re.MULTILINE)
307 re.MULTILINE)
308 # Paragraph continue
308 # Paragraph continue
309 par_re = re.compile(r'\\$',re.MULTILINE)
309 par_re = re.compile(r'\\$',re.MULTILINE)
310
310
311 # The "\n" symbol
311 # The "\n" symbol
312 newline_re = re.compile(r'\\n')
312 newline_re = re.compile(r'\\n')
313
313
314 # Now build the string for output:
314 # Now build the string for output:
315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
317 strng)
317 strng)
318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
319 strng = par_re.sub(r'\\\\',strng)
319 strng = par_re.sub(r'\\\\',strng)
320 strng = escape_re.sub(r'\\\1',strng)
320 strng = escape_re.sub(r'\\\1',strng)
321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
322 return strng
322 return strng
323
323
324 def format_screen(self,strng):
324 def format_screen(self,strng):
325 """Format a string for screen printing.
325 """Format a string for screen printing.
326
326
327 This removes some latex-type format codes."""
327 This removes some latex-type format codes."""
328 # Paragraph continue
328 # Paragraph continue
329 par_re = re.compile(r'\\$',re.MULTILINE)
329 par_re = re.compile(r'\\$',re.MULTILINE)
330 strng = par_re.sub('',strng)
330 strng = par_re.sub('',strng)
331 return strng
331 return strng
332
332
333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
334 """Parse options passed to an argument string.
334 """Parse options passed to an argument string.
335
335
336 The interface is similar to that of getopt(), but it returns back a
336 The interface is similar to that of getopt(), but it returns back a
337 Struct with the options as keys and the stripped argument string still
337 Struct with the options as keys and the stripped argument string still
338 as a string.
338 as a string.
339
339
340 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 arg_str is quoted as a true sys.argv vector by using shlex.split.
341 This allows us to easily expand variables, glob files, quote
341 This allows us to easily expand variables, glob files, quote
342 arguments, etc.
342 arguments, etc.
343
343
344 Options:
344 Options:
345 -mode: default 'string'. If given as 'list', the argument string is
345 -mode: default 'string'. If given as 'list', the argument string is
346 returned as a list (split on whitespace) instead of a string.
346 returned as a list (split on whitespace) instead of a string.
347
347
348 -list_all: put all option values in lists. Normally only options
348 -list_all: put all option values in lists. Normally only options
349 appearing more than once are put in a list.
349 appearing more than once are put in a list.
350
350
351 -posix (True): whether to split the input line in POSIX mode or not,
351 -posix (True): whether to split the input line in POSIX mode or not,
352 as per the conventions outlined in the shlex module from the
352 as per the conventions outlined in the shlex module from the
353 standard library."""
353 standard library."""
354
354
355 # inject default options at the beginning of the input line
355 # inject default options at the beginning of the input line
356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
358
358
359 mode = kw.get('mode','string')
359 mode = kw.get('mode','string')
360 if mode not in ['string','list']:
360 if mode not in ['string','list']:
361 raise ValueError,'incorrect mode given: %s' % mode
361 raise ValueError,'incorrect mode given: %s' % mode
362 # Get options
362 # Get options
363 list_all = kw.get('list_all',0)
363 list_all = kw.get('list_all',0)
364 posix = kw.get('posix', os.name == 'posix')
364 posix = kw.get('posix', os.name == 'posix')
365
365
366 # Check if we have more than one argument to warrant extra processing:
366 # Check if we have more than one argument to warrant extra processing:
367 odict = {} # Dictionary with options
367 odict = {} # Dictionary with options
368 args = arg_str.split()
368 args = arg_str.split()
369 if len(args) >= 1:
369 if len(args) >= 1:
370 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # If the list of inputs only has 0 or 1 thing in it, there's no
371 # need to look for options
371 # need to look for options
372 argv = arg_split(arg_str,posix)
372 argv = arg_split(arg_str,posix)
373 # Do regular option processing
373 # Do regular option processing
374 try:
374 try:
375 opts,args = getopt(argv,opt_str,*long_opts)
375 opts,args = getopt(argv,opt_str,*long_opts)
376 except GetoptError,e:
376 except GetoptError,e:
377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
378 " ".join(long_opts)))
378 " ".join(long_opts)))
379 for o,a in opts:
379 for o,a in opts:
380 if o.startswith('--'):
380 if o.startswith('--'):
381 o = o[2:]
381 o = o[2:]
382 else:
382 else:
383 o = o[1:]
383 o = o[1:]
384 try:
384 try:
385 odict[o].append(a)
385 odict[o].append(a)
386 except AttributeError:
386 except AttributeError:
387 odict[o] = [odict[o],a]
387 odict[o] = [odict[o],a]
388 except KeyError:
388 except KeyError:
389 if list_all:
389 if list_all:
390 odict[o] = [a]
390 odict[o] = [a]
391 else:
391 else:
392 odict[o] = a
392 odict[o] = a
393
393
394 # Prepare opts,args for return
394 # Prepare opts,args for return
395 opts = Struct(odict)
395 opts = Struct(odict)
396 if mode == 'string':
396 if mode == 'string':
397 args = ' '.join(args)
397 args = ' '.join(args)
398
398
399 return opts,args
399 return opts,args
400
400
401 #......................................................................
401 #......................................................................
402 # And now the actual magic functions
402 # And now the actual magic functions
403
403
404 # Functions for IPython shell work (vars,funcs, config, etc)
404 # Functions for IPython shell work (vars,funcs, config, etc)
405 def magic_lsmagic(self, parameter_s = ''):
405 def magic_lsmagic(self, parameter_s = ''):
406 """List currently available magic functions."""
406 """List currently available magic functions."""
407 mesc = ESC_MAGIC
407 mesc = ESC_MAGIC
408 print 'Available magic functions:\n'+mesc+\
408 print 'Available magic functions:\n'+mesc+\
409 (' '+mesc).join(self.lsmagic())
409 (' '+mesc).join(self.lsmagic())
410 print '\n' + Magic.auto_status[self.shell.automagic]
410 print '\n' + Magic.auto_status[self.shell.automagic]
411 return None
411 return None
412
412
413 def magic_magic(self, parameter_s = ''):
413 def magic_magic(self, parameter_s = ''):
414 """Print information about the magic function system.
414 """Print information about the magic function system.
415
415
416 Supported formats: -latex, -brief, -rest
416 Supported formats: -latex, -brief, -rest
417 """
417 """
418
418
419 mode = ''
419 mode = ''
420 try:
420 try:
421 if parameter_s.split()[0] == '-latex':
421 if parameter_s.split()[0] == '-latex':
422 mode = 'latex'
422 mode = 'latex'
423 if parameter_s.split()[0] == '-brief':
423 if parameter_s.split()[0] == '-brief':
424 mode = 'brief'
424 mode = 'brief'
425 if parameter_s.split()[0] == '-rest':
425 if parameter_s.split()[0] == '-rest':
426 mode = 'rest'
426 mode = 'rest'
427 rest_docs = []
427 rest_docs = []
428 except:
428 except:
429 pass
429 pass
430
430
431 magic_docs = []
431 magic_docs = []
432 for fname in self.lsmagic():
432 for fname in self.lsmagic():
433 mname = 'magic_' + fname
433 mname = 'magic_' + fname
434 for space in (Magic,self,self.__class__):
434 for space in (Magic,self,self.__class__):
435 try:
435 try:
436 fn = space.__dict__[mname]
436 fn = space.__dict__[mname]
437 except KeyError:
437 except KeyError:
438 pass
438 pass
439 else:
439 else:
440 break
440 break
441 if mode == 'brief':
441 if mode == 'brief':
442 # only first line
442 # only first line
443 if fn.__doc__:
443 if fn.__doc__:
444 fndoc = fn.__doc__.split('\n',1)[0]
444 fndoc = fn.__doc__.split('\n',1)[0]
445 else:
445 else:
446 fndoc = 'No documentation'
446 fndoc = 'No documentation'
447 else:
447 else:
448 if fn.__doc__:
448 if fn.__doc__:
449 fndoc = fn.__doc__.rstrip()
449 fndoc = fn.__doc__.rstrip()
450 else:
450 else:
451 fndoc = 'No documentation'
451 fndoc = 'No documentation'
452
452
453
453
454 if mode == 'rest':
454 if mode == 'rest':
455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
456 fname,fndoc))
456 fname,fndoc))
457
457
458 else:
458 else:
459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
460 fname,fndoc))
460 fname,fndoc))
461
461
462 magic_docs = ''.join(magic_docs)
462 magic_docs = ''.join(magic_docs)
463
463
464 if mode == 'rest':
464 if mode == 'rest':
465 return "".join(rest_docs)
465 return "".join(rest_docs)
466
466
467 if mode == 'latex':
467 if mode == 'latex':
468 print self.format_latex(magic_docs)
468 print self.format_latex(magic_docs)
469 return
469 return
470 else:
470 else:
471 magic_docs = self.format_screen(magic_docs)
471 magic_docs = self.format_screen(magic_docs)
472 if mode == 'brief':
472 if mode == 'brief':
473 return magic_docs
473 return magic_docs
474
474
475 outmsg = """
475 outmsg = """
476 IPython's 'magic' functions
476 IPython's 'magic' functions
477 ===========================
477 ===========================
478
478
479 The magic function system provides a series of functions which allow you to
479 The magic function system provides a series of functions which allow you to
480 control the behavior of IPython itself, plus a lot of system-type
480 control the behavior of IPython itself, plus a lot of system-type
481 features. All these functions are prefixed with a % character, but parameters
481 features. All these functions are prefixed with a % character, but parameters
482 are given without parentheses or quotes.
482 are given without parentheses or quotes.
483
483
484 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 NOTE: If you have 'automagic' enabled (via the command line option or with the
485 %automagic function), you don't need to type in the % explicitly. By default,
485 %automagic function), you don't need to type in the % explicitly. By default,
486 IPython ships with automagic on, so you should only rarely need the % escape.
486 IPython ships with automagic on, so you should only rarely need the % escape.
487
487
488 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 Example: typing '%cd mydir' (without the quotes) changes you working directory
489 to 'mydir', if it exists.
489 to 'mydir', if it exists.
490
490
491 You can define your own magic functions to extend the system. See the supplied
491 You can define your own magic functions to extend the system. See the supplied
492 ipythonrc and example-magic.py files for details (in your ipython
492 ipythonrc and example-magic.py files for details (in your ipython
493 configuration directory, typically $HOME/.ipython/).
493 configuration directory, typically $HOME/.ipython/).
494
494
495 You can also define your own aliased names for magic functions. In your
495 You can also define your own aliased names for magic functions. In your
496 ipythonrc file, placing a line like:
496 ipythonrc file, placing a line like:
497
497
498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
499
499
500 will define %pf as a new name for %profile.
500 will define %pf as a new name for %profile.
501
501
502 You can also call magics in code using the magic() function, which IPython
502 You can also call magics in code using the magic() function, which IPython
503 automatically adds to the builtin namespace. Type 'magic?' for details.
503 automatically adds to the builtin namespace. Type 'magic?' for details.
504
504
505 For a list of the available magic functions, use %lsmagic. For a description
505 For a list of the available magic functions, use %lsmagic. For a description
506 of any of them, type %magic_name?, e.g. '%cd?'.
506 of any of them, type %magic_name?, e.g. '%cd?'.
507
507
508 Currently the magic system has the following functions:\n"""
508 Currently the magic system has the following functions:\n"""
509
509
510 mesc = ESC_MAGIC
510 mesc = ESC_MAGIC
511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
512 "\n\n%s%s\n\n%s" % (outmsg,
512 "\n\n%s%s\n\n%s" % (outmsg,
513 magic_docs,mesc,mesc,
513 magic_docs,mesc,mesc,
514 (' '+mesc).join(self.lsmagic()),
514 (' '+mesc).join(self.lsmagic()),
515 Magic.auto_status[self.shell.automagic] ) )
515 Magic.auto_status[self.shell.automagic] ) )
516 page.page(outmsg)
516 page.page(outmsg)
517
517
518 def magic_autoindent(self, parameter_s = ''):
518 def magic_autoindent(self, parameter_s = ''):
519 """Toggle autoindent on/off (if available)."""
519 """Toggle autoindent on/off (if available)."""
520
520
521 self.shell.set_autoindent()
521 self.shell.set_autoindent()
522 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
522 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
523
523
524 def magic_automagic(self, parameter_s = ''):
524 def magic_automagic(self, parameter_s = ''):
525 """Make magic functions callable without having to type the initial %.
525 """Make magic functions callable without having to type the initial %.
526
526
527 Without argumentsl toggles on/off (when off, you must call it as
527 Without argumentsl toggles on/off (when off, you must call it as
528 %automagic, of course). With arguments it sets the value, and you can
528 %automagic, of course). With arguments it sets the value, and you can
529 use any of (case insensitive):
529 use any of (case insensitive):
530
530
531 - on,1,True: to activate
531 - on,1,True: to activate
532
532
533 - off,0,False: to deactivate.
533 - off,0,False: to deactivate.
534
534
535 Note that magic functions have lowest priority, so if there's a
535 Note that magic functions have lowest priority, so if there's a
536 variable whose name collides with that of a magic fn, automagic won't
536 variable whose name collides with that of a magic fn, automagic won't
537 work for that function (you get the variable instead). However, if you
537 work for that function (you get the variable instead). However, if you
538 delete the variable (del var), the previously shadowed magic function
538 delete the variable (del var), the previously shadowed magic function
539 becomes visible to automagic again."""
539 becomes visible to automagic again."""
540
540
541 arg = parameter_s.lower()
541 arg = parameter_s.lower()
542 if parameter_s in ('on','1','true'):
542 if parameter_s in ('on','1','true'):
543 self.shell.automagic = True
543 self.shell.automagic = True
544 elif parameter_s in ('off','0','false'):
544 elif parameter_s in ('off','0','false'):
545 self.shell.automagic = False
545 self.shell.automagic = False
546 else:
546 else:
547 self.shell.automagic = not self.shell.automagic
547 self.shell.automagic = not self.shell.automagic
548 print '\n' + Magic.auto_status[self.shell.automagic]
548 print '\n' + Magic.auto_status[self.shell.automagic]
549
549
550 @testdec.skip_doctest
550 @testdec.skip_doctest
551 def magic_autocall(self, parameter_s = ''):
551 def magic_autocall(self, parameter_s = ''):
552 """Make functions callable without having to type parentheses.
552 """Make functions callable without having to type parentheses.
553
553
554 Usage:
554 Usage:
555
555
556 %autocall [mode]
556 %autocall [mode]
557
557
558 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
558 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
559 value is toggled on and off (remembering the previous state).
559 value is toggled on and off (remembering the previous state).
560
560
561 In more detail, these values mean:
561 In more detail, these values mean:
562
562
563 0 -> fully disabled
563 0 -> fully disabled
564
564
565 1 -> active, but do not apply if there are no arguments on the line.
565 1 -> active, but do not apply if there are no arguments on the line.
566
566
567 In this mode, you get:
567 In this mode, you get:
568
568
569 In [1]: callable
569 In [1]: callable
570 Out[1]: <built-in function callable>
570 Out[1]: <built-in function callable>
571
571
572 In [2]: callable 'hello'
572 In [2]: callable 'hello'
573 ------> callable('hello')
573 ------> callable('hello')
574 Out[2]: False
574 Out[2]: False
575
575
576 2 -> Active always. Even if no arguments are present, the callable
576 2 -> Active always. Even if no arguments are present, the callable
577 object is called:
577 object is called:
578
578
579 In [2]: float
579 In [2]: float
580 ------> float()
580 ------> float()
581 Out[2]: 0.0
581 Out[2]: 0.0
582
582
583 Note that even with autocall off, you can still use '/' at the start of
583 Note that even with autocall off, you can still use '/' at the start of
584 a line to treat the first argument on the command line as a function
584 a line to treat the first argument on the command line as a function
585 and add parentheses to it:
585 and add parentheses to it:
586
586
587 In [8]: /str 43
587 In [8]: /str 43
588 ------> str(43)
588 ------> str(43)
589 Out[8]: '43'
589 Out[8]: '43'
590
590
591 # all-random (note for auto-testing)
591 # all-random (note for auto-testing)
592 """
592 """
593
593
594 if parameter_s:
594 if parameter_s:
595 arg = int(parameter_s)
595 arg = int(parameter_s)
596 else:
596 else:
597 arg = 'toggle'
597 arg = 'toggle'
598
598
599 if not arg in (0,1,2,'toggle'):
599 if not arg in (0,1,2,'toggle'):
600 error('Valid modes: (0->Off, 1->Smart, 2->Full')
600 error('Valid modes: (0->Off, 1->Smart, 2->Full')
601 return
601 return
602
602
603 if arg in (0,1,2):
603 if arg in (0,1,2):
604 self.shell.autocall = arg
604 self.shell.autocall = arg
605 else: # toggle
605 else: # toggle
606 if self.shell.autocall:
606 if self.shell.autocall:
607 self._magic_state.autocall_save = self.shell.autocall
607 self._magic_state.autocall_save = self.shell.autocall
608 self.shell.autocall = 0
608 self.shell.autocall = 0
609 else:
609 else:
610 try:
610 try:
611 self.shell.autocall = self._magic_state.autocall_save
611 self.shell.autocall = self._magic_state.autocall_save
612 except AttributeError:
612 except AttributeError:
613 self.shell.autocall = self._magic_state.autocall_save = 1
613 self.shell.autocall = self._magic_state.autocall_save = 1
614
614
615 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
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 def magic_page(self, parameter_s=''):
618 def magic_page(self, parameter_s=''):
636 """Pretty print the object and display it through a pager.
619 """Pretty print the object and display it through a pager.
637
620
638 %page [options] OBJECT
621 %page [options] OBJECT
639
622
640 If no object is given, use _ (last output).
623 If no object is given, use _ (last output).
641
624
642 Options:
625 Options:
643
626
644 -r: page str(object), don't pretty-print it."""
627 -r: page str(object), don't pretty-print it."""
645
628
646 # After a function contributed by Olivier Aubert, slightly modified.
629 # After a function contributed by Olivier Aubert, slightly modified.
647
630
648 # Process options/args
631 # Process options/args
649 opts,args = self.parse_options(parameter_s,'r')
632 opts,args = self.parse_options(parameter_s,'r')
650 raw = 'r' in opts
633 raw = 'r' in opts
651
634
652 oname = args and args or '_'
635 oname = args and args or '_'
653 info = self._ofind(oname)
636 info = self._ofind(oname)
654 if info['found']:
637 if info['found']:
655 txt = (raw and str or pformat)( info['obj'] )
638 txt = (raw and str or pformat)( info['obj'] )
656 page.page(txt)
639 page.page(txt)
657 else:
640 else:
658 print 'Object `%s` not found' % oname
641 print 'Object `%s` not found' % oname
659
642
660 def magic_profile(self, parameter_s=''):
643 def magic_profile(self, parameter_s=''):
661 """Print your currently active IPython profile."""
644 """Print your currently active IPython profile."""
662 if self.shell.profile:
645 if self.shell.profile:
663 printpl('Current IPython profile: $self.shell.profile.')
646 printpl('Current IPython profile: $self.shell.profile.')
664 else:
647 else:
665 print 'No profile active.'
648 print 'No profile active.'
666
649
667 def magic_pinfo(self, parameter_s='', namespaces=None):
650 def magic_pinfo(self, parameter_s='', namespaces=None):
668 """Provide detailed information about an object.
651 """Provide detailed information about an object.
669
652
670 '%pinfo object' is just a synonym for object? or ?object."""
653 '%pinfo object' is just a synonym for object? or ?object."""
671
654
672 #print 'pinfo par: <%s>' % parameter_s # dbg
655 #print 'pinfo par: <%s>' % parameter_s # dbg
673
656
674
657
675 # detail_level: 0 -> obj? , 1 -> obj??
658 # detail_level: 0 -> obj? , 1 -> obj??
676 detail_level = 0
659 detail_level = 0
677 # We need to detect if we got called as 'pinfo pinfo foo', which can
660 # We need to detect if we got called as 'pinfo pinfo foo', which can
678 # happen if the user types 'pinfo foo?' at the cmd line.
661 # happen if the user types 'pinfo foo?' at the cmd line.
679 pinfo,qmark1,oname,qmark2 = \
662 pinfo,qmark1,oname,qmark2 = \
680 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
663 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
681 if pinfo or qmark1 or qmark2:
664 if pinfo or qmark1 or qmark2:
682 detail_level = 1
665 detail_level = 1
683 if "*" in oname:
666 if "*" in oname:
684 self.magic_psearch(oname)
667 self.magic_psearch(oname)
685 else:
668 else:
686 self._inspect('pinfo', oname, detail_level=detail_level,
669 self._inspect('pinfo', oname, detail_level=detail_level,
687 namespaces=namespaces)
670 namespaces=namespaces)
688
671
689 def magic_pdef(self, parameter_s='', namespaces=None):
672 def magic_pdef(self, parameter_s='', namespaces=None):
690 """Print the definition header for any callable object.
673 """Print the definition header for any callable object.
691
674
692 If the object is a class, print the constructor information."""
675 If the object is a class, print the constructor information."""
693 self._inspect('pdef',parameter_s, namespaces)
676 self._inspect('pdef',parameter_s, namespaces)
694
677
695 def magic_pdoc(self, parameter_s='', namespaces=None):
678 def magic_pdoc(self, parameter_s='', namespaces=None):
696 """Print the docstring for an object.
679 """Print the docstring for an object.
697
680
698 If the given object is a class, it will print both the class and the
681 If the given object is a class, it will print both the class and the
699 constructor docstrings."""
682 constructor docstrings."""
700 self._inspect('pdoc',parameter_s, namespaces)
683 self._inspect('pdoc',parameter_s, namespaces)
701
684
702 def magic_psource(self, parameter_s='', namespaces=None):
685 def magic_psource(self, parameter_s='', namespaces=None):
703 """Print (or run through pager) the source code for an object."""
686 """Print (or run through pager) the source code for an object."""
704 self._inspect('psource',parameter_s, namespaces)
687 self._inspect('psource',parameter_s, namespaces)
705
688
706 def magic_pfile(self, parameter_s=''):
689 def magic_pfile(self, parameter_s=''):
707 """Print (or run through pager) the file where an object is defined.
690 """Print (or run through pager) the file where an object is defined.
708
691
709 The file opens at the line where the object definition begins. IPython
692 The file opens at the line where the object definition begins. IPython
710 will honor the environment variable PAGER if set, and otherwise will
693 will honor the environment variable PAGER if set, and otherwise will
711 do its best to print the file in a convenient form.
694 do its best to print the file in a convenient form.
712
695
713 If the given argument is not an object currently defined, IPython will
696 If the given argument is not an object currently defined, IPython will
714 try to interpret it as a filename (automatically adding a .py extension
697 try to interpret it as a filename (automatically adding a .py extension
715 if needed). You can thus use %pfile as a syntax highlighting code
698 if needed). You can thus use %pfile as a syntax highlighting code
716 viewer."""
699 viewer."""
717
700
718 # first interpret argument as an object name
701 # first interpret argument as an object name
719 out = self._inspect('pfile',parameter_s)
702 out = self._inspect('pfile',parameter_s)
720 # if not, try the input as a filename
703 # if not, try the input as a filename
721 if out == 'not found':
704 if out == 'not found':
722 try:
705 try:
723 filename = get_py_filename(parameter_s)
706 filename = get_py_filename(parameter_s)
724 except IOError,msg:
707 except IOError,msg:
725 print msg
708 print msg
726 return
709 return
727 page.page(self.shell.inspector.format(file(filename).read()))
710 page.page(self.shell.inspector.format(file(filename).read()))
728
711
729 def _inspect(self,meth,oname,namespaces=None,**kw):
712 def _inspect(self,meth,oname,namespaces=None,**kw):
730 """Generic interface to the inspector system.
713 """Generic interface to the inspector system.
731
714
732 This function is meant to be called by pdef, pdoc & friends."""
715 This function is meant to be called by pdef, pdoc & friends."""
733
716
734 #oname = oname.strip()
717 #oname = oname.strip()
735 #print '1- oname: <%r>' % oname # dbg
718 #print '1- oname: <%r>' % oname # dbg
736 try:
719 try:
737 oname = oname.strip().encode('ascii')
720 oname = oname.strip().encode('ascii')
738 #print '2- oname: <%r>' % oname # dbg
721 #print '2- oname: <%r>' % oname # dbg
739 except UnicodeEncodeError:
722 except UnicodeEncodeError:
740 print 'Python identifiers can only contain ascii characters.'
723 print 'Python identifiers can only contain ascii characters.'
741 return 'not found'
724 return 'not found'
742
725
743 info = Struct(self._ofind(oname, namespaces))
726 info = Struct(self._ofind(oname, namespaces))
744
727
745 if info.found:
728 if info.found:
746 try:
729 try:
747 IPython.utils.generics.inspect_object(info.obj)
730 IPython.utils.generics.inspect_object(info.obj)
748 return
731 return
749 except TryNext:
732 except TryNext:
750 pass
733 pass
751 # Get the docstring of the class property if it exists.
734 # Get the docstring of the class property if it exists.
752 path = oname.split('.')
735 path = oname.split('.')
753 root = '.'.join(path[:-1])
736 root = '.'.join(path[:-1])
754 if info.parent is not None:
737 if info.parent is not None:
755 try:
738 try:
756 target = getattr(info.parent, '__class__')
739 target = getattr(info.parent, '__class__')
757 # The object belongs to a class instance.
740 # The object belongs to a class instance.
758 try:
741 try:
759 target = getattr(target, path[-1])
742 target = getattr(target, path[-1])
760 # The class defines the object.
743 # The class defines the object.
761 if isinstance(target, property):
744 if isinstance(target, property):
762 oname = root + '.__class__.' + path[-1]
745 oname = root + '.__class__.' + path[-1]
763 info = Struct(self._ofind(oname))
746 info = Struct(self._ofind(oname))
764 except AttributeError: pass
747 except AttributeError: pass
765 except AttributeError: pass
748 except AttributeError: pass
766
749
767 pmethod = getattr(self.shell.inspector,meth)
750 pmethod = getattr(self.shell.inspector,meth)
768 formatter = info.ismagic and self.format_screen or None
751 formatter = info.ismagic and self.format_screen or None
769 if meth == 'pdoc':
752 if meth == 'pdoc':
770 pmethod(info.obj,oname,formatter)
753 pmethod(info.obj,oname,formatter)
771 elif meth == 'pinfo':
754 elif meth == 'pinfo':
772 pmethod(info.obj,oname,formatter,info,**kw)
755 pmethod(info.obj,oname,formatter,info,**kw)
773 else:
756 else:
774 pmethod(info.obj,oname)
757 pmethod(info.obj,oname)
775 else:
758 else:
776 print 'Object `%s` not found.' % oname
759 print 'Object `%s` not found.' % oname
777 return 'not found' # so callers can take other action
760 return 'not found' # so callers can take other action
778
761
779 def magic_psearch(self, parameter_s=''):
762 def magic_psearch(self, parameter_s=''):
780 """Search for object in namespaces by wildcard.
763 """Search for object in namespaces by wildcard.
781
764
782 %psearch [options] PATTERN [OBJECT TYPE]
765 %psearch [options] PATTERN [OBJECT TYPE]
783
766
784 Note: ? can be used as a synonym for %psearch, at the beginning or at
767 Note: ? can be used as a synonym for %psearch, at the beginning or at
785 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
768 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
786 rest of the command line must be unchanged (options come first), so
769 rest of the command line must be unchanged (options come first), so
787 for example the following forms are equivalent
770 for example the following forms are equivalent
788
771
789 %psearch -i a* function
772 %psearch -i a* function
790 -i a* function?
773 -i a* function?
791 ?-i a* function
774 ?-i a* function
792
775
793 Arguments:
776 Arguments:
794
777
795 PATTERN
778 PATTERN
796
779
797 where PATTERN is a string containing * as a wildcard similar to its
780 where PATTERN is a string containing * as a wildcard similar to its
798 use in a shell. The pattern is matched in all namespaces on the
781 use in a shell. The pattern is matched in all namespaces on the
799 search path. By default objects starting with a single _ are not
782 search path. By default objects starting with a single _ are not
800 matched, many IPython generated objects have a single
783 matched, many IPython generated objects have a single
801 underscore. The default is case insensitive matching. Matching is
784 underscore. The default is case insensitive matching. Matching is
802 also done on the attributes of objects and not only on the objects
785 also done on the attributes of objects and not only on the objects
803 in a module.
786 in a module.
804
787
805 [OBJECT TYPE]
788 [OBJECT TYPE]
806
789
807 Is the name of a python type from the types module. The name is
790 Is the name of a python type from the types module. The name is
808 given in lowercase without the ending type, ex. StringType is
791 given in lowercase without the ending type, ex. StringType is
809 written string. By adding a type here only objects matching the
792 written string. By adding a type here only objects matching the
810 given type are matched. Using all here makes the pattern match all
793 given type are matched. Using all here makes the pattern match all
811 types (this is the default).
794 types (this is the default).
812
795
813 Options:
796 Options:
814
797
815 -a: makes the pattern match even objects whose names start with a
798 -a: makes the pattern match even objects whose names start with a
816 single underscore. These names are normally ommitted from the
799 single underscore. These names are normally ommitted from the
817 search.
800 search.
818
801
819 -i/-c: make the pattern case insensitive/sensitive. If neither of
802 -i/-c: make the pattern case insensitive/sensitive. If neither of
820 these options is given, the default is read from your ipythonrc
803 these options is given, the default is read from your ipythonrc
821 file. The option name which sets this value is
804 file. The option name which sets this value is
822 'wildcards_case_sensitive'. If this option is not specified in your
805 'wildcards_case_sensitive'. If this option is not specified in your
823 ipythonrc file, IPython's internal default is to do a case sensitive
806 ipythonrc file, IPython's internal default is to do a case sensitive
824 search.
807 search.
825
808
826 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
809 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
827 specifiy can be searched in any of the following namespaces:
810 specifiy can be searched in any of the following namespaces:
828 'builtin', 'user', 'user_global','internal', 'alias', where
811 'builtin', 'user', 'user_global','internal', 'alias', where
829 'builtin' and 'user' are the search defaults. Note that you should
812 'builtin' and 'user' are the search defaults. Note that you should
830 not use quotes when specifying namespaces.
813 not use quotes when specifying namespaces.
831
814
832 'Builtin' contains the python module builtin, 'user' contains all
815 'Builtin' contains the python module builtin, 'user' contains all
833 user data, 'alias' only contain the shell aliases and no python
816 user data, 'alias' only contain the shell aliases and no python
834 objects, 'internal' contains objects used by IPython. The
817 objects, 'internal' contains objects used by IPython. The
835 'user_global' namespace is only used by embedded IPython instances,
818 'user_global' namespace is only used by embedded IPython instances,
836 and it contains module-level globals. You can add namespaces to the
819 and it contains module-level globals. You can add namespaces to the
837 search with -s or exclude them with -e (these options can be given
820 search with -s or exclude them with -e (these options can be given
838 more than once).
821 more than once).
839
822
840 Examples:
823 Examples:
841
824
842 %psearch a* -> objects beginning with an a
825 %psearch a* -> objects beginning with an a
843 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
826 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
844 %psearch a* function -> all functions beginning with an a
827 %psearch a* function -> all functions beginning with an a
845 %psearch re.e* -> objects beginning with an e in module re
828 %psearch re.e* -> objects beginning with an e in module re
846 %psearch r*.e* -> objects that start with e in modules starting in r
829 %psearch r*.e* -> objects that start with e in modules starting in r
847 %psearch r*.* string -> all strings in modules beginning with r
830 %psearch r*.* string -> all strings in modules beginning with r
848
831
849 Case sensitve search:
832 Case sensitve search:
850
833
851 %psearch -c a* list all object beginning with lower case a
834 %psearch -c a* list all object beginning with lower case a
852
835
853 Show objects beginning with a single _:
836 Show objects beginning with a single _:
854
837
855 %psearch -a _* list objects beginning with a single underscore"""
838 %psearch -a _* list objects beginning with a single underscore"""
856 try:
839 try:
857 parameter_s = parameter_s.encode('ascii')
840 parameter_s = parameter_s.encode('ascii')
858 except UnicodeEncodeError:
841 except UnicodeEncodeError:
859 print 'Python identifiers can only contain ascii characters.'
842 print 'Python identifiers can only contain ascii characters.'
860 return
843 return
861
844
862 # default namespaces to be searched
845 # default namespaces to be searched
863 def_search = ['user','builtin']
846 def_search = ['user','builtin']
864
847
865 # Process options/args
848 # Process options/args
866 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
849 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
867 opt = opts.get
850 opt = opts.get
868 shell = self.shell
851 shell = self.shell
869 psearch = shell.inspector.psearch
852 psearch = shell.inspector.psearch
870
853
871 # select case options
854 # select case options
872 if opts.has_key('i'):
855 if opts.has_key('i'):
873 ignore_case = True
856 ignore_case = True
874 elif opts.has_key('c'):
857 elif opts.has_key('c'):
875 ignore_case = False
858 ignore_case = False
876 else:
859 else:
877 ignore_case = not shell.wildcards_case_sensitive
860 ignore_case = not shell.wildcards_case_sensitive
878
861
879 # Build list of namespaces to search from user options
862 # Build list of namespaces to search from user options
880 def_search.extend(opt('s',[]))
863 def_search.extend(opt('s',[]))
881 ns_exclude = ns_exclude=opt('e',[])
864 ns_exclude = ns_exclude=opt('e',[])
882 ns_search = [nm for nm in def_search if nm not in ns_exclude]
865 ns_search = [nm for nm in def_search if nm not in ns_exclude]
883
866
884 # Call the actual search
867 # Call the actual search
885 try:
868 try:
886 psearch(args,shell.ns_table,ns_search,
869 psearch(args,shell.ns_table,ns_search,
887 show_all=opt('a'),ignore_case=ignore_case)
870 show_all=opt('a'),ignore_case=ignore_case)
888 except:
871 except:
889 shell.showtraceback()
872 shell.showtraceback()
890
873
891 def magic_who_ls(self, parameter_s=''):
874 def magic_who_ls(self, parameter_s=''):
892 """Return a sorted list of all interactive variables.
875 """Return a sorted list of all interactive variables.
893
876
894 If arguments are given, only variables of types matching these
877 If arguments are given, only variables of types matching these
895 arguments are returned."""
878 arguments are returned."""
896
879
897 user_ns = self.shell.user_ns
880 user_ns = self.shell.user_ns
898 internal_ns = self.shell.internal_ns
881 internal_ns = self.shell.internal_ns
899 user_ns_hidden = self.shell.user_ns_hidden
882 user_ns_hidden = self.shell.user_ns_hidden
900 out = [ i for i in user_ns
883 out = [ i for i in user_ns
901 if not i.startswith('_') \
884 if not i.startswith('_') \
902 and not (i in internal_ns or i in user_ns_hidden) ]
885 and not (i in internal_ns or i in user_ns_hidden) ]
903
886
904 typelist = parameter_s.split()
887 typelist = parameter_s.split()
905 if typelist:
888 if typelist:
906 typeset = set(typelist)
889 typeset = set(typelist)
907 out = [i for i in out if type(i).__name__ in typeset]
890 out = [i for i in out if type(i).__name__ in typeset]
908
891
909 out.sort()
892 out.sort()
910 return out
893 return out
911
894
912 def magic_who(self, parameter_s=''):
895 def magic_who(self, parameter_s=''):
913 """Print all interactive variables, with some minimal formatting.
896 """Print all interactive variables, with some minimal formatting.
914
897
915 If any arguments are given, only variables whose type matches one of
898 If any arguments are given, only variables whose type matches one of
916 these are printed. For example:
899 these are printed. For example:
917
900
918 %who function str
901 %who function str
919
902
920 will only list functions and strings, excluding all other types of
903 will only list functions and strings, excluding all other types of
921 variables. To find the proper type names, simply use type(var) at a
904 variables. To find the proper type names, simply use type(var) at a
922 command line to see how python prints type names. For example:
905 command line to see how python prints type names. For example:
923
906
924 In [1]: type('hello')\\
907 In [1]: type('hello')\\
925 Out[1]: <type 'str'>
908 Out[1]: <type 'str'>
926
909
927 indicates that the type name for strings is 'str'.
910 indicates that the type name for strings is 'str'.
928
911
929 %who always excludes executed names loaded through your configuration
912 %who always excludes executed names loaded through your configuration
930 file and things which are internal to IPython.
913 file and things which are internal to IPython.
931
914
932 This is deliberate, as typically you may load many modules and the
915 This is deliberate, as typically you may load many modules and the
933 purpose of %who is to show you only what you've manually defined."""
916 purpose of %who is to show you only what you've manually defined."""
934
917
935 varlist = self.magic_who_ls(parameter_s)
918 varlist = self.magic_who_ls(parameter_s)
936 if not varlist:
919 if not varlist:
937 if parameter_s:
920 if parameter_s:
938 print 'No variables match your requested type.'
921 print 'No variables match your requested type.'
939 else:
922 else:
940 print 'Interactive namespace is empty.'
923 print 'Interactive namespace is empty.'
941 return
924 return
942
925
943 # if we have variables, move on...
926 # if we have variables, move on...
944 count = 0
927 count = 0
945 for i in varlist:
928 for i in varlist:
946 print i+'\t',
929 print i+'\t',
947 count += 1
930 count += 1
948 if count > 8:
931 if count > 8:
949 count = 0
932 count = 0
950 print
933 print
951 print
934 print
952
935
953 def magic_whos(self, parameter_s=''):
936 def magic_whos(self, parameter_s=''):
954 """Like %who, but gives some extra information about each variable.
937 """Like %who, but gives some extra information about each variable.
955
938
956 The same type filtering of %who can be applied here.
939 The same type filtering of %who can be applied here.
957
940
958 For all variables, the type is printed. Additionally it prints:
941 For all variables, the type is printed. Additionally it prints:
959
942
960 - For {},[],(): their length.
943 - For {},[],(): their length.
961
944
962 - For numpy and Numeric arrays, a summary with shape, number of
945 - For numpy and Numeric arrays, a summary with shape, number of
963 elements, typecode and size in memory.
946 elements, typecode and size in memory.
964
947
965 - Everything else: a string representation, snipping their middle if
948 - Everything else: a string representation, snipping their middle if
966 too long."""
949 too long."""
967
950
968 varnames = self.magic_who_ls(parameter_s)
951 varnames = self.magic_who_ls(parameter_s)
969 if not varnames:
952 if not varnames:
970 if parameter_s:
953 if parameter_s:
971 print 'No variables match your requested type.'
954 print 'No variables match your requested type.'
972 else:
955 else:
973 print 'Interactive namespace is empty.'
956 print 'Interactive namespace is empty.'
974 return
957 return
975
958
976 # if we have variables, move on...
959 # if we have variables, move on...
977
960
978 # for these types, show len() instead of data:
961 # for these types, show len() instead of data:
979 seq_types = [types.DictType,types.ListType,types.TupleType]
962 seq_types = [types.DictType,types.ListType,types.TupleType]
980
963
981 # for numpy/Numeric arrays, display summary info
964 # for numpy/Numeric arrays, display summary info
982 try:
965 try:
983 import numpy
966 import numpy
984 except ImportError:
967 except ImportError:
985 ndarray_type = None
968 ndarray_type = None
986 else:
969 else:
987 ndarray_type = numpy.ndarray.__name__
970 ndarray_type = numpy.ndarray.__name__
988 try:
971 try:
989 import Numeric
972 import Numeric
990 except ImportError:
973 except ImportError:
991 array_type = None
974 array_type = None
992 else:
975 else:
993 array_type = Numeric.ArrayType.__name__
976 array_type = Numeric.ArrayType.__name__
994
977
995 # Find all variable names and types so we can figure out column sizes
978 # Find all variable names and types so we can figure out column sizes
996 def get_vars(i):
979 def get_vars(i):
997 return self.shell.user_ns[i]
980 return self.shell.user_ns[i]
998
981
999 # some types are well known and can be shorter
982 # some types are well known and can be shorter
1000 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
983 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1001 def type_name(v):
984 def type_name(v):
1002 tn = type(v).__name__
985 tn = type(v).__name__
1003 return abbrevs.get(tn,tn)
986 return abbrevs.get(tn,tn)
1004
987
1005 varlist = map(get_vars,varnames)
988 varlist = map(get_vars,varnames)
1006
989
1007 typelist = []
990 typelist = []
1008 for vv in varlist:
991 for vv in varlist:
1009 tt = type_name(vv)
992 tt = type_name(vv)
1010
993
1011 if tt=='instance':
994 if tt=='instance':
1012 typelist.append( abbrevs.get(str(vv.__class__),
995 typelist.append( abbrevs.get(str(vv.__class__),
1013 str(vv.__class__)))
996 str(vv.__class__)))
1014 else:
997 else:
1015 typelist.append(tt)
998 typelist.append(tt)
1016
999
1017 # column labels and # of spaces as separator
1000 # column labels and # of spaces as separator
1018 varlabel = 'Variable'
1001 varlabel = 'Variable'
1019 typelabel = 'Type'
1002 typelabel = 'Type'
1020 datalabel = 'Data/Info'
1003 datalabel = 'Data/Info'
1021 colsep = 3
1004 colsep = 3
1022 # variable format strings
1005 # variable format strings
1023 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1006 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1024 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1007 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1025 aformat = "%s: %s elems, type `%s`, %s bytes"
1008 aformat = "%s: %s elems, type `%s`, %s bytes"
1026 # find the size of the columns to format the output nicely
1009 # find the size of the columns to format the output nicely
1027 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1010 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1028 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1011 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1029 # table header
1012 # table header
1030 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1013 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1031 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1014 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1032 # and the table itself
1015 # and the table itself
1033 kb = 1024
1016 kb = 1024
1034 Mb = 1048576 # kb**2
1017 Mb = 1048576 # kb**2
1035 for vname,var,vtype in zip(varnames,varlist,typelist):
1018 for vname,var,vtype in zip(varnames,varlist,typelist):
1036 print itpl(vformat),
1019 print itpl(vformat),
1037 if vtype in seq_types:
1020 if vtype in seq_types:
1038 print len(var)
1021 print len(var)
1039 elif vtype in [array_type,ndarray_type]:
1022 elif vtype in [array_type,ndarray_type]:
1040 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1023 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1041 if vtype==ndarray_type:
1024 if vtype==ndarray_type:
1042 # numpy
1025 # numpy
1043 vsize = var.size
1026 vsize = var.size
1044 vbytes = vsize*var.itemsize
1027 vbytes = vsize*var.itemsize
1045 vdtype = var.dtype
1028 vdtype = var.dtype
1046 else:
1029 else:
1047 # Numeric
1030 # Numeric
1048 vsize = Numeric.size(var)
1031 vsize = Numeric.size(var)
1049 vbytes = vsize*var.itemsize()
1032 vbytes = vsize*var.itemsize()
1050 vdtype = var.typecode()
1033 vdtype = var.typecode()
1051
1034
1052 if vbytes < 100000:
1035 if vbytes < 100000:
1053 print aformat % (vshape,vsize,vdtype,vbytes)
1036 print aformat % (vshape,vsize,vdtype,vbytes)
1054 else:
1037 else:
1055 print aformat % (vshape,vsize,vdtype,vbytes),
1038 print aformat % (vshape,vsize,vdtype,vbytes),
1056 if vbytes < Mb:
1039 if vbytes < Mb:
1057 print '(%s kb)' % (vbytes/kb,)
1040 print '(%s kb)' % (vbytes/kb,)
1058 else:
1041 else:
1059 print '(%s Mb)' % (vbytes/Mb,)
1042 print '(%s Mb)' % (vbytes/Mb,)
1060 else:
1043 else:
1061 try:
1044 try:
1062 vstr = str(var)
1045 vstr = str(var)
1063 except UnicodeEncodeError:
1046 except UnicodeEncodeError:
1064 vstr = unicode(var).encode(sys.getdefaultencoding(),
1047 vstr = unicode(var).encode(sys.getdefaultencoding(),
1065 'backslashreplace')
1048 'backslashreplace')
1066 vstr = vstr.replace('\n','\\n')
1049 vstr = vstr.replace('\n','\\n')
1067 if len(vstr) < 50:
1050 if len(vstr) < 50:
1068 print vstr
1051 print vstr
1069 else:
1052 else:
1070 printpl(vfmt_short)
1053 printpl(vfmt_short)
1071
1054
1072 def magic_reset(self, parameter_s=''):
1055 def magic_reset(self, parameter_s=''):
1073 """Resets the namespace by removing all names defined by the user.
1056 """Resets the namespace by removing all names defined by the user.
1074
1057
1075 Input/Output history are left around in case you need them.
1058 Input/Output history are left around in case you need them.
1076
1059
1077 Parameters
1060 Parameters
1078 ----------
1061 ----------
1079 -y : force reset without asking for confirmation.
1062 -y : force reset without asking for confirmation.
1080
1063
1081 Examples
1064 Examples
1082 --------
1065 --------
1083 In [6]: a = 1
1066 In [6]: a = 1
1084
1067
1085 In [7]: a
1068 In [7]: a
1086 Out[7]: 1
1069 Out[7]: 1
1087
1070
1088 In [8]: 'a' in _ip.user_ns
1071 In [8]: 'a' in _ip.user_ns
1089 Out[8]: True
1072 Out[8]: True
1090
1073
1091 In [9]: %reset -f
1074 In [9]: %reset -f
1092
1075
1093 In [10]: 'a' in _ip.user_ns
1076 In [10]: 'a' in _ip.user_ns
1094 Out[10]: False
1077 Out[10]: False
1095 """
1078 """
1096
1079
1097 if parameter_s == '-f':
1080 if parameter_s == '-f':
1098 ans = True
1081 ans = True
1099 else:
1082 else:
1100 ans = self.shell.ask_yes_no(
1083 ans = self.shell.ask_yes_no(
1101 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1084 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1102 if not ans:
1085 if not ans:
1103 print 'Nothing done.'
1086 print 'Nothing done.'
1104 return
1087 return
1105 user_ns = self.shell.user_ns
1088 user_ns = self.shell.user_ns
1106 for i in self.magic_who_ls():
1089 for i in self.magic_who_ls():
1107 del(user_ns[i])
1090 del(user_ns[i])
1108
1091
1109 # Also flush the private list of module references kept for script
1092 # Also flush the private list of module references kept for script
1110 # execution protection
1093 # execution protection
1111 self.shell.clear_main_mod_cache()
1094 self.shell.clear_main_mod_cache()
1112
1095
1113 def magic_reset_selective(self, parameter_s=''):
1096 def magic_reset_selective(self, parameter_s=''):
1114 """Resets the namespace by removing names defined by the user.
1097 """Resets the namespace by removing names defined by the user.
1115
1098
1116 Input/Output history are left around in case you need them.
1099 Input/Output history are left around in case you need them.
1117
1100
1118 %reset_selective [-f] regex
1101 %reset_selective [-f] regex
1119
1102
1120 No action is taken if regex is not included
1103 No action is taken if regex is not included
1121
1104
1122 Options
1105 Options
1123 -f : force reset without asking for confirmation.
1106 -f : force reset without asking for confirmation.
1124
1107
1125 Examples
1108 Examples
1126 --------
1109 --------
1127
1110
1128 We first fully reset the namespace so your output looks identical to
1111 We first fully reset the namespace so your output looks identical to
1129 this example for pedagogical reasons; in practice you do not need a
1112 this example for pedagogical reasons; in practice you do not need a
1130 full reset.
1113 full reset.
1131
1114
1132 In [1]: %reset -f
1115 In [1]: %reset -f
1133
1116
1134 Now, with a clean namespace we can make a few variables and use
1117 Now, with a clean namespace we can make a few variables and use
1135 %reset_selective to only delete names that match our regexp:
1118 %reset_selective to only delete names that match our regexp:
1136
1119
1137 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1120 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1138
1121
1139 In [3]: who_ls
1122 In [3]: who_ls
1140 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1123 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1141
1124
1142 In [4]: %reset_selective -f b[2-3]m
1125 In [4]: %reset_selective -f b[2-3]m
1143
1126
1144 In [5]: who_ls
1127 In [5]: who_ls
1145 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1128 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1146
1129
1147 In [6]: %reset_selective -f d
1130 In [6]: %reset_selective -f d
1148
1131
1149 In [7]: who_ls
1132 In [7]: who_ls
1150 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1133 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1151
1134
1152 In [8]: %reset_selective -f c
1135 In [8]: %reset_selective -f c
1153
1136
1154 In [9]: who_ls
1137 In [9]: who_ls
1155 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1138 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1156
1139
1157 In [10]: %reset_selective -f b
1140 In [10]: %reset_selective -f b
1158
1141
1159 In [11]: who_ls
1142 In [11]: who_ls
1160 Out[11]: ['a']
1143 Out[11]: ['a']
1161 """
1144 """
1162
1145
1163 opts, regex = self.parse_options(parameter_s,'f')
1146 opts, regex = self.parse_options(parameter_s,'f')
1164
1147
1165 if opts.has_key('f'):
1148 if opts.has_key('f'):
1166 ans = True
1149 ans = True
1167 else:
1150 else:
1168 ans = self.shell.ask_yes_no(
1151 ans = self.shell.ask_yes_no(
1169 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1152 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1170 if not ans:
1153 if not ans:
1171 print 'Nothing done.'
1154 print 'Nothing done.'
1172 return
1155 return
1173 user_ns = self.shell.user_ns
1156 user_ns = self.shell.user_ns
1174 if not regex:
1157 if not regex:
1175 print 'No regex pattern specified. Nothing done.'
1158 print 'No regex pattern specified. Nothing done.'
1176 return
1159 return
1177 else:
1160 else:
1178 try:
1161 try:
1179 m = re.compile(regex)
1162 m = re.compile(regex)
1180 except TypeError:
1163 except TypeError:
1181 raise TypeError('regex must be a string or compiled pattern')
1164 raise TypeError('regex must be a string or compiled pattern')
1182 for i in self.magic_who_ls():
1165 for i in self.magic_who_ls():
1183 if m.search(i):
1166 if m.search(i):
1184 del(user_ns[i])
1167 del(user_ns[i])
1185
1168
1186 def magic_logstart(self,parameter_s=''):
1169 def magic_logstart(self,parameter_s=''):
1187 """Start logging anywhere in a session.
1170 """Start logging anywhere in a session.
1188
1171
1189 %logstart [-o|-r|-t] [log_name [log_mode]]
1172 %logstart [-o|-r|-t] [log_name [log_mode]]
1190
1173
1191 If no name is given, it defaults to a file named 'ipython_log.py' in your
1174 If no name is given, it defaults to a file named 'ipython_log.py' in your
1192 current directory, in 'rotate' mode (see below).
1175 current directory, in 'rotate' mode (see below).
1193
1176
1194 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1177 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1195 history up to that point and then continues logging.
1178 history up to that point and then continues logging.
1196
1179
1197 %logstart takes a second optional parameter: logging mode. This can be one
1180 %logstart takes a second optional parameter: logging mode. This can be one
1198 of (note that the modes are given unquoted):\\
1181 of (note that the modes are given unquoted):\\
1199 append: well, that says it.\\
1182 append: well, that says it.\\
1200 backup: rename (if exists) to name~ and start name.\\
1183 backup: rename (if exists) to name~ and start name.\\
1201 global: single logfile in your home dir, appended to.\\
1184 global: single logfile in your home dir, appended to.\\
1202 over : overwrite existing log.\\
1185 over : overwrite existing log.\\
1203 rotate: create rotating logs name.1~, name.2~, etc.
1186 rotate: create rotating logs name.1~, name.2~, etc.
1204
1187
1205 Options:
1188 Options:
1206
1189
1207 -o: log also IPython's output. In this mode, all commands which
1190 -o: log also IPython's output. In this mode, all commands which
1208 generate an Out[NN] prompt are recorded to the logfile, right after
1191 generate an Out[NN] prompt are recorded to the logfile, right after
1209 their corresponding input line. The output lines are always
1192 their corresponding input line. The output lines are always
1210 prepended with a '#[Out]# ' marker, so that the log remains valid
1193 prepended with a '#[Out]# ' marker, so that the log remains valid
1211 Python code.
1194 Python code.
1212
1195
1213 Since this marker is always the same, filtering only the output from
1196 Since this marker is always the same, filtering only the output from
1214 a log is very easy, using for example a simple awk call:
1197 a log is very easy, using for example a simple awk call:
1215
1198
1216 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1199 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1217
1200
1218 -r: log 'raw' input. Normally, IPython's logs contain the processed
1201 -r: log 'raw' input. Normally, IPython's logs contain the processed
1219 input, so that user lines are logged in their final form, converted
1202 input, so that user lines are logged in their final form, converted
1220 into valid Python. For example, %Exit is logged as
1203 into valid Python. For example, %Exit is logged as
1221 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1204 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1222 exactly as typed, with no transformations applied.
1205 exactly as typed, with no transformations applied.
1223
1206
1224 -t: put timestamps before each input line logged (these are put in
1207 -t: put timestamps before each input line logged (these are put in
1225 comments)."""
1208 comments)."""
1226
1209
1227 opts,par = self.parse_options(parameter_s,'ort')
1210 opts,par = self.parse_options(parameter_s,'ort')
1228 log_output = 'o' in opts
1211 log_output = 'o' in opts
1229 log_raw_input = 'r' in opts
1212 log_raw_input = 'r' in opts
1230 timestamp = 't' in opts
1213 timestamp = 't' in opts
1231
1214
1232 logger = self.shell.logger
1215 logger = self.shell.logger
1233
1216
1234 # if no args are given, the defaults set in the logger constructor by
1217 # if no args are given, the defaults set in the logger constructor by
1235 # ipytohn remain valid
1218 # ipytohn remain valid
1236 if par:
1219 if par:
1237 try:
1220 try:
1238 logfname,logmode = par.split()
1221 logfname,logmode = par.split()
1239 except:
1222 except:
1240 logfname = par
1223 logfname = par
1241 logmode = 'backup'
1224 logmode = 'backup'
1242 else:
1225 else:
1243 logfname = logger.logfname
1226 logfname = logger.logfname
1244 logmode = logger.logmode
1227 logmode = logger.logmode
1245 # put logfname into rc struct as if it had been called on the command
1228 # put logfname into rc struct as if it had been called on the command
1246 # line, so it ends up saved in the log header Save it in case we need
1229 # line, so it ends up saved in the log header Save it in case we need
1247 # to restore it...
1230 # to restore it...
1248 old_logfile = self.shell.logfile
1231 old_logfile = self.shell.logfile
1249 if logfname:
1232 if logfname:
1250 logfname = os.path.expanduser(logfname)
1233 logfname = os.path.expanduser(logfname)
1251 self.shell.logfile = logfname
1234 self.shell.logfile = logfname
1252
1235
1253 loghead = '# IPython log file\n\n'
1236 loghead = '# IPython log file\n\n'
1254 try:
1237 try:
1255 started = logger.logstart(logfname,loghead,logmode,
1238 started = logger.logstart(logfname,loghead,logmode,
1256 log_output,timestamp,log_raw_input)
1239 log_output,timestamp,log_raw_input)
1257 except:
1240 except:
1258 self.shell.logfile = old_logfile
1241 self.shell.logfile = old_logfile
1259 warn("Couldn't start log: %s" % sys.exc_info()[1])
1242 warn("Couldn't start log: %s" % sys.exc_info()[1])
1260 else:
1243 else:
1261 # log input history up to this point, optionally interleaving
1244 # log input history up to this point, optionally interleaving
1262 # output if requested
1245 # output if requested
1263
1246
1264 if timestamp:
1247 if timestamp:
1265 # disable timestamping for the previous history, since we've
1248 # disable timestamping for the previous history, since we've
1266 # lost those already (no time machine here).
1249 # lost those already (no time machine here).
1267 logger.timestamp = False
1250 logger.timestamp = False
1268
1251
1269 if log_raw_input:
1252 if log_raw_input:
1270 input_hist = self.shell.input_hist_raw
1253 input_hist = self.shell.input_hist_raw
1271 else:
1254 else:
1272 input_hist = self.shell.input_hist
1255 input_hist = self.shell.input_hist
1273
1256
1274 if log_output:
1257 if log_output:
1275 log_write = logger.log_write
1258 log_write = logger.log_write
1276 output_hist = self.shell.output_hist
1259 output_hist = self.shell.output_hist
1277 for n in range(1,len(input_hist)-1):
1260 for n in range(1,len(input_hist)-1):
1278 log_write(input_hist[n].rstrip())
1261 log_write(input_hist[n].rstrip())
1279 if n in output_hist:
1262 if n in output_hist:
1280 log_write(repr(output_hist[n]),'output')
1263 log_write(repr(output_hist[n]),'output')
1281 else:
1264 else:
1282 logger.log_write(input_hist[1:])
1265 logger.log_write(input_hist[1:])
1283 if timestamp:
1266 if timestamp:
1284 # re-enable timestamping
1267 # re-enable timestamping
1285 logger.timestamp = True
1268 logger.timestamp = True
1286
1269
1287 print ('Activating auto-logging. '
1270 print ('Activating auto-logging. '
1288 'Current session state plus future input saved.')
1271 'Current session state plus future input saved.')
1289 logger.logstate()
1272 logger.logstate()
1290
1273
1291 def magic_logstop(self,parameter_s=''):
1274 def magic_logstop(self,parameter_s=''):
1292 """Fully stop logging and close log file.
1275 """Fully stop logging and close log file.
1293
1276
1294 In order to start logging again, a new %logstart call needs to be made,
1277 In order to start logging again, a new %logstart call needs to be made,
1295 possibly (though not necessarily) with a new filename, mode and other
1278 possibly (though not necessarily) with a new filename, mode and other
1296 options."""
1279 options."""
1297 self.logger.logstop()
1280 self.logger.logstop()
1298
1281
1299 def magic_logoff(self,parameter_s=''):
1282 def magic_logoff(self,parameter_s=''):
1300 """Temporarily stop logging.
1283 """Temporarily stop logging.
1301
1284
1302 You must have previously started logging."""
1285 You must have previously started logging."""
1303 self.shell.logger.switch_log(0)
1286 self.shell.logger.switch_log(0)
1304
1287
1305 def magic_logon(self,parameter_s=''):
1288 def magic_logon(self,parameter_s=''):
1306 """Restart logging.
1289 """Restart logging.
1307
1290
1308 This function is for restarting logging which you've temporarily
1291 This function is for restarting logging which you've temporarily
1309 stopped with %logoff. For starting logging for the first time, you
1292 stopped with %logoff. For starting logging for the first time, you
1310 must use the %logstart function, which allows you to specify an
1293 must use the %logstart function, which allows you to specify an
1311 optional log filename."""
1294 optional log filename."""
1312
1295
1313 self.shell.logger.switch_log(1)
1296 self.shell.logger.switch_log(1)
1314
1297
1315 def magic_logstate(self,parameter_s=''):
1298 def magic_logstate(self,parameter_s=''):
1316 """Print the status of the logging system."""
1299 """Print the status of the logging system."""
1317
1300
1318 self.shell.logger.logstate()
1301 self.shell.logger.logstate()
1319
1302
1320 def magic_pdb(self, parameter_s=''):
1303 def magic_pdb(self, parameter_s=''):
1321 """Control the automatic calling of the pdb interactive debugger.
1304 """Control the automatic calling of the pdb interactive debugger.
1322
1305
1323 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1306 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1324 argument it works as a toggle.
1307 argument it works as a toggle.
1325
1308
1326 When an exception is triggered, IPython can optionally call the
1309 When an exception is triggered, IPython can optionally call the
1327 interactive pdb debugger after the traceback printout. %pdb toggles
1310 interactive pdb debugger after the traceback printout. %pdb toggles
1328 this feature on and off.
1311 this feature on and off.
1329
1312
1330 The initial state of this feature is set in your ipythonrc
1313 The initial state of this feature is set in your ipythonrc
1331 configuration file (the variable is called 'pdb').
1314 configuration file (the variable is called 'pdb').
1332
1315
1333 If you want to just activate the debugger AFTER an exception has fired,
1316 If you want to just activate the debugger AFTER an exception has fired,
1334 without having to type '%pdb on' and rerunning your code, you can use
1317 without having to type '%pdb on' and rerunning your code, you can use
1335 the %debug magic."""
1318 the %debug magic."""
1336
1319
1337 par = parameter_s.strip().lower()
1320 par = parameter_s.strip().lower()
1338
1321
1339 if par:
1322 if par:
1340 try:
1323 try:
1341 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1324 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1342 except KeyError:
1325 except KeyError:
1343 print ('Incorrect argument. Use on/1, off/0, '
1326 print ('Incorrect argument. Use on/1, off/0, '
1344 'or nothing for a toggle.')
1327 'or nothing for a toggle.')
1345 return
1328 return
1346 else:
1329 else:
1347 # toggle
1330 # toggle
1348 new_pdb = not self.shell.call_pdb
1331 new_pdb = not self.shell.call_pdb
1349
1332
1350 # set on the shell
1333 # set on the shell
1351 self.shell.call_pdb = new_pdb
1334 self.shell.call_pdb = new_pdb
1352 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1335 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1353
1336
1354 def magic_debug(self, parameter_s=''):
1337 def magic_debug(self, parameter_s=''):
1355 """Activate the interactive debugger in post-mortem mode.
1338 """Activate the interactive debugger in post-mortem mode.
1356
1339
1357 If an exception has just occurred, this lets you inspect its stack
1340 If an exception has just occurred, this lets you inspect its stack
1358 frames interactively. Note that this will always work only on the last
1341 frames interactively. Note that this will always work only on the last
1359 traceback that occurred, so you must call this quickly after an
1342 traceback that occurred, so you must call this quickly after an
1360 exception that you wish to inspect has fired, because if another one
1343 exception that you wish to inspect has fired, because if another one
1361 occurs, it clobbers the previous one.
1344 occurs, it clobbers the previous one.
1362
1345
1363 If you want IPython to automatically do this on every exception, see
1346 If you want IPython to automatically do this on every exception, see
1364 the %pdb magic for more details.
1347 the %pdb magic for more details.
1365 """
1348 """
1366 self.shell.debugger(force=True)
1349 self.shell.debugger(force=True)
1367
1350
1368 @testdec.skip_doctest
1351 @testdec.skip_doctest
1369 def magic_prun(self, parameter_s ='',user_mode=1,
1352 def magic_prun(self, parameter_s ='',user_mode=1,
1370 opts=None,arg_lst=None,prog_ns=None):
1353 opts=None,arg_lst=None,prog_ns=None):
1371
1354
1372 """Run a statement through the python code profiler.
1355 """Run a statement through the python code profiler.
1373
1356
1374 Usage:
1357 Usage:
1375 %prun [options] statement
1358 %prun [options] statement
1376
1359
1377 The given statement (which doesn't require quote marks) is run via the
1360 The given statement (which doesn't require quote marks) is run via the
1378 python profiler in a manner similar to the profile.run() function.
1361 python profiler in a manner similar to the profile.run() function.
1379 Namespaces are internally managed to work correctly; profile.run
1362 Namespaces are internally managed to work correctly; profile.run
1380 cannot be used in IPython because it makes certain assumptions about
1363 cannot be used in IPython because it makes certain assumptions about
1381 namespaces which do not hold under IPython.
1364 namespaces which do not hold under IPython.
1382
1365
1383 Options:
1366 Options:
1384
1367
1385 -l <limit>: you can place restrictions on what or how much of the
1368 -l <limit>: you can place restrictions on what or how much of the
1386 profile gets printed. The limit value can be:
1369 profile gets printed. The limit value can be:
1387
1370
1388 * A string: only information for function names containing this string
1371 * A string: only information for function names containing this string
1389 is printed.
1372 is printed.
1390
1373
1391 * An integer: only these many lines are printed.
1374 * An integer: only these many lines are printed.
1392
1375
1393 * A float (between 0 and 1): this fraction of the report is printed
1376 * A float (between 0 and 1): this fraction of the report is printed
1394 (for example, use a limit of 0.4 to see the topmost 40% only).
1377 (for example, use a limit of 0.4 to see the topmost 40% only).
1395
1378
1396 You can combine several limits with repeated use of the option. For
1379 You can combine several limits with repeated use of the option. For
1397 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1380 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1398 information about class constructors.
1381 information about class constructors.
1399
1382
1400 -r: return the pstats.Stats object generated by the profiling. This
1383 -r: return the pstats.Stats object generated by the profiling. This
1401 object has all the information about the profile in it, and you can
1384 object has all the information about the profile in it, and you can
1402 later use it for further analysis or in other functions.
1385 later use it for further analysis or in other functions.
1403
1386
1404 -s <key>: sort profile by given key. You can provide more than one key
1387 -s <key>: sort profile by given key. You can provide more than one key
1405 by using the option several times: '-s key1 -s key2 -s key3...'. The
1388 by using the option several times: '-s key1 -s key2 -s key3...'. The
1406 default sorting key is 'time'.
1389 default sorting key is 'time'.
1407
1390
1408 The following is copied verbatim from the profile documentation
1391 The following is copied verbatim from the profile documentation
1409 referenced below:
1392 referenced below:
1410
1393
1411 When more than one key is provided, additional keys are used as
1394 When more than one key is provided, additional keys are used as
1412 secondary criteria when the there is equality in all keys selected
1395 secondary criteria when the there is equality in all keys selected
1413 before them.
1396 before them.
1414
1397
1415 Abbreviations can be used for any key names, as long as the
1398 Abbreviations can be used for any key names, as long as the
1416 abbreviation is unambiguous. The following are the keys currently
1399 abbreviation is unambiguous. The following are the keys currently
1417 defined:
1400 defined:
1418
1401
1419 Valid Arg Meaning
1402 Valid Arg Meaning
1420 "calls" call count
1403 "calls" call count
1421 "cumulative" cumulative time
1404 "cumulative" cumulative time
1422 "file" file name
1405 "file" file name
1423 "module" file name
1406 "module" file name
1424 "pcalls" primitive call count
1407 "pcalls" primitive call count
1425 "line" line number
1408 "line" line number
1426 "name" function name
1409 "name" function name
1427 "nfl" name/file/line
1410 "nfl" name/file/line
1428 "stdname" standard name
1411 "stdname" standard name
1429 "time" internal time
1412 "time" internal time
1430
1413
1431 Note that all sorts on statistics are in descending order (placing
1414 Note that all sorts on statistics are in descending order (placing
1432 most time consuming items first), where as name, file, and line number
1415 most time consuming items first), where as name, file, and line number
1433 searches are in ascending order (i.e., alphabetical). The subtle
1416 searches are in ascending order (i.e., alphabetical). The subtle
1434 distinction between "nfl" and "stdname" is that the standard name is a
1417 distinction between "nfl" and "stdname" is that the standard name is a
1435 sort of the name as printed, which means that the embedded line
1418 sort of the name as printed, which means that the embedded line
1436 numbers get compared in an odd way. For example, lines 3, 20, and 40
1419 numbers get compared in an odd way. For example, lines 3, 20, and 40
1437 would (if the file names were the same) appear in the string order
1420 would (if the file names were the same) appear in the string order
1438 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1421 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1439 line numbers. In fact, sort_stats("nfl") is the same as
1422 line numbers. In fact, sort_stats("nfl") is the same as
1440 sort_stats("name", "file", "line").
1423 sort_stats("name", "file", "line").
1441
1424
1442 -T <filename>: save profile results as shown on screen to a text
1425 -T <filename>: save profile results as shown on screen to a text
1443 file. The profile is still shown on screen.
1426 file. The profile is still shown on screen.
1444
1427
1445 -D <filename>: save (via dump_stats) profile statistics to given
1428 -D <filename>: save (via dump_stats) profile statistics to given
1446 filename. This data is in a format understod by the pstats module, and
1429 filename. This data is in a format understod by the pstats module, and
1447 is generated by a call to the dump_stats() method of profile
1430 is generated by a call to the dump_stats() method of profile
1448 objects. The profile is still shown on screen.
1431 objects. The profile is still shown on screen.
1449
1432
1450 If you want to run complete programs under the profiler's control, use
1433 If you want to run complete programs under the profiler's control, use
1451 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1434 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1452 contains profiler specific options as described here.
1435 contains profiler specific options as described here.
1453
1436
1454 You can read the complete documentation for the profile module with::
1437 You can read the complete documentation for the profile module with::
1455
1438
1456 In [1]: import profile; profile.help()
1439 In [1]: import profile; profile.help()
1457 """
1440 """
1458
1441
1459 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1442 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1460 # protect user quote marks
1443 # protect user quote marks
1461 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1444 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1462
1445
1463 if user_mode: # regular user call
1446 if user_mode: # regular user call
1464 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1447 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1465 list_all=1)
1448 list_all=1)
1466 namespace = self.shell.user_ns
1449 namespace = self.shell.user_ns
1467 else: # called to run a program by %run -p
1450 else: # called to run a program by %run -p
1468 try:
1451 try:
1469 filename = get_py_filename(arg_lst[0])
1452 filename = get_py_filename(arg_lst[0])
1470 except IOError,msg:
1453 except IOError,msg:
1471 error(msg)
1454 error(msg)
1472 return
1455 return
1473
1456
1474 arg_str = 'execfile(filename,prog_ns)'
1457 arg_str = 'execfile(filename,prog_ns)'
1475 namespace = locals()
1458 namespace = locals()
1476
1459
1477 opts.merge(opts_def)
1460 opts.merge(opts_def)
1478
1461
1479 prof = profile.Profile()
1462 prof = profile.Profile()
1480 try:
1463 try:
1481 prof = prof.runctx(arg_str,namespace,namespace)
1464 prof = prof.runctx(arg_str,namespace,namespace)
1482 sys_exit = ''
1465 sys_exit = ''
1483 except SystemExit:
1466 except SystemExit:
1484 sys_exit = """*** SystemExit exception caught in code being profiled."""
1467 sys_exit = """*** SystemExit exception caught in code being profiled."""
1485
1468
1486 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1469 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1487
1470
1488 lims = opts.l
1471 lims = opts.l
1489 if lims:
1472 if lims:
1490 lims = [] # rebuild lims with ints/floats/strings
1473 lims = [] # rebuild lims with ints/floats/strings
1491 for lim in opts.l:
1474 for lim in opts.l:
1492 try:
1475 try:
1493 lims.append(int(lim))
1476 lims.append(int(lim))
1494 except ValueError:
1477 except ValueError:
1495 try:
1478 try:
1496 lims.append(float(lim))
1479 lims.append(float(lim))
1497 except ValueError:
1480 except ValueError:
1498 lims.append(lim)
1481 lims.append(lim)
1499
1482
1500 # Trap output.
1483 # Trap output.
1501 stdout_trap = StringIO()
1484 stdout_trap = StringIO()
1502
1485
1503 if hasattr(stats,'stream'):
1486 if hasattr(stats,'stream'):
1504 # In newer versions of python, the stats object has a 'stream'
1487 # In newer versions of python, the stats object has a 'stream'
1505 # attribute to write into.
1488 # attribute to write into.
1506 stats.stream = stdout_trap
1489 stats.stream = stdout_trap
1507 stats.print_stats(*lims)
1490 stats.print_stats(*lims)
1508 else:
1491 else:
1509 # For older versions, we manually redirect stdout during printing
1492 # For older versions, we manually redirect stdout during printing
1510 sys_stdout = sys.stdout
1493 sys_stdout = sys.stdout
1511 try:
1494 try:
1512 sys.stdout = stdout_trap
1495 sys.stdout = stdout_trap
1513 stats.print_stats(*lims)
1496 stats.print_stats(*lims)
1514 finally:
1497 finally:
1515 sys.stdout = sys_stdout
1498 sys.stdout = sys_stdout
1516
1499
1517 output = stdout_trap.getvalue()
1500 output = stdout_trap.getvalue()
1518 output = output.rstrip()
1501 output = output.rstrip()
1519
1502
1520 page.page(output)
1503 page.page(output)
1521 print sys_exit,
1504 print sys_exit,
1522
1505
1523 dump_file = opts.D[0]
1506 dump_file = opts.D[0]
1524 text_file = opts.T[0]
1507 text_file = opts.T[0]
1525 if dump_file:
1508 if dump_file:
1526 prof.dump_stats(dump_file)
1509 prof.dump_stats(dump_file)
1527 print '\n*** Profile stats marshalled to file',\
1510 print '\n*** Profile stats marshalled to file',\
1528 `dump_file`+'.',sys_exit
1511 `dump_file`+'.',sys_exit
1529 if text_file:
1512 if text_file:
1530 pfile = file(text_file,'w')
1513 pfile = file(text_file,'w')
1531 pfile.write(output)
1514 pfile.write(output)
1532 pfile.close()
1515 pfile.close()
1533 print '\n*** Profile printout saved to text file',\
1516 print '\n*** Profile printout saved to text file',\
1534 `text_file`+'.',sys_exit
1517 `text_file`+'.',sys_exit
1535
1518
1536 if opts.has_key('r'):
1519 if opts.has_key('r'):
1537 return stats
1520 return stats
1538 else:
1521 else:
1539 return None
1522 return None
1540
1523
1541 @testdec.skip_doctest
1524 @testdec.skip_doctest
1542 def magic_run(self, parameter_s ='',runner=None,
1525 def magic_run(self, parameter_s ='',runner=None,
1543 file_finder=get_py_filename):
1526 file_finder=get_py_filename):
1544 """Run the named file inside IPython as a program.
1527 """Run the named file inside IPython as a program.
1545
1528
1546 Usage:\\
1529 Usage:\\
1547 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1530 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1548
1531
1549 Parameters after the filename are passed as command-line arguments to
1532 Parameters after the filename are passed as command-line arguments to
1550 the program (put in sys.argv). Then, control returns to IPython's
1533 the program (put in sys.argv). Then, control returns to IPython's
1551 prompt.
1534 prompt.
1552
1535
1553 This is similar to running at a system prompt:\\
1536 This is similar to running at a system prompt:\\
1554 $ python file args\\
1537 $ python file args\\
1555 but with the advantage of giving you IPython's tracebacks, and of
1538 but with the advantage of giving you IPython's tracebacks, and of
1556 loading all variables into your interactive namespace for further use
1539 loading all variables into your interactive namespace for further use
1557 (unless -p is used, see below).
1540 (unless -p is used, see below).
1558
1541
1559 The file is executed in a namespace initially consisting only of
1542 The file is executed in a namespace initially consisting only of
1560 __name__=='__main__' and sys.argv constructed as indicated. It thus
1543 __name__=='__main__' and sys.argv constructed as indicated. It thus
1561 sees its environment as if it were being run as a stand-alone program
1544 sees its environment as if it were being run as a stand-alone program
1562 (except for sharing global objects such as previously imported
1545 (except for sharing global objects such as previously imported
1563 modules). But after execution, the IPython interactive namespace gets
1546 modules). But after execution, the IPython interactive namespace gets
1564 updated with all variables defined in the program (except for __name__
1547 updated with all variables defined in the program (except for __name__
1565 and sys.argv). This allows for very convenient loading of code for
1548 and sys.argv). This allows for very convenient loading of code for
1566 interactive work, while giving each program a 'clean sheet' to run in.
1549 interactive work, while giving each program a 'clean sheet' to run in.
1567
1550
1568 Options:
1551 Options:
1569
1552
1570 -n: __name__ is NOT set to '__main__', but to the running file's name
1553 -n: __name__ is NOT set to '__main__', but to the running file's name
1571 without extension (as python does under import). This allows running
1554 without extension (as python does under import). This allows running
1572 scripts and reloading the definitions in them without calling code
1555 scripts and reloading the definitions in them without calling code
1573 protected by an ' if __name__ == "__main__" ' clause.
1556 protected by an ' if __name__ == "__main__" ' clause.
1574
1557
1575 -i: run the file in IPython's namespace instead of an empty one. This
1558 -i: run the file in IPython's namespace instead of an empty one. This
1576 is useful if you are experimenting with code written in a text editor
1559 is useful if you are experimenting with code written in a text editor
1577 which depends on variables defined interactively.
1560 which depends on variables defined interactively.
1578
1561
1579 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1562 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1580 being run. This is particularly useful if IPython is being used to
1563 being run. This is particularly useful if IPython is being used to
1581 run unittests, which always exit with a sys.exit() call. In such
1564 run unittests, which always exit with a sys.exit() call. In such
1582 cases you are interested in the output of the test results, not in
1565 cases you are interested in the output of the test results, not in
1583 seeing a traceback of the unittest module.
1566 seeing a traceback of the unittest module.
1584
1567
1585 -t: print timing information at the end of the run. IPython will give
1568 -t: print timing information at the end of the run. IPython will give
1586 you an estimated CPU time consumption for your script, which under
1569 you an estimated CPU time consumption for your script, which under
1587 Unix uses the resource module to avoid the wraparound problems of
1570 Unix uses the resource module to avoid the wraparound problems of
1588 time.clock(). Under Unix, an estimate of time spent on system tasks
1571 time.clock(). Under Unix, an estimate of time spent on system tasks
1589 is also given (for Windows platforms this is reported as 0.0).
1572 is also given (for Windows platforms this is reported as 0.0).
1590
1573
1591 If -t is given, an additional -N<N> option can be given, where <N>
1574 If -t is given, an additional -N<N> option can be given, where <N>
1592 must be an integer indicating how many times you want the script to
1575 must be an integer indicating how many times you want the script to
1593 run. The final timing report will include total and per run results.
1576 run. The final timing report will include total and per run results.
1594
1577
1595 For example (testing the script uniq_stable.py):
1578 For example (testing the script uniq_stable.py):
1596
1579
1597 In [1]: run -t uniq_stable
1580 In [1]: run -t uniq_stable
1598
1581
1599 IPython CPU timings (estimated):\\
1582 IPython CPU timings (estimated):\\
1600 User : 0.19597 s.\\
1583 User : 0.19597 s.\\
1601 System: 0.0 s.\\
1584 System: 0.0 s.\\
1602
1585
1603 In [2]: run -t -N5 uniq_stable
1586 In [2]: run -t -N5 uniq_stable
1604
1587
1605 IPython CPU timings (estimated):\\
1588 IPython CPU timings (estimated):\\
1606 Total runs performed: 5\\
1589 Total runs performed: 5\\
1607 Times : Total Per run\\
1590 Times : Total Per run\\
1608 User : 0.910862 s, 0.1821724 s.\\
1591 User : 0.910862 s, 0.1821724 s.\\
1609 System: 0.0 s, 0.0 s.
1592 System: 0.0 s, 0.0 s.
1610
1593
1611 -d: run your program under the control of pdb, the Python debugger.
1594 -d: run your program under the control of pdb, the Python debugger.
1612 This allows you to execute your program step by step, watch variables,
1595 This allows you to execute your program step by step, watch variables,
1613 etc. Internally, what IPython does is similar to calling:
1596 etc. Internally, what IPython does is similar to calling:
1614
1597
1615 pdb.run('execfile("YOURFILENAME")')
1598 pdb.run('execfile("YOURFILENAME")')
1616
1599
1617 with a breakpoint set on line 1 of your file. You can change the line
1600 with a breakpoint set on line 1 of your file. You can change the line
1618 number for this automatic breakpoint to be <N> by using the -bN option
1601 number for this automatic breakpoint to be <N> by using the -bN option
1619 (where N must be an integer). For example:
1602 (where N must be an integer). For example:
1620
1603
1621 %run -d -b40 myscript
1604 %run -d -b40 myscript
1622
1605
1623 will set the first breakpoint at line 40 in myscript.py. Note that
1606 will set the first breakpoint at line 40 in myscript.py. Note that
1624 the first breakpoint must be set on a line which actually does
1607 the first breakpoint must be set on a line which actually does
1625 something (not a comment or docstring) for it to stop execution.
1608 something (not a comment or docstring) for it to stop execution.
1626
1609
1627 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1610 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1628 first enter 'c' (without qoutes) to start execution up to the first
1611 first enter 'c' (without qoutes) to start execution up to the first
1629 breakpoint.
1612 breakpoint.
1630
1613
1631 Entering 'help' gives information about the use of the debugger. You
1614 Entering 'help' gives information about the use of the debugger. You
1632 can easily see pdb's full documentation with "import pdb;pdb.help()"
1615 can easily see pdb's full documentation with "import pdb;pdb.help()"
1633 at a prompt.
1616 at a prompt.
1634
1617
1635 -p: run program under the control of the Python profiler module (which
1618 -p: run program under the control of the Python profiler module (which
1636 prints a detailed report of execution times, function calls, etc).
1619 prints a detailed report of execution times, function calls, etc).
1637
1620
1638 You can pass other options after -p which affect the behavior of the
1621 You can pass other options after -p which affect the behavior of the
1639 profiler itself. See the docs for %prun for details.
1622 profiler itself. See the docs for %prun for details.
1640
1623
1641 In this mode, the program's variables do NOT propagate back to the
1624 In this mode, the program's variables do NOT propagate back to the
1642 IPython interactive namespace (because they remain in the namespace
1625 IPython interactive namespace (because they remain in the namespace
1643 where the profiler executes them).
1626 where the profiler executes them).
1644
1627
1645 Internally this triggers a call to %prun, see its documentation for
1628 Internally this triggers a call to %prun, see its documentation for
1646 details on the options available specifically for profiling.
1629 details on the options available specifically for profiling.
1647
1630
1648 There is one special usage for which the text above doesn't apply:
1631 There is one special usage for which the text above doesn't apply:
1649 if the filename ends with .ipy, the file is run as ipython script,
1632 if the filename ends with .ipy, the file is run as ipython script,
1650 just as if the commands were written on IPython prompt.
1633 just as if the commands were written on IPython prompt.
1651 """
1634 """
1652
1635
1653 # get arguments and set sys.argv for program to be run.
1636 # get arguments and set sys.argv for program to be run.
1654 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1637 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1655 mode='list',list_all=1)
1638 mode='list',list_all=1)
1656
1639
1657 try:
1640 try:
1658 filename = file_finder(arg_lst[0])
1641 filename = file_finder(arg_lst[0])
1659 except IndexError:
1642 except IndexError:
1660 warn('you must provide at least a filename.')
1643 warn('you must provide at least a filename.')
1661 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1644 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1662 return
1645 return
1663 except IOError,msg:
1646 except IOError,msg:
1664 error(msg)
1647 error(msg)
1665 return
1648 return
1666
1649
1667 if filename.lower().endswith('.ipy'):
1650 if filename.lower().endswith('.ipy'):
1668 self.shell.safe_execfile_ipy(filename)
1651 self.shell.safe_execfile_ipy(filename)
1669 return
1652 return
1670
1653
1671 # Control the response to exit() calls made by the script being run
1654 # Control the response to exit() calls made by the script being run
1672 exit_ignore = opts.has_key('e')
1655 exit_ignore = opts.has_key('e')
1673
1656
1674 # Make sure that the running script gets a proper sys.argv as if it
1657 # Make sure that the running script gets a proper sys.argv as if it
1675 # were run from a system shell.
1658 # were run from a system shell.
1676 save_argv = sys.argv # save it for later restoring
1659 save_argv = sys.argv # save it for later restoring
1677 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1660 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1678
1661
1679 if opts.has_key('i'):
1662 if opts.has_key('i'):
1680 # Run in user's interactive namespace
1663 # Run in user's interactive namespace
1681 prog_ns = self.shell.user_ns
1664 prog_ns = self.shell.user_ns
1682 __name__save = self.shell.user_ns['__name__']
1665 __name__save = self.shell.user_ns['__name__']
1683 prog_ns['__name__'] = '__main__'
1666 prog_ns['__name__'] = '__main__'
1684 main_mod = self.shell.new_main_mod(prog_ns)
1667 main_mod = self.shell.new_main_mod(prog_ns)
1685 else:
1668 else:
1686 # Run in a fresh, empty namespace
1669 # Run in a fresh, empty namespace
1687 if opts.has_key('n'):
1670 if opts.has_key('n'):
1688 name = os.path.splitext(os.path.basename(filename))[0]
1671 name = os.path.splitext(os.path.basename(filename))[0]
1689 else:
1672 else:
1690 name = '__main__'
1673 name = '__main__'
1691
1674
1692 main_mod = self.shell.new_main_mod()
1675 main_mod = self.shell.new_main_mod()
1693 prog_ns = main_mod.__dict__
1676 prog_ns = main_mod.__dict__
1694 prog_ns['__name__'] = name
1677 prog_ns['__name__'] = name
1695
1678
1696 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1679 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1697 # set the __file__ global in the script's namespace
1680 # set the __file__ global in the script's namespace
1698 prog_ns['__file__'] = filename
1681 prog_ns['__file__'] = filename
1699
1682
1700 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1683 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1701 # that, if we overwrite __main__, we replace it at the end
1684 # that, if we overwrite __main__, we replace it at the end
1702 main_mod_name = prog_ns['__name__']
1685 main_mod_name = prog_ns['__name__']
1703
1686
1704 if main_mod_name == '__main__':
1687 if main_mod_name == '__main__':
1705 restore_main = sys.modules['__main__']
1688 restore_main = sys.modules['__main__']
1706 else:
1689 else:
1707 restore_main = False
1690 restore_main = False
1708
1691
1709 # This needs to be undone at the end to prevent holding references to
1692 # This needs to be undone at the end to prevent holding references to
1710 # every single object ever created.
1693 # every single object ever created.
1711 sys.modules[main_mod_name] = main_mod
1694 sys.modules[main_mod_name] = main_mod
1712
1695
1713 stats = None
1696 stats = None
1714 try:
1697 try:
1715 self.shell.savehist()
1698 self.shell.savehist()
1716
1699
1717 if opts.has_key('p'):
1700 if opts.has_key('p'):
1718 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1701 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1719 else:
1702 else:
1720 if opts.has_key('d'):
1703 if opts.has_key('d'):
1721 deb = debugger.Pdb(self.shell.colors)
1704 deb = debugger.Pdb(self.shell.colors)
1722 # reset Breakpoint state, which is moronically kept
1705 # reset Breakpoint state, which is moronically kept
1723 # in a class
1706 # in a class
1724 bdb.Breakpoint.next = 1
1707 bdb.Breakpoint.next = 1
1725 bdb.Breakpoint.bplist = {}
1708 bdb.Breakpoint.bplist = {}
1726 bdb.Breakpoint.bpbynumber = [None]
1709 bdb.Breakpoint.bpbynumber = [None]
1727 # Set an initial breakpoint to stop execution
1710 # Set an initial breakpoint to stop execution
1728 maxtries = 10
1711 maxtries = 10
1729 bp = int(opts.get('b',[1])[0])
1712 bp = int(opts.get('b',[1])[0])
1730 checkline = deb.checkline(filename,bp)
1713 checkline = deb.checkline(filename,bp)
1731 if not checkline:
1714 if not checkline:
1732 for bp in range(bp+1,bp+maxtries+1):
1715 for bp in range(bp+1,bp+maxtries+1):
1733 if deb.checkline(filename,bp):
1716 if deb.checkline(filename,bp):
1734 break
1717 break
1735 else:
1718 else:
1736 msg = ("\nI failed to find a valid line to set "
1719 msg = ("\nI failed to find a valid line to set "
1737 "a breakpoint\n"
1720 "a breakpoint\n"
1738 "after trying up to line: %s.\n"
1721 "after trying up to line: %s.\n"
1739 "Please set a valid breakpoint manually "
1722 "Please set a valid breakpoint manually "
1740 "with the -b option." % bp)
1723 "with the -b option." % bp)
1741 error(msg)
1724 error(msg)
1742 return
1725 return
1743 # if we find a good linenumber, set the breakpoint
1726 # if we find a good linenumber, set the breakpoint
1744 deb.do_break('%s:%s' % (filename,bp))
1727 deb.do_break('%s:%s' % (filename,bp))
1745 # Start file run
1728 # Start file run
1746 print "NOTE: Enter 'c' at the",
1729 print "NOTE: Enter 'c' at the",
1747 print "%s prompt to start your script." % deb.prompt
1730 print "%s prompt to start your script." % deb.prompt
1748 try:
1731 try:
1749 deb.run('execfile("%s")' % filename,prog_ns)
1732 deb.run('execfile("%s")' % filename,prog_ns)
1750
1733
1751 except:
1734 except:
1752 etype, value, tb = sys.exc_info()
1735 etype, value, tb = sys.exc_info()
1753 # Skip three frames in the traceback: the %run one,
1736 # Skip three frames in the traceback: the %run one,
1754 # one inside bdb.py, and the command-line typed by the
1737 # one inside bdb.py, and the command-line typed by the
1755 # user (run by exec in pdb itself).
1738 # user (run by exec in pdb itself).
1756 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1739 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1757 else:
1740 else:
1758 if runner is None:
1741 if runner is None:
1759 runner = self.shell.safe_execfile
1742 runner = self.shell.safe_execfile
1760 if opts.has_key('t'):
1743 if opts.has_key('t'):
1761 # timed execution
1744 # timed execution
1762 try:
1745 try:
1763 nruns = int(opts['N'][0])
1746 nruns = int(opts['N'][0])
1764 if nruns < 1:
1747 if nruns < 1:
1765 error('Number of runs must be >=1')
1748 error('Number of runs must be >=1')
1766 return
1749 return
1767 except (KeyError):
1750 except (KeyError):
1768 nruns = 1
1751 nruns = 1
1769 if nruns == 1:
1752 if nruns == 1:
1770 t0 = clock2()
1753 t0 = clock2()
1771 runner(filename,prog_ns,prog_ns,
1754 runner(filename,prog_ns,prog_ns,
1772 exit_ignore=exit_ignore)
1755 exit_ignore=exit_ignore)
1773 t1 = clock2()
1756 t1 = clock2()
1774 t_usr = t1[0]-t0[0]
1757 t_usr = t1[0]-t0[0]
1775 t_sys = t1[1]-t0[1]
1758 t_sys = t1[1]-t0[1]
1776 print "\nIPython CPU timings (estimated):"
1759 print "\nIPython CPU timings (estimated):"
1777 print " User : %10s s." % t_usr
1760 print " User : %10s s." % t_usr
1778 print " System: %10s s." % t_sys
1761 print " System: %10s s." % t_sys
1779 else:
1762 else:
1780 runs = range(nruns)
1763 runs = range(nruns)
1781 t0 = clock2()
1764 t0 = clock2()
1782 for nr in runs:
1765 for nr in runs:
1783 runner(filename,prog_ns,prog_ns,
1766 runner(filename,prog_ns,prog_ns,
1784 exit_ignore=exit_ignore)
1767 exit_ignore=exit_ignore)
1785 t1 = clock2()
1768 t1 = clock2()
1786 t_usr = t1[0]-t0[0]
1769 t_usr = t1[0]-t0[0]
1787 t_sys = t1[1]-t0[1]
1770 t_sys = t1[1]-t0[1]
1788 print "\nIPython CPU timings (estimated):"
1771 print "\nIPython CPU timings (estimated):"
1789 print "Total runs performed:",nruns
1772 print "Total runs performed:",nruns
1790 print " Times : %10s %10s" % ('Total','Per run')
1773 print " Times : %10s %10s" % ('Total','Per run')
1791 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1774 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1792 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1775 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1793
1776
1794 else:
1777 else:
1795 # regular execution
1778 # regular execution
1796 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1779 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1797
1780
1798 if opts.has_key('i'):
1781 if opts.has_key('i'):
1799 self.shell.user_ns['__name__'] = __name__save
1782 self.shell.user_ns['__name__'] = __name__save
1800 else:
1783 else:
1801 # The shell MUST hold a reference to prog_ns so after %run
1784 # The shell MUST hold a reference to prog_ns so after %run
1802 # exits, the python deletion mechanism doesn't zero it out
1785 # exits, the python deletion mechanism doesn't zero it out
1803 # (leaving dangling references).
1786 # (leaving dangling references).
1804 self.shell.cache_main_mod(prog_ns,filename)
1787 self.shell.cache_main_mod(prog_ns,filename)
1805 # update IPython interactive namespace
1788 # update IPython interactive namespace
1806
1789
1807 # Some forms of read errors on the file may mean the
1790 # Some forms of read errors on the file may mean the
1808 # __name__ key was never set; using pop we don't have to
1791 # __name__ key was never set; using pop we don't have to
1809 # worry about a possible KeyError.
1792 # worry about a possible KeyError.
1810 prog_ns.pop('__name__', None)
1793 prog_ns.pop('__name__', None)
1811
1794
1812 self.shell.user_ns.update(prog_ns)
1795 self.shell.user_ns.update(prog_ns)
1813 finally:
1796 finally:
1814 # It's a bit of a mystery why, but __builtins__ can change from
1797 # It's a bit of a mystery why, but __builtins__ can change from
1815 # being a module to becoming a dict missing some key data after
1798 # being a module to becoming a dict missing some key data after
1816 # %run. As best I can see, this is NOT something IPython is doing
1799 # %run. As best I can see, this is NOT something IPython is doing
1817 # at all, and similar problems have been reported before:
1800 # at all, and similar problems have been reported before:
1818 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1801 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1819 # Since this seems to be done by the interpreter itself, the best
1802 # Since this seems to be done by the interpreter itself, the best
1820 # we can do is to at least restore __builtins__ for the user on
1803 # we can do is to at least restore __builtins__ for the user on
1821 # exit.
1804 # exit.
1822 self.shell.user_ns['__builtins__'] = __builtin__
1805 self.shell.user_ns['__builtins__'] = __builtin__
1823
1806
1824 # Ensure key global structures are restored
1807 # Ensure key global structures are restored
1825 sys.argv = save_argv
1808 sys.argv = save_argv
1826 if restore_main:
1809 if restore_main:
1827 sys.modules['__main__'] = restore_main
1810 sys.modules['__main__'] = restore_main
1828 else:
1811 else:
1829 # Remove from sys.modules the reference to main_mod we'd
1812 # Remove from sys.modules the reference to main_mod we'd
1830 # added. Otherwise it will trap references to objects
1813 # added. Otherwise it will trap references to objects
1831 # contained therein.
1814 # contained therein.
1832 del sys.modules[main_mod_name]
1815 del sys.modules[main_mod_name]
1833
1816
1834 self.shell.reloadhist()
1817 self.shell.reloadhist()
1835
1818
1836 return stats
1819 return stats
1837
1820
1838 @testdec.skip_doctest
1821 @testdec.skip_doctest
1839 def magic_timeit(self, parameter_s =''):
1822 def magic_timeit(self, parameter_s =''):
1840 """Time execution of a Python statement or expression
1823 """Time execution of a Python statement or expression
1841
1824
1842 Usage:\\
1825 Usage:\\
1843 %timeit [-n<N> -r<R> [-t|-c]] statement
1826 %timeit [-n<N> -r<R> [-t|-c]] statement
1844
1827
1845 Time execution of a Python statement or expression using the timeit
1828 Time execution of a Python statement or expression using the timeit
1846 module.
1829 module.
1847
1830
1848 Options:
1831 Options:
1849 -n<N>: execute the given statement <N> times in a loop. If this value
1832 -n<N>: execute the given statement <N> times in a loop. If this value
1850 is not given, a fitting value is chosen.
1833 is not given, a fitting value is chosen.
1851
1834
1852 -r<R>: repeat the loop iteration <R> times and take the best result.
1835 -r<R>: repeat the loop iteration <R> times and take the best result.
1853 Default: 3
1836 Default: 3
1854
1837
1855 -t: use time.time to measure the time, which is the default on Unix.
1838 -t: use time.time to measure the time, which is the default on Unix.
1856 This function measures wall time.
1839 This function measures wall time.
1857
1840
1858 -c: use time.clock to measure the time, which is the default on
1841 -c: use time.clock to measure the time, which is the default on
1859 Windows and measures wall time. On Unix, resource.getrusage is used
1842 Windows and measures wall time. On Unix, resource.getrusage is used
1860 instead and returns the CPU user time.
1843 instead and returns the CPU user time.
1861
1844
1862 -p<P>: use a precision of <P> digits to display the timing result.
1845 -p<P>: use a precision of <P> digits to display the timing result.
1863 Default: 3
1846 Default: 3
1864
1847
1865
1848
1866 Examples:
1849 Examples:
1867
1850
1868 In [1]: %timeit pass
1851 In [1]: %timeit pass
1869 10000000 loops, best of 3: 53.3 ns per loop
1852 10000000 loops, best of 3: 53.3 ns per loop
1870
1853
1871 In [2]: u = None
1854 In [2]: u = None
1872
1855
1873 In [3]: %timeit u is None
1856 In [3]: %timeit u is None
1874 10000000 loops, best of 3: 184 ns per loop
1857 10000000 loops, best of 3: 184 ns per loop
1875
1858
1876 In [4]: %timeit -r 4 u == None
1859 In [4]: %timeit -r 4 u == None
1877 1000000 loops, best of 4: 242 ns per loop
1860 1000000 loops, best of 4: 242 ns per loop
1878
1861
1879 In [5]: import time
1862 In [5]: import time
1880
1863
1881 In [6]: %timeit -n1 time.sleep(2)
1864 In [6]: %timeit -n1 time.sleep(2)
1882 1 loops, best of 3: 2 s per loop
1865 1 loops, best of 3: 2 s per loop
1883
1866
1884
1867
1885 The times reported by %timeit will be slightly higher than those
1868 The times reported by %timeit will be slightly higher than those
1886 reported by the timeit.py script when variables are accessed. This is
1869 reported by the timeit.py script when variables are accessed. This is
1887 due to the fact that %timeit executes the statement in the namespace
1870 due to the fact that %timeit executes the statement in the namespace
1888 of the shell, compared with timeit.py, which uses a single setup
1871 of the shell, compared with timeit.py, which uses a single setup
1889 statement to import function or create variables. Generally, the bias
1872 statement to import function or create variables. Generally, the bias
1890 does not matter as long as results from timeit.py are not mixed with
1873 does not matter as long as results from timeit.py are not mixed with
1891 those from %timeit."""
1874 those from %timeit."""
1892
1875
1893 import timeit
1876 import timeit
1894 import math
1877 import math
1895
1878
1896 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1879 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1897 # certain terminals. Until we figure out a robust way of
1880 # certain terminals. Until we figure out a robust way of
1898 # auto-detecting if the terminal can deal with it, use plain 'us' for
1881 # auto-detecting if the terminal can deal with it, use plain 'us' for
1899 # microseconds. I am really NOT happy about disabling the proper
1882 # microseconds. I am really NOT happy about disabling the proper
1900 # 'micro' prefix, but crashing is worse... If anyone knows what the
1883 # 'micro' prefix, but crashing is worse... If anyone knows what the
1901 # right solution for this is, I'm all ears...
1884 # right solution for this is, I'm all ears...
1902 #
1885 #
1903 # Note: using
1886 # Note: using
1904 #
1887 #
1905 # s = u'\xb5'
1888 # s = u'\xb5'
1906 # s.encode(sys.getdefaultencoding())
1889 # s.encode(sys.getdefaultencoding())
1907 #
1890 #
1908 # is not sufficient, as I've seen terminals where that fails but
1891 # is not sufficient, as I've seen terminals where that fails but
1909 # print s
1892 # print s
1910 #
1893 #
1911 # succeeds
1894 # succeeds
1912 #
1895 #
1913 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1896 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1914
1897
1915 #units = [u"s", u"ms",u'\xb5',"ns"]
1898 #units = [u"s", u"ms",u'\xb5',"ns"]
1916 units = [u"s", u"ms",u'us',"ns"]
1899 units = [u"s", u"ms",u'us',"ns"]
1917
1900
1918 scaling = [1, 1e3, 1e6, 1e9]
1901 scaling = [1, 1e3, 1e6, 1e9]
1919
1902
1920 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1903 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1921 posix=False)
1904 posix=False)
1922 if stmt == "":
1905 if stmt == "":
1923 return
1906 return
1924 timefunc = timeit.default_timer
1907 timefunc = timeit.default_timer
1925 number = int(getattr(opts, "n", 0))
1908 number = int(getattr(opts, "n", 0))
1926 repeat = int(getattr(opts, "r", timeit.default_repeat))
1909 repeat = int(getattr(opts, "r", timeit.default_repeat))
1927 precision = int(getattr(opts, "p", 3))
1910 precision = int(getattr(opts, "p", 3))
1928 if hasattr(opts, "t"):
1911 if hasattr(opts, "t"):
1929 timefunc = time.time
1912 timefunc = time.time
1930 if hasattr(opts, "c"):
1913 if hasattr(opts, "c"):
1931 timefunc = clock
1914 timefunc = clock
1932
1915
1933 timer = timeit.Timer(timer=timefunc)
1916 timer = timeit.Timer(timer=timefunc)
1934 # this code has tight coupling to the inner workings of timeit.Timer,
1917 # this code has tight coupling to the inner workings of timeit.Timer,
1935 # but is there a better way to achieve that the code stmt has access
1918 # but is there a better way to achieve that the code stmt has access
1936 # to the shell namespace?
1919 # to the shell namespace?
1937
1920
1938 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1921 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1939 'setup': "pass"}
1922 'setup': "pass"}
1940 # Track compilation time so it can be reported if too long
1923 # Track compilation time so it can be reported if too long
1941 # Minimum time above which compilation time will be reported
1924 # Minimum time above which compilation time will be reported
1942 tc_min = 0.1
1925 tc_min = 0.1
1943
1926
1944 t0 = clock()
1927 t0 = clock()
1945 code = compile(src, "<magic-timeit>", "exec")
1928 code = compile(src, "<magic-timeit>", "exec")
1946 tc = clock()-t0
1929 tc = clock()-t0
1947
1930
1948 ns = {}
1931 ns = {}
1949 exec code in self.shell.user_ns, ns
1932 exec code in self.shell.user_ns, ns
1950 timer.inner = ns["inner"]
1933 timer.inner = ns["inner"]
1951
1934
1952 if number == 0:
1935 if number == 0:
1953 # determine number so that 0.2 <= total time < 2.0
1936 # determine number so that 0.2 <= total time < 2.0
1954 number = 1
1937 number = 1
1955 for i in range(1, 10):
1938 for i in range(1, 10):
1956 if timer.timeit(number) >= 0.2:
1939 if timer.timeit(number) >= 0.2:
1957 break
1940 break
1958 number *= 10
1941 number *= 10
1959
1942
1960 best = min(timer.repeat(repeat, number)) / number
1943 best = min(timer.repeat(repeat, number)) / number
1961
1944
1962 if best > 0.0 and best < 1000.0:
1945 if best > 0.0 and best < 1000.0:
1963 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1946 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1964 elif best >= 1000.0:
1947 elif best >= 1000.0:
1965 order = 0
1948 order = 0
1966 else:
1949 else:
1967 order = 3
1950 order = 3
1968 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1951 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1969 precision,
1952 precision,
1970 best * scaling[order],
1953 best * scaling[order],
1971 units[order])
1954 units[order])
1972 if tc > tc_min:
1955 if tc > tc_min:
1973 print "Compiler time: %.2f s" % tc
1956 print "Compiler time: %.2f s" % tc
1974
1957
1975 @testdec.skip_doctest
1958 @testdec.skip_doctest
1976 def magic_time(self,parameter_s = ''):
1959 def magic_time(self,parameter_s = ''):
1977 """Time execution of a Python statement or expression.
1960 """Time execution of a Python statement or expression.
1978
1961
1979 The CPU and wall clock times are printed, and the value of the
1962 The CPU and wall clock times are printed, and the value of the
1980 expression (if any) is returned. Note that under Win32, system time
1963 expression (if any) is returned. Note that under Win32, system time
1981 is always reported as 0, since it can not be measured.
1964 is always reported as 0, since it can not be measured.
1982
1965
1983 This function provides very basic timing functionality. In Python
1966 This function provides very basic timing functionality. In Python
1984 2.3, the timeit module offers more control and sophistication, so this
1967 2.3, the timeit module offers more control and sophistication, so this
1985 could be rewritten to use it (patches welcome).
1968 could be rewritten to use it (patches welcome).
1986
1969
1987 Some examples:
1970 Some examples:
1988
1971
1989 In [1]: time 2**128
1972 In [1]: time 2**128
1990 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1973 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1991 Wall time: 0.00
1974 Wall time: 0.00
1992 Out[1]: 340282366920938463463374607431768211456L
1975 Out[1]: 340282366920938463463374607431768211456L
1993
1976
1994 In [2]: n = 1000000
1977 In [2]: n = 1000000
1995
1978
1996 In [3]: time sum(range(n))
1979 In [3]: time sum(range(n))
1997 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1980 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1998 Wall time: 1.37
1981 Wall time: 1.37
1999 Out[3]: 499999500000L
1982 Out[3]: 499999500000L
2000
1983
2001 In [4]: time print 'hello world'
1984 In [4]: time print 'hello world'
2002 hello world
1985 hello world
2003 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1986 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2004 Wall time: 0.00
1987 Wall time: 0.00
2005
1988
2006 Note that the time needed by Python to compile the given expression
1989 Note that the time needed by Python to compile the given expression
2007 will be reported if it is more than 0.1s. In this example, the
1990 will be reported if it is more than 0.1s. In this example, the
2008 actual exponentiation is done by Python at compilation time, so while
1991 actual exponentiation is done by Python at compilation time, so while
2009 the expression can take a noticeable amount of time to compute, that
1992 the expression can take a noticeable amount of time to compute, that
2010 time is purely due to the compilation:
1993 time is purely due to the compilation:
2011
1994
2012 In [5]: time 3**9999;
1995 In [5]: time 3**9999;
2013 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1996 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2014 Wall time: 0.00 s
1997 Wall time: 0.00 s
2015
1998
2016 In [6]: time 3**999999;
1999 In [6]: time 3**999999;
2017 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2000 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2018 Wall time: 0.00 s
2001 Wall time: 0.00 s
2019 Compiler : 0.78 s
2002 Compiler : 0.78 s
2020 """
2003 """
2021
2004
2022 # fail immediately if the given expression can't be compiled
2005 # fail immediately if the given expression can't be compiled
2023
2006
2024 expr = self.shell.prefilter(parameter_s,False)
2007 expr = self.shell.prefilter(parameter_s,False)
2025
2008
2026 # Minimum time above which compilation time will be reported
2009 # Minimum time above which compilation time will be reported
2027 tc_min = 0.1
2010 tc_min = 0.1
2028
2011
2029 try:
2012 try:
2030 mode = 'eval'
2013 mode = 'eval'
2031 t0 = clock()
2014 t0 = clock()
2032 code = compile(expr,'<timed eval>',mode)
2015 code = compile(expr,'<timed eval>',mode)
2033 tc = clock()-t0
2016 tc = clock()-t0
2034 except SyntaxError:
2017 except SyntaxError:
2035 mode = 'exec'
2018 mode = 'exec'
2036 t0 = clock()
2019 t0 = clock()
2037 code = compile(expr,'<timed exec>',mode)
2020 code = compile(expr,'<timed exec>',mode)
2038 tc = clock()-t0
2021 tc = clock()-t0
2039 # skew measurement as little as possible
2022 # skew measurement as little as possible
2040 glob = self.shell.user_ns
2023 glob = self.shell.user_ns
2041 clk = clock2
2024 clk = clock2
2042 wtime = time.time
2025 wtime = time.time
2043 # time execution
2026 # time execution
2044 wall_st = wtime()
2027 wall_st = wtime()
2045 if mode=='eval':
2028 if mode=='eval':
2046 st = clk()
2029 st = clk()
2047 out = eval(code,glob)
2030 out = eval(code,glob)
2048 end = clk()
2031 end = clk()
2049 else:
2032 else:
2050 st = clk()
2033 st = clk()
2051 exec code in glob
2034 exec code in glob
2052 end = clk()
2035 end = clk()
2053 out = None
2036 out = None
2054 wall_end = wtime()
2037 wall_end = wtime()
2055 # Compute actual times and report
2038 # Compute actual times and report
2056 wall_time = wall_end-wall_st
2039 wall_time = wall_end-wall_st
2057 cpu_user = end[0]-st[0]
2040 cpu_user = end[0]-st[0]
2058 cpu_sys = end[1]-st[1]
2041 cpu_sys = end[1]-st[1]
2059 cpu_tot = cpu_user+cpu_sys
2042 cpu_tot = cpu_user+cpu_sys
2060 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2043 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2061 (cpu_user,cpu_sys,cpu_tot)
2044 (cpu_user,cpu_sys,cpu_tot)
2062 print "Wall time: %.2f s" % wall_time
2045 print "Wall time: %.2f s" % wall_time
2063 if tc > tc_min:
2046 if tc > tc_min:
2064 print "Compiler : %.2f s" % tc
2047 print "Compiler : %.2f s" % tc
2065 return out
2048 return out
2066
2049
2067 @testdec.skip_doctest
2050 @testdec.skip_doctest
2068 def magic_macro(self,parameter_s = ''):
2051 def magic_macro(self,parameter_s = ''):
2069 """Define a set of input lines as a macro for future re-execution.
2052 """Define a set of input lines as a macro for future re-execution.
2070
2053
2071 Usage:\\
2054 Usage:\\
2072 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2055 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2073
2056
2074 Options:
2057 Options:
2075
2058
2076 -r: use 'raw' input. By default, the 'processed' history is used,
2059 -r: use 'raw' input. By default, the 'processed' history is used,
2077 so that magics are loaded in their transformed version to valid
2060 so that magics are loaded in their transformed version to valid
2078 Python. If this option is given, the raw input as typed as the
2061 Python. If this option is given, the raw input as typed as the
2079 command line is used instead.
2062 command line is used instead.
2080
2063
2081 This will define a global variable called `name` which is a string
2064 This will define a global variable called `name` which is a string
2082 made of joining the slices and lines you specify (n1,n2,... numbers
2065 made of joining the slices and lines you specify (n1,n2,... numbers
2083 above) from your input history into a single string. This variable
2066 above) from your input history into a single string. This variable
2084 acts like an automatic function which re-executes those lines as if
2067 acts like an automatic function which re-executes those lines as if
2085 you had typed them. You just type 'name' at the prompt and the code
2068 you had typed them. You just type 'name' at the prompt and the code
2086 executes.
2069 executes.
2087
2070
2088 The notation for indicating number ranges is: n1-n2 means 'use line
2071 The notation for indicating number ranges is: n1-n2 means 'use line
2089 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2072 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2090 using the lines numbered 5,6 and 7.
2073 using the lines numbered 5,6 and 7.
2091
2074
2092 Note: as a 'hidden' feature, you can also use traditional python slice
2075 Note: as a 'hidden' feature, you can also use traditional python slice
2093 notation, where N:M means numbers N through M-1.
2076 notation, where N:M means numbers N through M-1.
2094
2077
2095 For example, if your history contains (%hist prints it):
2078 For example, if your history contains (%hist prints it):
2096
2079
2097 44: x=1
2080 44: x=1
2098 45: y=3
2081 45: y=3
2099 46: z=x+y
2082 46: z=x+y
2100 47: print x
2083 47: print x
2101 48: a=5
2084 48: a=5
2102 49: print 'x',x,'y',y
2085 49: print 'x',x,'y',y
2103
2086
2104 you can create a macro with lines 44 through 47 (included) and line 49
2087 you can create a macro with lines 44 through 47 (included) and line 49
2105 called my_macro with:
2088 called my_macro with:
2106
2089
2107 In [55]: %macro my_macro 44-47 49
2090 In [55]: %macro my_macro 44-47 49
2108
2091
2109 Now, typing `my_macro` (without quotes) will re-execute all this code
2092 Now, typing `my_macro` (without quotes) will re-execute all this code
2110 in one pass.
2093 in one pass.
2111
2094
2112 You don't need to give the line-numbers in order, and any given line
2095 You don't need to give the line-numbers in order, and any given line
2113 number can appear multiple times. You can assemble macros with any
2096 number can appear multiple times. You can assemble macros with any
2114 lines from your input history in any order.
2097 lines from your input history in any order.
2115
2098
2116 The macro is a simple object which holds its value in an attribute,
2099 The macro is a simple object which holds its value in an attribute,
2117 but IPython's display system checks for macros and executes them as
2100 but IPython's display system checks for macros and executes them as
2118 code instead of printing them when you type their name.
2101 code instead of printing them when you type their name.
2119
2102
2120 You can view a macro's contents by explicitly printing it with:
2103 You can view a macro's contents by explicitly printing it with:
2121
2104
2122 'print macro_name'.
2105 'print macro_name'.
2123
2106
2124 For one-off cases which DON'T contain magic function calls in them you
2107 For one-off cases which DON'T contain magic function calls in them you
2125 can obtain similar results by explicitly executing slices from your
2108 can obtain similar results by explicitly executing slices from your
2126 input history with:
2109 input history with:
2127
2110
2128 In [60]: exec In[44:48]+In[49]"""
2111 In [60]: exec In[44:48]+In[49]"""
2129
2112
2130 opts,args = self.parse_options(parameter_s,'r',mode='list')
2113 opts,args = self.parse_options(parameter_s,'r',mode='list')
2131 if not args:
2114 if not args:
2132 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2115 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2133 macs.sort()
2116 macs.sort()
2134 return macs
2117 return macs
2135 if len(args) == 1:
2118 if len(args) == 1:
2136 raise UsageError(
2119 raise UsageError(
2137 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2120 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2138 name,ranges = args[0], args[1:]
2121 name,ranges = args[0], args[1:]
2139
2122
2140 #print 'rng',ranges # dbg
2123 #print 'rng',ranges # dbg
2141 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2124 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2142 macro = Macro(lines)
2125 macro = Macro(lines)
2143 self.shell.define_macro(name, macro)
2126 self.shell.define_macro(name, macro)
2144 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2127 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2145 print 'Macro contents:'
2128 print 'Macro contents:'
2146 print macro,
2129 print macro,
2147
2130
2148 def magic_save(self,parameter_s = ''):
2131 def magic_save(self,parameter_s = ''):
2149 """Save a set of lines to a given filename.
2132 """Save a set of lines to a given filename.
2150
2133
2151 Usage:\\
2134 Usage:\\
2152 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2135 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2153
2136
2154 Options:
2137 Options:
2155
2138
2156 -r: use 'raw' input. By default, the 'processed' history is used,
2139 -r: use 'raw' input. By default, the 'processed' history is used,
2157 so that magics are loaded in their transformed version to valid
2140 so that magics are loaded in their transformed version to valid
2158 Python. If this option is given, the raw input as typed as the
2141 Python. If this option is given, the raw input as typed as the
2159 command line is used instead.
2142 command line is used instead.
2160
2143
2161 This function uses the same syntax as %macro for line extraction, but
2144 This function uses the same syntax as %macro for line extraction, but
2162 instead of creating a macro it saves the resulting string to the
2145 instead of creating a macro it saves the resulting string to the
2163 filename you specify.
2146 filename you specify.
2164
2147
2165 It adds a '.py' extension to the file if you don't do so yourself, and
2148 It adds a '.py' extension to the file if you don't do so yourself, and
2166 it asks for confirmation before overwriting existing files."""
2149 it asks for confirmation before overwriting existing files."""
2167
2150
2168 opts,args = self.parse_options(parameter_s,'r',mode='list')
2151 opts,args = self.parse_options(parameter_s,'r',mode='list')
2169 fname,ranges = args[0], args[1:]
2152 fname,ranges = args[0], args[1:]
2170 if not fname.endswith('.py'):
2153 if not fname.endswith('.py'):
2171 fname += '.py'
2154 fname += '.py'
2172 if os.path.isfile(fname):
2155 if os.path.isfile(fname):
2173 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2156 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2174 if ans.lower() not in ['y','yes']:
2157 if ans.lower() not in ['y','yes']:
2175 print 'Operation cancelled.'
2158 print 'Operation cancelled.'
2176 return
2159 return
2177 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2160 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2178 f = file(fname,'w')
2161 f = file(fname,'w')
2179 f.write(cmds)
2162 f.write(cmds)
2180 f.close()
2163 f.close()
2181 print 'The following commands were written to file `%s`:' % fname
2164 print 'The following commands were written to file `%s`:' % fname
2182 print cmds
2165 print cmds
2183
2166
2184 def _edit_macro(self,mname,macro):
2167 def _edit_macro(self,mname,macro):
2185 """open an editor with the macro data in a file"""
2168 """open an editor with the macro data in a file"""
2186 filename = self.shell.mktempfile(macro.value)
2169 filename = self.shell.mktempfile(macro.value)
2187 self.shell.hooks.editor(filename)
2170 self.shell.hooks.editor(filename)
2188
2171
2189 # and make a new macro object, to replace the old one
2172 # and make a new macro object, to replace the old one
2190 mfile = open(filename)
2173 mfile = open(filename)
2191 mvalue = mfile.read()
2174 mvalue = mfile.read()
2192 mfile.close()
2175 mfile.close()
2193 self.shell.user_ns[mname] = Macro(mvalue)
2176 self.shell.user_ns[mname] = Macro(mvalue)
2194
2177
2195 def magic_ed(self,parameter_s=''):
2178 def magic_ed(self,parameter_s=''):
2196 """Alias to %edit."""
2179 """Alias to %edit."""
2197 return self.magic_edit(parameter_s)
2180 return self.magic_edit(parameter_s)
2198
2181
2199 @testdec.skip_doctest
2182 @testdec.skip_doctest
2200 def magic_edit(self,parameter_s='',last_call=['','']):
2183 def magic_edit(self,parameter_s='',last_call=['','']):
2201 """Bring up an editor and execute the resulting code.
2184 """Bring up an editor and execute the resulting code.
2202
2185
2203 Usage:
2186 Usage:
2204 %edit [options] [args]
2187 %edit [options] [args]
2205
2188
2206 %edit runs IPython's editor hook. The default version of this hook is
2189 %edit runs IPython's editor hook. The default version of this hook is
2207 set to call the __IPYTHON__.rc.editor command. This is read from your
2190 set to call the __IPYTHON__.rc.editor command. This is read from your
2208 environment variable $EDITOR. If this isn't found, it will default to
2191 environment variable $EDITOR. If this isn't found, it will default to
2209 vi under Linux/Unix and to notepad under Windows. See the end of this
2192 vi under Linux/Unix and to notepad under Windows. See the end of this
2210 docstring for how to change the editor hook.
2193 docstring for how to change the editor hook.
2211
2194
2212 You can also set the value of this editor via the command line option
2195 You can also set the value of this editor via the command line option
2213 '-editor' or in your ipythonrc file. This is useful if you wish to use
2196 '-editor' or in your ipythonrc file. This is useful if you wish to use
2214 specifically for IPython an editor different from your typical default
2197 specifically for IPython an editor different from your typical default
2215 (and for Windows users who typically don't set environment variables).
2198 (and for Windows users who typically don't set environment variables).
2216
2199
2217 This command allows you to conveniently edit multi-line code right in
2200 This command allows you to conveniently edit multi-line code right in
2218 your IPython session.
2201 your IPython session.
2219
2202
2220 If called without arguments, %edit opens up an empty editor with a
2203 If called without arguments, %edit opens up an empty editor with a
2221 temporary file and will execute the contents of this file when you
2204 temporary file and will execute the contents of this file when you
2222 close it (don't forget to save it!).
2205 close it (don't forget to save it!).
2223
2206
2224
2207
2225 Options:
2208 Options:
2226
2209
2227 -n <number>: open the editor at a specified line number. By default,
2210 -n <number>: open the editor at a specified line number. By default,
2228 the IPython editor hook uses the unix syntax 'editor +N filename', but
2211 the IPython editor hook uses the unix syntax 'editor +N filename', but
2229 you can configure this by providing your own modified hook if your
2212 you can configure this by providing your own modified hook if your
2230 favorite editor supports line-number specifications with a different
2213 favorite editor supports line-number specifications with a different
2231 syntax.
2214 syntax.
2232
2215
2233 -p: this will call the editor with the same data as the previous time
2216 -p: this will call the editor with the same data as the previous time
2234 it was used, regardless of how long ago (in your current session) it
2217 it was used, regardless of how long ago (in your current session) it
2235 was.
2218 was.
2236
2219
2237 -r: use 'raw' input. This option only applies to input taken from the
2220 -r: use 'raw' input. This option only applies to input taken from the
2238 user's history. By default, the 'processed' history is used, so that
2221 user's history. By default, the 'processed' history is used, so that
2239 magics are loaded in their transformed version to valid Python. If
2222 magics are loaded in their transformed version to valid Python. If
2240 this option is given, the raw input as typed as the command line is
2223 this option is given, the raw input as typed as the command line is
2241 used instead. When you exit the editor, it will be executed by
2224 used instead. When you exit the editor, it will be executed by
2242 IPython's own processor.
2225 IPython's own processor.
2243
2226
2244 -x: do not execute the edited code immediately upon exit. This is
2227 -x: do not execute the edited code immediately upon exit. This is
2245 mainly useful if you are editing programs which need to be called with
2228 mainly useful if you are editing programs which need to be called with
2246 command line arguments, which you can then do using %run.
2229 command line arguments, which you can then do using %run.
2247
2230
2248
2231
2249 Arguments:
2232 Arguments:
2250
2233
2251 If arguments are given, the following possibilites exist:
2234 If arguments are given, the following possibilites exist:
2252
2235
2253 - The arguments are numbers or pairs of colon-separated numbers (like
2236 - The arguments are numbers or pairs of colon-separated numbers (like
2254 1 4:8 9). These are interpreted as lines of previous input to be
2237 1 4:8 9). These are interpreted as lines of previous input to be
2255 loaded into the editor. The syntax is the same of the %macro command.
2238 loaded into the editor. The syntax is the same of the %macro command.
2256
2239
2257 - If the argument doesn't start with a number, it is evaluated as a
2240 - If the argument doesn't start with a number, it is evaluated as a
2258 variable and its contents loaded into the editor. You can thus edit
2241 variable and its contents loaded into the editor. You can thus edit
2259 any string which contains python code (including the result of
2242 any string which contains python code (including the result of
2260 previous edits).
2243 previous edits).
2261
2244
2262 - If the argument is the name of an object (other than a string),
2245 - If the argument is the name of an object (other than a string),
2263 IPython will try to locate the file where it was defined and open the
2246 IPython will try to locate the file where it was defined and open the
2264 editor at the point where it is defined. You can use `%edit function`
2247 editor at the point where it is defined. You can use `%edit function`
2265 to load an editor exactly at the point where 'function' is defined,
2248 to load an editor exactly at the point where 'function' is defined,
2266 edit it and have the file be executed automatically.
2249 edit it and have the file be executed automatically.
2267
2250
2268 If the object is a macro (see %macro for details), this opens up your
2251 If the object is a macro (see %macro for details), this opens up your
2269 specified editor with a temporary file containing the macro's data.
2252 specified editor with a temporary file containing the macro's data.
2270 Upon exit, the macro is reloaded with the contents of the file.
2253 Upon exit, the macro is reloaded with the contents of the file.
2271
2254
2272 Note: opening at an exact line is only supported under Unix, and some
2255 Note: opening at an exact line is only supported under Unix, and some
2273 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2256 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2274 '+NUMBER' parameter necessary for this feature. Good editors like
2257 '+NUMBER' parameter necessary for this feature. Good editors like
2275 (X)Emacs, vi, jed, pico and joe all do.
2258 (X)Emacs, vi, jed, pico and joe all do.
2276
2259
2277 - If the argument is not found as a variable, IPython will look for a
2260 - If the argument is not found as a variable, IPython will look for a
2278 file with that name (adding .py if necessary) and load it into the
2261 file with that name (adding .py if necessary) and load it into the
2279 editor. It will execute its contents with execfile() when you exit,
2262 editor. It will execute its contents with execfile() when you exit,
2280 loading any code in the file into your interactive namespace.
2263 loading any code in the file into your interactive namespace.
2281
2264
2282 After executing your code, %edit will return as output the code you
2265 After executing your code, %edit will return as output the code you
2283 typed in the editor (except when it was an existing file). This way
2266 typed in the editor (except when it was an existing file). This way
2284 you can reload the code in further invocations of %edit as a variable,
2267 you can reload the code in further invocations of %edit as a variable,
2285 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2268 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2286 the output.
2269 the output.
2287
2270
2288 Note that %edit is also available through the alias %ed.
2271 Note that %edit is also available through the alias %ed.
2289
2272
2290 This is an example of creating a simple function inside the editor and
2273 This is an example of creating a simple function inside the editor and
2291 then modifying it. First, start up the editor:
2274 then modifying it. First, start up the editor:
2292
2275
2293 In [1]: ed
2276 In [1]: ed
2294 Editing... done. Executing edited code...
2277 Editing... done. Executing edited code...
2295 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2278 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2296
2279
2297 We can then call the function foo():
2280 We can then call the function foo():
2298
2281
2299 In [2]: foo()
2282 In [2]: foo()
2300 foo() was defined in an editing session
2283 foo() was defined in an editing session
2301
2284
2302 Now we edit foo. IPython automatically loads the editor with the
2285 Now we edit foo. IPython automatically loads the editor with the
2303 (temporary) file where foo() was previously defined:
2286 (temporary) file where foo() was previously defined:
2304
2287
2305 In [3]: ed foo
2288 In [3]: ed foo
2306 Editing... done. Executing edited code...
2289 Editing... done. Executing edited code...
2307
2290
2308 And if we call foo() again we get the modified version:
2291 And if we call foo() again we get the modified version:
2309
2292
2310 In [4]: foo()
2293 In [4]: foo()
2311 foo() has now been changed!
2294 foo() has now been changed!
2312
2295
2313 Here is an example of how to edit a code snippet successive
2296 Here is an example of how to edit a code snippet successive
2314 times. First we call the editor:
2297 times. First we call the editor:
2315
2298
2316 In [5]: ed
2299 In [5]: ed
2317 Editing... done. Executing edited code...
2300 Editing... done. Executing edited code...
2318 hello
2301 hello
2319 Out[5]: "print 'hello'n"
2302 Out[5]: "print 'hello'n"
2320
2303
2321 Now we call it again with the previous output (stored in _):
2304 Now we call it again with the previous output (stored in _):
2322
2305
2323 In [6]: ed _
2306 In [6]: ed _
2324 Editing... done. Executing edited code...
2307 Editing... done. Executing edited code...
2325 hello world
2308 hello world
2326 Out[6]: "print 'hello world'n"
2309 Out[6]: "print 'hello world'n"
2327
2310
2328 Now we call it with the output #8 (stored in _8, also as Out[8]):
2311 Now we call it with the output #8 (stored in _8, also as Out[8]):
2329
2312
2330 In [7]: ed _8
2313 In [7]: ed _8
2331 Editing... done. Executing edited code...
2314 Editing... done. Executing edited code...
2332 hello again
2315 hello again
2333 Out[7]: "print 'hello again'n"
2316 Out[7]: "print 'hello again'n"
2334
2317
2335
2318
2336 Changing the default editor hook:
2319 Changing the default editor hook:
2337
2320
2338 If you wish to write your own editor hook, you can put it in a
2321 If you wish to write your own editor hook, you can put it in a
2339 configuration file which you load at startup time. The default hook
2322 configuration file which you load at startup time. The default hook
2340 is defined in the IPython.core.hooks module, and you can use that as a
2323 is defined in the IPython.core.hooks module, and you can use that as a
2341 starting example for further modifications. That file also has
2324 starting example for further modifications. That file also has
2342 general instructions on how to set a new hook for use once you've
2325 general instructions on how to set a new hook for use once you've
2343 defined it."""
2326 defined it."""
2344
2327
2345 # FIXME: This function has become a convoluted mess. It needs a
2328 # FIXME: This function has become a convoluted mess. It needs a
2346 # ground-up rewrite with clean, simple logic.
2329 # ground-up rewrite with clean, simple logic.
2347
2330
2348 def make_filename(arg):
2331 def make_filename(arg):
2349 "Make a filename from the given args"
2332 "Make a filename from the given args"
2350 try:
2333 try:
2351 filename = get_py_filename(arg)
2334 filename = get_py_filename(arg)
2352 except IOError:
2335 except IOError:
2353 if args.endswith('.py'):
2336 if args.endswith('.py'):
2354 filename = arg
2337 filename = arg
2355 else:
2338 else:
2356 filename = None
2339 filename = None
2357 return filename
2340 return filename
2358
2341
2359 # custom exceptions
2342 # custom exceptions
2360 class DataIsObject(Exception): pass
2343 class DataIsObject(Exception): pass
2361
2344
2362 opts,args = self.parse_options(parameter_s,'prxn:')
2345 opts,args = self.parse_options(parameter_s,'prxn:')
2363 # Set a few locals from the options for convenience:
2346 # Set a few locals from the options for convenience:
2364 opts_p = opts.has_key('p')
2347 opts_p = opts.has_key('p')
2365 opts_r = opts.has_key('r')
2348 opts_r = opts.has_key('r')
2366
2349
2367 # Default line number value
2350 # Default line number value
2368 lineno = opts.get('n',None)
2351 lineno = opts.get('n',None)
2369
2352
2370 if opts_p:
2353 if opts_p:
2371 args = '_%s' % last_call[0]
2354 args = '_%s' % last_call[0]
2372 if not self.shell.user_ns.has_key(args):
2355 if not self.shell.user_ns.has_key(args):
2373 args = last_call[1]
2356 args = last_call[1]
2374
2357
2375 # use last_call to remember the state of the previous call, but don't
2358 # use last_call to remember the state of the previous call, but don't
2376 # let it be clobbered by successive '-p' calls.
2359 # let it be clobbered by successive '-p' calls.
2377 try:
2360 try:
2378 last_call[0] = self.shell.displayhook.prompt_count
2361 last_call[0] = self.shell.displayhook.prompt_count
2379 if not opts_p:
2362 if not opts_p:
2380 last_call[1] = parameter_s
2363 last_call[1] = parameter_s
2381 except:
2364 except:
2382 pass
2365 pass
2383
2366
2384 # by default this is done with temp files, except when the given
2367 # by default this is done with temp files, except when the given
2385 # arg is a filename
2368 # arg is a filename
2386 use_temp = 1
2369 use_temp = 1
2387
2370
2388 if re.match(r'\d',args):
2371 if re.match(r'\d',args):
2389 # Mode where user specifies ranges of lines, like in %macro.
2372 # Mode where user specifies ranges of lines, like in %macro.
2390 # This means that you can't edit files whose names begin with
2373 # This means that you can't edit files whose names begin with
2391 # numbers this way. Tough.
2374 # numbers this way. Tough.
2392 ranges = args.split()
2375 ranges = args.split()
2393 data = ''.join(self.extract_input_slices(ranges,opts_r))
2376 data = ''.join(self.extract_input_slices(ranges,opts_r))
2394 elif args.endswith('.py'):
2377 elif args.endswith('.py'):
2395 filename = make_filename(args)
2378 filename = make_filename(args)
2396 data = ''
2379 data = ''
2397 use_temp = 0
2380 use_temp = 0
2398 elif args:
2381 elif args:
2399 try:
2382 try:
2400 # Load the parameter given as a variable. If not a string,
2383 # Load the parameter given as a variable. If not a string,
2401 # process it as an object instead (below)
2384 # process it as an object instead (below)
2402
2385
2403 #print '*** args',args,'type',type(args) # dbg
2386 #print '*** args',args,'type',type(args) # dbg
2404 data = eval(args,self.shell.user_ns)
2387 data = eval(args,self.shell.user_ns)
2405 if not type(data) in StringTypes:
2388 if not type(data) in StringTypes:
2406 raise DataIsObject
2389 raise DataIsObject
2407
2390
2408 except (NameError,SyntaxError):
2391 except (NameError,SyntaxError):
2409 # given argument is not a variable, try as a filename
2392 # given argument is not a variable, try as a filename
2410 filename = make_filename(args)
2393 filename = make_filename(args)
2411 if filename is None:
2394 if filename is None:
2412 warn("Argument given (%s) can't be found as a variable "
2395 warn("Argument given (%s) can't be found as a variable "
2413 "or as a filename." % args)
2396 "or as a filename." % args)
2414 return
2397 return
2415
2398
2416 data = ''
2399 data = ''
2417 use_temp = 0
2400 use_temp = 0
2418 except DataIsObject:
2401 except DataIsObject:
2419
2402
2420 # macros have a special edit function
2403 # macros have a special edit function
2421 if isinstance(data,Macro):
2404 if isinstance(data,Macro):
2422 self._edit_macro(args,data)
2405 self._edit_macro(args,data)
2423 return
2406 return
2424
2407
2425 # For objects, try to edit the file where they are defined
2408 # For objects, try to edit the file where they are defined
2426 try:
2409 try:
2427 filename = inspect.getabsfile(data)
2410 filename = inspect.getabsfile(data)
2428 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2411 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2429 # class created by %edit? Try to find source
2412 # class created by %edit? Try to find source
2430 # by looking for method definitions instead, the
2413 # by looking for method definitions instead, the
2431 # __module__ in those classes is FakeModule.
2414 # __module__ in those classes is FakeModule.
2432 attrs = [getattr(data, aname) for aname in dir(data)]
2415 attrs = [getattr(data, aname) for aname in dir(data)]
2433 for attr in attrs:
2416 for attr in attrs:
2434 if not inspect.ismethod(attr):
2417 if not inspect.ismethod(attr):
2435 continue
2418 continue
2436 filename = inspect.getabsfile(attr)
2419 filename = inspect.getabsfile(attr)
2437 if filename and 'fakemodule' not in filename.lower():
2420 if filename and 'fakemodule' not in filename.lower():
2438 # change the attribute to be the edit target instead
2421 # change the attribute to be the edit target instead
2439 data = attr
2422 data = attr
2440 break
2423 break
2441
2424
2442 datafile = 1
2425 datafile = 1
2443 except TypeError:
2426 except TypeError:
2444 filename = make_filename(args)
2427 filename = make_filename(args)
2445 datafile = 1
2428 datafile = 1
2446 warn('Could not find file where `%s` is defined.\n'
2429 warn('Could not find file where `%s` is defined.\n'
2447 'Opening a file named `%s`' % (args,filename))
2430 'Opening a file named `%s`' % (args,filename))
2448 # Now, make sure we can actually read the source (if it was in
2431 # Now, make sure we can actually read the source (if it was in
2449 # a temp file it's gone by now).
2432 # a temp file it's gone by now).
2450 if datafile:
2433 if datafile:
2451 try:
2434 try:
2452 if lineno is None:
2435 if lineno is None:
2453 lineno = inspect.getsourcelines(data)[1]
2436 lineno = inspect.getsourcelines(data)[1]
2454 except IOError:
2437 except IOError:
2455 filename = make_filename(args)
2438 filename = make_filename(args)
2456 if filename is None:
2439 if filename is None:
2457 warn('The file `%s` where `%s` was defined cannot '
2440 warn('The file `%s` where `%s` was defined cannot '
2458 'be read.' % (filename,data))
2441 'be read.' % (filename,data))
2459 return
2442 return
2460 use_temp = 0
2443 use_temp = 0
2461 else:
2444 else:
2462 data = ''
2445 data = ''
2463
2446
2464 if use_temp:
2447 if use_temp:
2465 filename = self.shell.mktempfile(data)
2448 filename = self.shell.mktempfile(data)
2466 print 'IPython will make a temporary file named:',filename
2449 print 'IPython will make a temporary file named:',filename
2467
2450
2468 # do actual editing here
2451 # do actual editing here
2469 print 'Editing...',
2452 print 'Editing...',
2470 sys.stdout.flush()
2453 sys.stdout.flush()
2471 try:
2454 try:
2472 # Quote filenames that may have spaces in them
2455 # Quote filenames that may have spaces in them
2473 if ' ' in filename:
2456 if ' ' in filename:
2474 filename = "%s" % filename
2457 filename = "%s" % filename
2475 self.shell.hooks.editor(filename,lineno)
2458 self.shell.hooks.editor(filename,lineno)
2476 except TryNext:
2459 except TryNext:
2477 warn('Could not open editor')
2460 warn('Could not open editor')
2478 return
2461 return
2479
2462
2480 # XXX TODO: should this be generalized for all string vars?
2463 # XXX TODO: should this be generalized for all string vars?
2481 # For now, this is special-cased to blocks created by cpaste
2464 # For now, this is special-cased to blocks created by cpaste
2482 if args.strip() == 'pasted_block':
2465 if args.strip() == 'pasted_block':
2483 self.shell.user_ns['pasted_block'] = file_read(filename)
2466 self.shell.user_ns['pasted_block'] = file_read(filename)
2484
2467
2485 if opts.has_key('x'): # -x prevents actual execution
2468 if opts.has_key('x'): # -x prevents actual execution
2486 print
2469 print
2487 else:
2470 else:
2488 print 'done. Executing edited code...'
2471 print 'done. Executing edited code...'
2489 if opts_r:
2472 if opts_r:
2490 self.shell.runlines(file_read(filename))
2473 self.shell.runlines(file_read(filename))
2491 else:
2474 else:
2492 self.shell.safe_execfile(filename,self.shell.user_ns,
2475 self.shell.safe_execfile(filename,self.shell.user_ns,
2493 self.shell.user_ns)
2476 self.shell.user_ns)
2494
2477
2495
2478
2496 if use_temp:
2479 if use_temp:
2497 try:
2480 try:
2498 return open(filename).read()
2481 return open(filename).read()
2499 except IOError,msg:
2482 except IOError,msg:
2500 if msg.filename == filename:
2483 if msg.filename == filename:
2501 warn('File not found. Did you forget to save?')
2484 warn('File not found. Did you forget to save?')
2502 return
2485 return
2503 else:
2486 else:
2504 self.shell.showtraceback()
2487 self.shell.showtraceback()
2505
2488
2506 def magic_xmode(self,parameter_s = ''):
2489 def magic_xmode(self,parameter_s = ''):
2507 """Switch modes for the exception handlers.
2490 """Switch modes for the exception handlers.
2508
2491
2509 Valid modes: Plain, Context and Verbose.
2492 Valid modes: Plain, Context and Verbose.
2510
2493
2511 If called without arguments, acts as a toggle."""
2494 If called without arguments, acts as a toggle."""
2512
2495
2513 def xmode_switch_err(name):
2496 def xmode_switch_err(name):
2514 warn('Error changing %s exception modes.\n%s' %
2497 warn('Error changing %s exception modes.\n%s' %
2515 (name,sys.exc_info()[1]))
2498 (name,sys.exc_info()[1]))
2516
2499
2517 shell = self.shell
2500 shell = self.shell
2518 new_mode = parameter_s.strip().capitalize()
2501 new_mode = parameter_s.strip().capitalize()
2519 try:
2502 try:
2520 shell.InteractiveTB.set_mode(mode=new_mode)
2503 shell.InteractiveTB.set_mode(mode=new_mode)
2521 print 'Exception reporting mode:',shell.InteractiveTB.mode
2504 print 'Exception reporting mode:',shell.InteractiveTB.mode
2522 except:
2505 except:
2523 xmode_switch_err('user')
2506 xmode_switch_err('user')
2524
2507
2525 def magic_colors(self,parameter_s = ''):
2508 def magic_colors(self,parameter_s = ''):
2526 """Switch color scheme for prompts, info system and exception handlers.
2509 """Switch color scheme for prompts, info system and exception handlers.
2527
2510
2528 Currently implemented schemes: NoColor, Linux, LightBG.
2511 Currently implemented schemes: NoColor, Linux, LightBG.
2529
2512
2530 Color scheme names are not case-sensitive."""
2513 Color scheme names are not case-sensitive."""
2531
2514
2532 def color_switch_err(name):
2515 def color_switch_err(name):
2533 warn('Error changing %s color schemes.\n%s' %
2516 warn('Error changing %s color schemes.\n%s' %
2534 (name,sys.exc_info()[1]))
2517 (name,sys.exc_info()[1]))
2535
2518
2536
2519
2537 new_scheme = parameter_s.strip()
2520 new_scheme = parameter_s.strip()
2538 if not new_scheme:
2521 if not new_scheme:
2539 raise UsageError(
2522 raise UsageError(
2540 "%colors: you must specify a color scheme. See '%colors?'")
2523 "%colors: you must specify a color scheme. See '%colors?'")
2541 return
2524 return
2542 # local shortcut
2525 # local shortcut
2543 shell = self.shell
2526 shell = self.shell
2544
2527
2545 import IPython.utils.rlineimpl as readline
2528 import IPython.utils.rlineimpl as readline
2546
2529
2547 if not readline.have_readline and sys.platform == "win32":
2530 if not readline.have_readline and sys.platform == "win32":
2548 msg = """\
2531 msg = """\
2549 Proper color support under MS Windows requires the pyreadline library.
2532 Proper color support under MS Windows requires the pyreadline library.
2550 You can find it at:
2533 You can find it at:
2551 http://ipython.scipy.org/moin/PyReadline/Intro
2534 http://ipython.scipy.org/moin/PyReadline/Intro
2552 Gary's readline needs the ctypes module, from:
2535 Gary's readline needs the ctypes module, from:
2553 http://starship.python.net/crew/theller/ctypes
2536 http://starship.python.net/crew/theller/ctypes
2554 (Note that ctypes is already part of Python versions 2.5 and newer).
2537 (Note that ctypes is already part of Python versions 2.5 and newer).
2555
2538
2556 Defaulting color scheme to 'NoColor'"""
2539 Defaulting color scheme to 'NoColor'"""
2557 new_scheme = 'NoColor'
2540 new_scheme = 'NoColor'
2558 warn(msg)
2541 warn(msg)
2559
2542
2560 # readline option is 0
2543 # readline option is 0
2561 if not shell.has_readline:
2544 if not shell.has_readline:
2562 new_scheme = 'NoColor'
2545 new_scheme = 'NoColor'
2563
2546
2564 # Set prompt colors
2547 # Set prompt colors
2565 try:
2548 try:
2566 shell.displayhook.set_colors(new_scheme)
2549 shell.displayhook.set_colors(new_scheme)
2567 except:
2550 except:
2568 color_switch_err('prompt')
2551 color_switch_err('prompt')
2569 else:
2552 else:
2570 shell.colors = \
2553 shell.colors = \
2571 shell.displayhook.color_table.active_scheme_name
2554 shell.displayhook.color_table.active_scheme_name
2572 # Set exception colors
2555 # Set exception colors
2573 try:
2556 try:
2574 shell.InteractiveTB.set_colors(scheme = new_scheme)
2557 shell.InteractiveTB.set_colors(scheme = new_scheme)
2575 shell.SyntaxTB.set_colors(scheme = new_scheme)
2558 shell.SyntaxTB.set_colors(scheme = new_scheme)
2576 except:
2559 except:
2577 color_switch_err('exception')
2560 color_switch_err('exception')
2578
2561
2579 # Set info (for 'object?') colors
2562 # Set info (for 'object?') colors
2580 if shell.color_info:
2563 if shell.color_info:
2581 try:
2564 try:
2582 shell.inspector.set_active_scheme(new_scheme)
2565 shell.inspector.set_active_scheme(new_scheme)
2583 except:
2566 except:
2584 color_switch_err('object inspector')
2567 color_switch_err('object inspector')
2585 else:
2568 else:
2586 shell.inspector.set_active_scheme('NoColor')
2569 shell.inspector.set_active_scheme('NoColor')
2587
2570
2588 def magic_color_info(self,parameter_s = ''):
2571 def magic_color_info(self,parameter_s = ''):
2589 """Toggle color_info.
2572 """Toggle color_info.
2590
2573
2591 The color_info configuration parameter controls whether colors are
2574 The color_info configuration parameter controls whether colors are
2592 used for displaying object details (by things like %psource, %pfile or
2575 used for displaying object details (by things like %psource, %pfile or
2593 the '?' system). This function toggles this value with each call.
2576 the '?' system). This function toggles this value with each call.
2594
2577
2595 Note that unless you have a fairly recent pager (less works better
2578 Note that unless you have a fairly recent pager (less works better
2596 than more) in your system, using colored object information displays
2579 than more) in your system, using colored object information displays
2597 will not work properly. Test it and see."""
2580 will not work properly. Test it and see."""
2598
2581
2599 self.shell.color_info = not self.shell.color_info
2582 self.shell.color_info = not self.shell.color_info
2600 self.magic_colors(self.shell.colors)
2583 self.magic_colors(self.shell.colors)
2601 print 'Object introspection functions have now coloring:',
2584 print 'Object introspection functions have now coloring:',
2602 print ['OFF','ON'][int(self.shell.color_info)]
2585 print ['OFF','ON'][int(self.shell.color_info)]
2603
2586
2604 def magic_Pprint(self, parameter_s=''):
2587 def magic_Pprint(self, parameter_s=''):
2605 """Toggle pretty printing on/off."""
2588 """Toggle pretty printing on/off."""
2606
2589
2607 self.shell.pprint = 1 - self.shell.pprint
2590 self.shell.pprint = 1 - self.shell.pprint
2608 print 'Pretty printing has been turned', \
2591 print 'Pretty printing has been turned', \
2609 ['OFF','ON'][self.shell.pprint]
2592 ['OFF','ON'][self.shell.pprint]
2610
2593
2611 def magic_Exit(self, parameter_s=''):
2594 def magic_Exit(self, parameter_s=''):
2612 """Exit IPython without confirmation."""
2595 """Exit IPython without confirmation."""
2613
2596
2614 self.shell.ask_exit()
2597 self.shell.ask_exit()
2615
2598
2616 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2599 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2617 magic_exit = magic_quit = magic_Quit = magic_Exit
2600 magic_exit = magic_quit = magic_Quit = magic_Exit
2618
2601
2619 #......................................................................
2602 #......................................................................
2620 # Functions to implement unix shell-type things
2603 # Functions to implement unix shell-type things
2621
2604
2622 @testdec.skip_doctest
2605 @testdec.skip_doctest
2623 def magic_alias(self, parameter_s = ''):
2606 def magic_alias(self, parameter_s = ''):
2624 """Define an alias for a system command.
2607 """Define an alias for a system command.
2625
2608
2626 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2609 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2627
2610
2628 Then, typing 'alias_name params' will execute the system command 'cmd
2611 Then, typing 'alias_name params' will execute the system command 'cmd
2629 params' (from your underlying operating system).
2612 params' (from your underlying operating system).
2630
2613
2631 Aliases have lower precedence than magic functions and Python normal
2614 Aliases have lower precedence than magic functions and Python normal
2632 variables, so if 'foo' is both a Python variable and an alias, the
2615 variables, so if 'foo' is both a Python variable and an alias, the
2633 alias can not be executed until 'del foo' removes the Python variable.
2616 alias can not be executed until 'del foo' removes the Python variable.
2634
2617
2635 You can use the %l specifier in an alias definition to represent the
2618 You can use the %l specifier in an alias definition to represent the
2636 whole line when the alias is called. For example:
2619 whole line when the alias is called. For example:
2637
2620
2638 In [2]: alias bracket echo "Input in brackets: <%l>"
2621 In [2]: alias bracket echo "Input in brackets: <%l>"
2639 In [3]: bracket hello world
2622 In [3]: bracket hello world
2640 Input in brackets: <hello world>
2623 Input in brackets: <hello world>
2641
2624
2642 You can also define aliases with parameters using %s specifiers (one
2625 You can also define aliases with parameters using %s specifiers (one
2643 per parameter):
2626 per parameter):
2644
2627
2645 In [1]: alias parts echo first %s second %s
2628 In [1]: alias parts echo first %s second %s
2646 In [2]: %parts A B
2629 In [2]: %parts A B
2647 first A second B
2630 first A second B
2648 In [3]: %parts A
2631 In [3]: %parts A
2649 Incorrect number of arguments: 2 expected.
2632 Incorrect number of arguments: 2 expected.
2650 parts is an alias to: 'echo first %s second %s'
2633 parts is an alias to: 'echo first %s second %s'
2651
2634
2652 Note that %l and %s are mutually exclusive. You can only use one or
2635 Note that %l and %s are mutually exclusive. You can only use one or
2653 the other in your aliases.
2636 the other in your aliases.
2654
2637
2655 Aliases expand Python variables just like system calls using ! or !!
2638 Aliases expand Python variables just like system calls using ! or !!
2656 do: all expressions prefixed with '$' get expanded. For details of
2639 do: all expressions prefixed with '$' get expanded. For details of
2657 the semantic rules, see PEP-215:
2640 the semantic rules, see PEP-215:
2658 http://www.python.org/peps/pep-0215.html. This is the library used by
2641 http://www.python.org/peps/pep-0215.html. This is the library used by
2659 IPython for variable expansion. If you want to access a true shell
2642 IPython for variable expansion. If you want to access a true shell
2660 variable, an extra $ is necessary to prevent its expansion by IPython:
2643 variable, an extra $ is necessary to prevent its expansion by IPython:
2661
2644
2662 In [6]: alias show echo
2645 In [6]: alias show echo
2663 In [7]: PATH='A Python string'
2646 In [7]: PATH='A Python string'
2664 In [8]: show $PATH
2647 In [8]: show $PATH
2665 A Python string
2648 A Python string
2666 In [9]: show $$PATH
2649 In [9]: show $$PATH
2667 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2650 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2668
2651
2669 You can use the alias facility to acess all of $PATH. See the %rehash
2652 You can use the alias facility to acess all of $PATH. See the %rehash
2670 and %rehashx functions, which automatically create aliases for the
2653 and %rehashx functions, which automatically create aliases for the
2671 contents of your $PATH.
2654 contents of your $PATH.
2672
2655
2673 If called with no parameters, %alias prints the current alias table."""
2656 If called with no parameters, %alias prints the current alias table."""
2674
2657
2675 par = parameter_s.strip()
2658 par = parameter_s.strip()
2676 if not par:
2659 if not par:
2677 stored = self.db.get('stored_aliases', {} )
2660 stored = self.db.get('stored_aliases', {} )
2678 aliases = sorted(self.shell.alias_manager.aliases)
2661 aliases = sorted(self.shell.alias_manager.aliases)
2679 # for k, v in stored:
2662 # for k, v in stored:
2680 # atab.append(k, v[0])
2663 # atab.append(k, v[0])
2681
2664
2682 print "Total number of aliases:", len(aliases)
2665 print "Total number of aliases:", len(aliases)
2683 return aliases
2666 return aliases
2684
2667
2685 # Now try to define a new one
2668 # Now try to define a new one
2686 try:
2669 try:
2687 alias,cmd = par.split(None, 1)
2670 alias,cmd = par.split(None, 1)
2688 except:
2671 except:
2689 print oinspect.getdoc(self.magic_alias)
2672 print oinspect.getdoc(self.magic_alias)
2690 else:
2673 else:
2691 self.shell.alias_manager.soft_define_alias(alias, cmd)
2674 self.shell.alias_manager.soft_define_alias(alias, cmd)
2692 # end magic_alias
2675 # end magic_alias
2693
2676
2694 def magic_unalias(self, parameter_s = ''):
2677 def magic_unalias(self, parameter_s = ''):
2695 """Remove an alias"""
2678 """Remove an alias"""
2696
2679
2697 aname = parameter_s.strip()
2680 aname = parameter_s.strip()
2698 self.shell.alias_manager.undefine_alias(aname)
2681 self.shell.alias_manager.undefine_alias(aname)
2699 stored = self.db.get('stored_aliases', {} )
2682 stored = self.db.get('stored_aliases', {} )
2700 if aname in stored:
2683 if aname in stored:
2701 print "Removing %stored alias",aname
2684 print "Removing %stored alias",aname
2702 del stored[aname]
2685 del stored[aname]
2703 self.db['stored_aliases'] = stored
2686 self.db['stored_aliases'] = stored
2704
2687
2705
2688
2706 def magic_rehashx(self, parameter_s = ''):
2689 def magic_rehashx(self, parameter_s = ''):
2707 """Update the alias table with all executable files in $PATH.
2690 """Update the alias table with all executable files in $PATH.
2708
2691
2709 This version explicitly checks that every entry in $PATH is a file
2692 This version explicitly checks that every entry in $PATH is a file
2710 with execute access (os.X_OK), so it is much slower than %rehash.
2693 with execute access (os.X_OK), so it is much slower than %rehash.
2711
2694
2712 Under Windows, it checks executability as a match agains a
2695 Under Windows, it checks executability as a match agains a
2713 '|'-separated string of extensions, stored in the IPython config
2696 '|'-separated string of extensions, stored in the IPython config
2714 variable win_exec_ext. This defaults to 'exe|com|bat'.
2697 variable win_exec_ext. This defaults to 'exe|com|bat'.
2715
2698
2716 This function also resets the root module cache of module completer,
2699 This function also resets the root module cache of module completer,
2717 used on slow filesystems.
2700 used on slow filesystems.
2718 """
2701 """
2719 from IPython.core.alias import InvalidAliasError
2702 from IPython.core.alias import InvalidAliasError
2720
2703
2721 # for the benefit of module completer in ipy_completers.py
2704 # for the benefit of module completer in ipy_completers.py
2722 del self.db['rootmodules']
2705 del self.db['rootmodules']
2723
2706
2724 path = [os.path.abspath(os.path.expanduser(p)) for p in
2707 path = [os.path.abspath(os.path.expanduser(p)) for p in
2725 os.environ.get('PATH','').split(os.pathsep)]
2708 os.environ.get('PATH','').split(os.pathsep)]
2726 path = filter(os.path.isdir,path)
2709 path = filter(os.path.isdir,path)
2727
2710
2728 syscmdlist = []
2711 syscmdlist = []
2729 # Now define isexec in a cross platform manner.
2712 # Now define isexec in a cross platform manner.
2730 if os.name == 'posix':
2713 if os.name == 'posix':
2731 isexec = lambda fname:os.path.isfile(fname) and \
2714 isexec = lambda fname:os.path.isfile(fname) and \
2732 os.access(fname,os.X_OK)
2715 os.access(fname,os.X_OK)
2733 else:
2716 else:
2734 try:
2717 try:
2735 winext = os.environ['pathext'].replace(';','|').replace('.','')
2718 winext = os.environ['pathext'].replace(';','|').replace('.','')
2736 except KeyError:
2719 except KeyError:
2737 winext = 'exe|com|bat|py'
2720 winext = 'exe|com|bat|py'
2738 if 'py' not in winext:
2721 if 'py' not in winext:
2739 winext += '|py'
2722 winext += '|py'
2740 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2723 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2741 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2724 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2742 savedir = os.getcwd()
2725 savedir = os.getcwd()
2743
2726
2744 # Now walk the paths looking for executables to alias.
2727 # Now walk the paths looking for executables to alias.
2745 try:
2728 try:
2746 # write the whole loop for posix/Windows so we don't have an if in
2729 # write the whole loop for posix/Windows so we don't have an if in
2747 # the innermost part
2730 # the innermost part
2748 if os.name == 'posix':
2731 if os.name == 'posix':
2749 for pdir in path:
2732 for pdir in path:
2750 os.chdir(pdir)
2733 os.chdir(pdir)
2751 for ff in os.listdir(pdir):
2734 for ff in os.listdir(pdir):
2752 if isexec(ff):
2735 if isexec(ff):
2753 try:
2736 try:
2754 # Removes dots from the name since ipython
2737 # Removes dots from the name since ipython
2755 # will assume names with dots to be python.
2738 # will assume names with dots to be python.
2756 self.shell.alias_manager.define_alias(
2739 self.shell.alias_manager.define_alias(
2757 ff.replace('.',''), ff)
2740 ff.replace('.',''), ff)
2758 except InvalidAliasError:
2741 except InvalidAliasError:
2759 pass
2742 pass
2760 else:
2743 else:
2761 syscmdlist.append(ff)
2744 syscmdlist.append(ff)
2762 else:
2745 else:
2763 no_alias = self.shell.alias_manager.no_alias
2746 no_alias = self.shell.alias_manager.no_alias
2764 for pdir in path:
2747 for pdir in path:
2765 os.chdir(pdir)
2748 os.chdir(pdir)
2766 for ff in os.listdir(pdir):
2749 for ff in os.listdir(pdir):
2767 base, ext = os.path.splitext(ff)
2750 base, ext = os.path.splitext(ff)
2768 if isexec(ff) and base.lower() not in no_alias:
2751 if isexec(ff) and base.lower() not in no_alias:
2769 if ext.lower() == '.exe':
2752 if ext.lower() == '.exe':
2770 ff = base
2753 ff = base
2771 try:
2754 try:
2772 # Removes dots from the name since ipython
2755 # Removes dots from the name since ipython
2773 # will assume names with dots to be python.
2756 # will assume names with dots to be python.
2774 self.shell.alias_manager.define_alias(
2757 self.shell.alias_manager.define_alias(
2775 base.lower().replace('.',''), ff)
2758 base.lower().replace('.',''), ff)
2776 except InvalidAliasError:
2759 except InvalidAliasError:
2777 pass
2760 pass
2778 syscmdlist.append(ff)
2761 syscmdlist.append(ff)
2779 db = self.db
2762 db = self.db
2780 db['syscmdlist'] = syscmdlist
2763 db['syscmdlist'] = syscmdlist
2781 finally:
2764 finally:
2782 os.chdir(savedir)
2765 os.chdir(savedir)
2783
2766
2784 def magic_pwd(self, parameter_s = ''):
2767 def magic_pwd(self, parameter_s = ''):
2785 """Return the current working directory path."""
2768 """Return the current working directory path."""
2786 return os.getcwd()
2769 return os.getcwd()
2787
2770
2788 def magic_cd(self, parameter_s=''):
2771 def magic_cd(self, parameter_s=''):
2789 """Change the current working directory.
2772 """Change the current working directory.
2790
2773
2791 This command automatically maintains an internal list of directories
2774 This command automatically maintains an internal list of directories
2792 you visit during your IPython session, in the variable _dh. The
2775 you visit during your IPython session, in the variable _dh. The
2793 command %dhist shows this history nicely formatted. You can also
2776 command %dhist shows this history nicely formatted. You can also
2794 do 'cd -<tab>' to see directory history conveniently.
2777 do 'cd -<tab>' to see directory history conveniently.
2795
2778
2796 Usage:
2779 Usage:
2797
2780
2798 cd 'dir': changes to directory 'dir'.
2781 cd 'dir': changes to directory 'dir'.
2799
2782
2800 cd -: changes to the last visited directory.
2783 cd -: changes to the last visited directory.
2801
2784
2802 cd -<n>: changes to the n-th directory in the directory history.
2785 cd -<n>: changes to the n-th directory in the directory history.
2803
2786
2804 cd --foo: change to directory that matches 'foo' in history
2787 cd --foo: change to directory that matches 'foo' in history
2805
2788
2806 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2789 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2807 (note: cd <bookmark_name> is enough if there is no
2790 (note: cd <bookmark_name> is enough if there is no
2808 directory <bookmark_name>, but a bookmark with the name exists.)
2791 directory <bookmark_name>, but a bookmark with the name exists.)
2809 'cd -b <tab>' allows you to tab-complete bookmark names.
2792 'cd -b <tab>' allows you to tab-complete bookmark names.
2810
2793
2811 Options:
2794 Options:
2812
2795
2813 -q: quiet. Do not print the working directory after the cd command is
2796 -q: quiet. Do not print the working directory after the cd command is
2814 executed. By default IPython's cd command does print this directory,
2797 executed. By default IPython's cd command does print this directory,
2815 since the default prompts do not display path information.
2798 since the default prompts do not display path information.
2816
2799
2817 Note that !cd doesn't work for this purpose because the shell where
2800 Note that !cd doesn't work for this purpose because the shell where
2818 !command runs is immediately discarded after executing 'command'."""
2801 !command runs is immediately discarded after executing 'command'."""
2819
2802
2820 parameter_s = parameter_s.strip()
2803 parameter_s = parameter_s.strip()
2821 #bkms = self.shell.persist.get("bookmarks",{})
2804 #bkms = self.shell.persist.get("bookmarks",{})
2822
2805
2823 oldcwd = os.getcwd()
2806 oldcwd = os.getcwd()
2824 numcd = re.match(r'(-)(\d+)$',parameter_s)
2807 numcd = re.match(r'(-)(\d+)$',parameter_s)
2825 # jump in directory history by number
2808 # jump in directory history by number
2826 if numcd:
2809 if numcd:
2827 nn = int(numcd.group(2))
2810 nn = int(numcd.group(2))
2828 try:
2811 try:
2829 ps = self.shell.user_ns['_dh'][nn]
2812 ps = self.shell.user_ns['_dh'][nn]
2830 except IndexError:
2813 except IndexError:
2831 print 'The requested directory does not exist in history.'
2814 print 'The requested directory does not exist in history.'
2832 return
2815 return
2833 else:
2816 else:
2834 opts = {}
2817 opts = {}
2835 elif parameter_s.startswith('--'):
2818 elif parameter_s.startswith('--'):
2836 ps = None
2819 ps = None
2837 fallback = None
2820 fallback = None
2838 pat = parameter_s[2:]
2821 pat = parameter_s[2:]
2839 dh = self.shell.user_ns['_dh']
2822 dh = self.shell.user_ns['_dh']
2840 # first search only by basename (last component)
2823 # first search only by basename (last component)
2841 for ent in reversed(dh):
2824 for ent in reversed(dh):
2842 if pat in os.path.basename(ent) and os.path.isdir(ent):
2825 if pat in os.path.basename(ent) and os.path.isdir(ent):
2843 ps = ent
2826 ps = ent
2844 break
2827 break
2845
2828
2846 if fallback is None and pat in ent and os.path.isdir(ent):
2829 if fallback is None and pat in ent and os.path.isdir(ent):
2847 fallback = ent
2830 fallback = ent
2848
2831
2849 # if we have no last part match, pick the first full path match
2832 # if we have no last part match, pick the first full path match
2850 if ps is None:
2833 if ps is None:
2851 ps = fallback
2834 ps = fallback
2852
2835
2853 if ps is None:
2836 if ps is None:
2854 print "No matching entry in directory history"
2837 print "No matching entry in directory history"
2855 return
2838 return
2856 else:
2839 else:
2857 opts = {}
2840 opts = {}
2858
2841
2859
2842
2860 else:
2843 else:
2861 #turn all non-space-escaping backslashes to slashes,
2844 #turn all non-space-escaping backslashes to slashes,
2862 # for c:\windows\directory\names\
2845 # for c:\windows\directory\names\
2863 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2846 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2864 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2847 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2865 # jump to previous
2848 # jump to previous
2866 if ps == '-':
2849 if ps == '-':
2867 try:
2850 try:
2868 ps = self.shell.user_ns['_dh'][-2]
2851 ps = self.shell.user_ns['_dh'][-2]
2869 except IndexError:
2852 except IndexError:
2870 raise UsageError('%cd -: No previous directory to change to.')
2853 raise UsageError('%cd -: No previous directory to change to.')
2871 # jump to bookmark if needed
2854 # jump to bookmark if needed
2872 else:
2855 else:
2873 if not os.path.isdir(ps) or opts.has_key('b'):
2856 if not os.path.isdir(ps) or opts.has_key('b'):
2874 bkms = self.db.get('bookmarks', {})
2857 bkms = self.db.get('bookmarks', {})
2875
2858
2876 if bkms.has_key(ps):
2859 if bkms.has_key(ps):
2877 target = bkms[ps]
2860 target = bkms[ps]
2878 print '(bookmark:%s) -> %s' % (ps,target)
2861 print '(bookmark:%s) -> %s' % (ps,target)
2879 ps = target
2862 ps = target
2880 else:
2863 else:
2881 if opts.has_key('b'):
2864 if opts.has_key('b'):
2882 raise UsageError("Bookmark '%s' not found. "
2865 raise UsageError("Bookmark '%s' not found. "
2883 "Use '%%bookmark -l' to see your bookmarks." % ps)
2866 "Use '%%bookmark -l' to see your bookmarks." % ps)
2884
2867
2885 # at this point ps should point to the target dir
2868 # at this point ps should point to the target dir
2886 if ps:
2869 if ps:
2887 try:
2870 try:
2888 os.chdir(os.path.expanduser(ps))
2871 os.chdir(os.path.expanduser(ps))
2889 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2872 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2890 set_term_title('IPython: ' + abbrev_cwd())
2873 set_term_title('IPython: ' + abbrev_cwd())
2891 except OSError:
2874 except OSError:
2892 print sys.exc_info()[1]
2875 print sys.exc_info()[1]
2893 else:
2876 else:
2894 cwd = os.getcwd()
2877 cwd = os.getcwd()
2895 dhist = self.shell.user_ns['_dh']
2878 dhist = self.shell.user_ns['_dh']
2896 if oldcwd != cwd:
2879 if oldcwd != cwd:
2897 dhist.append(cwd)
2880 dhist.append(cwd)
2898 self.db['dhist'] = compress_dhist(dhist)[-100:]
2881 self.db['dhist'] = compress_dhist(dhist)[-100:]
2899
2882
2900 else:
2883 else:
2901 os.chdir(self.shell.home_dir)
2884 os.chdir(self.shell.home_dir)
2902 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2885 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2903 set_term_title('IPython: ' + '~')
2886 set_term_title('IPython: ' + '~')
2904 cwd = os.getcwd()
2887 cwd = os.getcwd()
2905 dhist = self.shell.user_ns['_dh']
2888 dhist = self.shell.user_ns['_dh']
2906
2889
2907 if oldcwd != cwd:
2890 if oldcwd != cwd:
2908 dhist.append(cwd)
2891 dhist.append(cwd)
2909 self.db['dhist'] = compress_dhist(dhist)[-100:]
2892 self.db['dhist'] = compress_dhist(dhist)[-100:]
2910 if not 'q' in opts and self.shell.user_ns['_dh']:
2893 if not 'q' in opts and self.shell.user_ns['_dh']:
2911 print self.shell.user_ns['_dh'][-1]
2894 print self.shell.user_ns['_dh'][-1]
2912
2895
2913
2896
2914 def magic_env(self, parameter_s=''):
2897 def magic_env(self, parameter_s=''):
2915 """List environment variables."""
2898 """List environment variables."""
2916
2899
2917 return os.environ.data
2900 return os.environ.data
2918
2901
2919 def magic_pushd(self, parameter_s=''):
2902 def magic_pushd(self, parameter_s=''):
2920 """Place the current dir on stack and change directory.
2903 """Place the current dir on stack and change directory.
2921
2904
2922 Usage:\\
2905 Usage:\\
2923 %pushd ['dirname']
2906 %pushd ['dirname']
2924 """
2907 """
2925
2908
2926 dir_s = self.shell.dir_stack
2909 dir_s = self.shell.dir_stack
2927 tgt = os.path.expanduser(parameter_s)
2910 tgt = os.path.expanduser(parameter_s)
2928 cwd = os.getcwd().replace(self.home_dir,'~')
2911 cwd = os.getcwd().replace(self.home_dir,'~')
2929 if tgt:
2912 if tgt:
2930 self.magic_cd(parameter_s)
2913 self.magic_cd(parameter_s)
2931 dir_s.insert(0,cwd)
2914 dir_s.insert(0,cwd)
2932 return self.magic_dirs()
2915 return self.magic_dirs()
2933
2916
2934 def magic_popd(self, parameter_s=''):
2917 def magic_popd(self, parameter_s=''):
2935 """Change to directory popped off the top of the stack.
2918 """Change to directory popped off the top of the stack.
2936 """
2919 """
2937 if not self.shell.dir_stack:
2920 if not self.shell.dir_stack:
2938 raise UsageError("%popd on empty stack")
2921 raise UsageError("%popd on empty stack")
2939 top = self.shell.dir_stack.pop(0)
2922 top = self.shell.dir_stack.pop(0)
2940 self.magic_cd(top)
2923 self.magic_cd(top)
2941 print "popd ->",top
2924 print "popd ->",top
2942
2925
2943 def magic_dirs(self, parameter_s=''):
2926 def magic_dirs(self, parameter_s=''):
2944 """Return the current directory stack."""
2927 """Return the current directory stack."""
2945
2928
2946 return self.shell.dir_stack
2929 return self.shell.dir_stack
2947
2930
2948 def magic_dhist(self, parameter_s=''):
2931 def magic_dhist(self, parameter_s=''):
2949 """Print your history of visited directories.
2932 """Print your history of visited directories.
2950
2933
2951 %dhist -> print full history\\
2934 %dhist -> print full history\\
2952 %dhist n -> print last n entries only\\
2935 %dhist n -> print last n entries only\\
2953 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2936 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2954
2937
2955 This history is automatically maintained by the %cd command, and
2938 This history is automatically maintained by the %cd command, and
2956 always available as the global list variable _dh. You can use %cd -<n>
2939 always available as the global list variable _dh. You can use %cd -<n>
2957 to go to directory number <n>.
2940 to go to directory number <n>.
2958
2941
2959 Note that most of time, you should view directory history by entering
2942 Note that most of time, you should view directory history by entering
2960 cd -<TAB>.
2943 cd -<TAB>.
2961
2944
2962 """
2945 """
2963
2946
2964 dh = self.shell.user_ns['_dh']
2947 dh = self.shell.user_ns['_dh']
2965 if parameter_s:
2948 if parameter_s:
2966 try:
2949 try:
2967 args = map(int,parameter_s.split())
2950 args = map(int,parameter_s.split())
2968 except:
2951 except:
2969 self.arg_err(Magic.magic_dhist)
2952 self.arg_err(Magic.magic_dhist)
2970 return
2953 return
2971 if len(args) == 1:
2954 if len(args) == 1:
2972 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2955 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2973 elif len(args) == 2:
2956 elif len(args) == 2:
2974 ini,fin = args
2957 ini,fin = args
2975 else:
2958 else:
2976 self.arg_err(Magic.magic_dhist)
2959 self.arg_err(Magic.magic_dhist)
2977 return
2960 return
2978 else:
2961 else:
2979 ini,fin = 0,len(dh)
2962 ini,fin = 0,len(dh)
2980 nlprint(dh,
2963 nlprint(dh,
2981 header = 'Directory history (kept in _dh)',
2964 header = 'Directory history (kept in _dh)',
2982 start=ini,stop=fin)
2965 start=ini,stop=fin)
2983
2966
2984 @testdec.skip_doctest
2967 @testdec.skip_doctest
2985 def magic_sc(self, parameter_s=''):
2968 def magic_sc(self, parameter_s=''):
2986 """Shell capture - execute a shell command and capture its output.
2969 """Shell capture - execute a shell command and capture its output.
2987
2970
2988 DEPRECATED. Suboptimal, retained for backwards compatibility.
2971 DEPRECATED. Suboptimal, retained for backwards compatibility.
2989
2972
2990 You should use the form 'var = !command' instead. Example:
2973 You should use the form 'var = !command' instead. Example:
2991
2974
2992 "%sc -l myfiles = ls ~" should now be written as
2975 "%sc -l myfiles = ls ~" should now be written as
2993
2976
2994 "myfiles = !ls ~"
2977 "myfiles = !ls ~"
2995
2978
2996 myfiles.s, myfiles.l and myfiles.n still apply as documented
2979 myfiles.s, myfiles.l and myfiles.n still apply as documented
2997 below.
2980 below.
2998
2981
2999 --
2982 --
3000 %sc [options] varname=command
2983 %sc [options] varname=command
3001
2984
3002 IPython will run the given command using commands.getoutput(), and
2985 IPython will run the given command using commands.getoutput(), and
3003 will then update the user's interactive namespace with a variable
2986 will then update the user's interactive namespace with a variable
3004 called varname, containing the value of the call. Your command can
2987 called varname, containing the value of the call. Your command can
3005 contain shell wildcards, pipes, etc.
2988 contain shell wildcards, pipes, etc.
3006
2989
3007 The '=' sign in the syntax is mandatory, and the variable name you
2990 The '=' sign in the syntax is mandatory, and the variable name you
3008 supply must follow Python's standard conventions for valid names.
2991 supply must follow Python's standard conventions for valid names.
3009
2992
3010 (A special format without variable name exists for internal use)
2993 (A special format without variable name exists for internal use)
3011
2994
3012 Options:
2995 Options:
3013
2996
3014 -l: list output. Split the output on newlines into a list before
2997 -l: list output. Split the output on newlines into a list before
3015 assigning it to the given variable. By default the output is stored
2998 assigning it to the given variable. By default the output is stored
3016 as a single string.
2999 as a single string.
3017
3000
3018 -v: verbose. Print the contents of the variable.
3001 -v: verbose. Print the contents of the variable.
3019
3002
3020 In most cases you should not need to split as a list, because the
3003 In most cases you should not need to split as a list, because the
3021 returned value is a special type of string which can automatically
3004 returned value is a special type of string which can automatically
3022 provide its contents either as a list (split on newlines) or as a
3005 provide its contents either as a list (split on newlines) or as a
3023 space-separated string. These are convenient, respectively, either
3006 space-separated string. These are convenient, respectively, either
3024 for sequential processing or to be passed to a shell command.
3007 for sequential processing or to be passed to a shell command.
3025
3008
3026 For example:
3009 For example:
3027
3010
3028 # all-random
3011 # all-random
3029
3012
3030 # Capture into variable a
3013 # Capture into variable a
3031 In [1]: sc a=ls *py
3014 In [1]: sc a=ls *py
3032
3015
3033 # a is a string with embedded newlines
3016 # a is a string with embedded newlines
3034 In [2]: a
3017 In [2]: a
3035 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3018 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3036
3019
3037 # which can be seen as a list:
3020 # which can be seen as a list:
3038 In [3]: a.l
3021 In [3]: a.l
3039 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3022 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3040
3023
3041 # or as a whitespace-separated string:
3024 # or as a whitespace-separated string:
3042 In [4]: a.s
3025 In [4]: a.s
3043 Out[4]: 'setup.py win32_manual_post_install.py'
3026 Out[4]: 'setup.py win32_manual_post_install.py'
3044
3027
3045 # a.s is useful to pass as a single command line:
3028 # a.s is useful to pass as a single command line:
3046 In [5]: !wc -l $a.s
3029 In [5]: !wc -l $a.s
3047 146 setup.py
3030 146 setup.py
3048 130 win32_manual_post_install.py
3031 130 win32_manual_post_install.py
3049 276 total
3032 276 total
3050
3033
3051 # while the list form is useful to loop over:
3034 # while the list form is useful to loop over:
3052 In [6]: for f in a.l:
3035 In [6]: for f in a.l:
3053 ...: !wc -l $f
3036 ...: !wc -l $f
3054 ...:
3037 ...:
3055 146 setup.py
3038 146 setup.py
3056 130 win32_manual_post_install.py
3039 130 win32_manual_post_install.py
3057
3040
3058 Similiarly, the lists returned by the -l option are also special, in
3041 Similiarly, the lists returned by the -l option are also special, in
3059 the sense that you can equally invoke the .s attribute on them to
3042 the sense that you can equally invoke the .s attribute on them to
3060 automatically get a whitespace-separated string from their contents:
3043 automatically get a whitespace-separated string from their contents:
3061
3044
3062 In [7]: sc -l b=ls *py
3045 In [7]: sc -l b=ls *py
3063
3046
3064 In [8]: b
3047 In [8]: b
3065 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3048 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3066
3049
3067 In [9]: b.s
3050 In [9]: b.s
3068 Out[9]: 'setup.py win32_manual_post_install.py'
3051 Out[9]: 'setup.py win32_manual_post_install.py'
3069
3052
3070 In summary, both the lists and strings used for ouptut capture have
3053 In summary, both the lists and strings used for ouptut capture have
3071 the following special attributes:
3054 the following special attributes:
3072
3055
3073 .l (or .list) : value as list.
3056 .l (or .list) : value as list.
3074 .n (or .nlstr): value as newline-separated string.
3057 .n (or .nlstr): value as newline-separated string.
3075 .s (or .spstr): value as space-separated string.
3058 .s (or .spstr): value as space-separated string.
3076 """
3059 """
3077
3060
3078 opts,args = self.parse_options(parameter_s,'lv')
3061 opts,args = self.parse_options(parameter_s,'lv')
3079 # Try to get a variable name and command to run
3062 # Try to get a variable name and command to run
3080 try:
3063 try:
3081 # the variable name must be obtained from the parse_options
3064 # the variable name must be obtained from the parse_options
3082 # output, which uses shlex.split to strip options out.
3065 # output, which uses shlex.split to strip options out.
3083 var,_ = args.split('=',1)
3066 var,_ = args.split('=',1)
3084 var = var.strip()
3067 var = var.strip()
3085 # But the the command has to be extracted from the original input
3068 # But the the command has to be extracted from the original input
3086 # parameter_s, not on what parse_options returns, to avoid the
3069 # parameter_s, not on what parse_options returns, to avoid the
3087 # quote stripping which shlex.split performs on it.
3070 # quote stripping which shlex.split performs on it.
3088 _,cmd = parameter_s.split('=',1)
3071 _,cmd = parameter_s.split('=',1)
3089 except ValueError:
3072 except ValueError:
3090 var,cmd = '',''
3073 var,cmd = '',''
3091 # If all looks ok, proceed
3074 # If all looks ok, proceed
3092 out,err = self.shell.getoutputerror(cmd)
3075 out,err = self.shell.getoutputerror(cmd)
3093 if err:
3076 if err:
3094 print >> IPython.utils.io.Term.cerr, err
3077 print >> IPython.utils.io.Term.cerr, err
3095 if opts.has_key('l'):
3078 if opts.has_key('l'):
3096 out = SList(out.split('\n'))
3079 out = SList(out.split('\n'))
3097 else:
3080 else:
3098 out = LSString(out)
3081 out = LSString(out)
3099 if opts.has_key('v'):
3082 if opts.has_key('v'):
3100 print '%s ==\n%s' % (var,pformat(out))
3083 print '%s ==\n%s' % (var,pformat(out))
3101 if var:
3084 if var:
3102 self.shell.user_ns.update({var:out})
3085 self.shell.user_ns.update({var:out})
3103 else:
3086 else:
3104 return out
3087 return out
3105
3088
3106 def magic_sx(self, parameter_s=''):
3089 def magic_sx(self, parameter_s=''):
3107 """Shell execute - run a shell command and capture its output.
3090 """Shell execute - run a shell command and capture its output.
3108
3091
3109 %sx command
3092 %sx command
3110
3093
3111 IPython will run the given command using commands.getoutput(), and
3094 IPython will run the given command using commands.getoutput(), and
3112 return the result formatted as a list (split on '\\n'). Since the
3095 return the result formatted as a list (split on '\\n'). Since the
3113 output is _returned_, it will be stored in ipython's regular output
3096 output is _returned_, it will be stored in ipython's regular output
3114 cache Out[N] and in the '_N' automatic variables.
3097 cache Out[N] and in the '_N' automatic variables.
3115
3098
3116 Notes:
3099 Notes:
3117
3100
3118 1) If an input line begins with '!!', then %sx is automatically
3101 1) If an input line begins with '!!', then %sx is automatically
3119 invoked. That is, while:
3102 invoked. That is, while:
3120 !ls
3103 !ls
3121 causes ipython to simply issue system('ls'), typing
3104 causes ipython to simply issue system('ls'), typing
3122 !!ls
3105 !!ls
3123 is a shorthand equivalent to:
3106 is a shorthand equivalent to:
3124 %sx ls
3107 %sx ls
3125
3108
3126 2) %sx differs from %sc in that %sx automatically splits into a list,
3109 2) %sx differs from %sc in that %sx automatically splits into a list,
3127 like '%sc -l'. The reason for this is to make it as easy as possible
3110 like '%sc -l'. The reason for this is to make it as easy as possible
3128 to process line-oriented shell output via further python commands.
3111 to process line-oriented shell output via further python commands.
3129 %sc is meant to provide much finer control, but requires more
3112 %sc is meant to provide much finer control, but requires more
3130 typing.
3113 typing.
3131
3114
3132 3) Just like %sc -l, this is a list with special attributes:
3115 3) Just like %sc -l, this is a list with special attributes:
3133
3116
3134 .l (or .list) : value as list.
3117 .l (or .list) : value as list.
3135 .n (or .nlstr): value as newline-separated string.
3118 .n (or .nlstr): value as newline-separated string.
3136 .s (or .spstr): value as whitespace-separated string.
3119 .s (or .spstr): value as whitespace-separated string.
3137
3120
3138 This is very useful when trying to use such lists as arguments to
3121 This is very useful when trying to use such lists as arguments to
3139 system commands."""
3122 system commands."""
3140
3123
3141 if parameter_s:
3124 if parameter_s:
3142 out,err = self.shell.getoutputerror(parameter_s)
3125 out,err = self.shell.getoutputerror(parameter_s)
3143 if err:
3126 if err:
3144 print >> IPython.utils.io.Term.cerr, err
3127 print >> IPython.utils.io.Term.cerr, err
3145 return SList(out.split('\n'))
3128 return SList(out.split('\n'))
3146
3129
3147 def magic_r(self, parameter_s=''):
3130 def magic_r(self, parameter_s=''):
3148 """Repeat previous input.
3131 """Repeat previous input.
3149
3132
3150 Note: Consider using the more powerfull %rep instead!
3133 Note: Consider using the more powerfull %rep instead!
3151
3134
3152 If given an argument, repeats the previous command which starts with
3135 If given an argument, repeats the previous command which starts with
3153 the same string, otherwise it just repeats the previous input.
3136 the same string, otherwise it just repeats the previous input.
3154
3137
3155 Shell escaped commands (with ! as first character) are not recognized
3138 Shell escaped commands (with ! as first character) are not recognized
3156 by this system, only pure python code and magic commands.
3139 by this system, only pure python code and magic commands.
3157 """
3140 """
3158
3141
3159 start = parameter_s.strip()
3142 start = parameter_s.strip()
3160 esc_magic = ESC_MAGIC
3143 esc_magic = ESC_MAGIC
3161 # Identify magic commands even if automagic is on (which means
3144 # Identify magic commands even if automagic is on (which means
3162 # the in-memory version is different from that typed by the user).
3145 # the in-memory version is different from that typed by the user).
3163 if self.shell.automagic:
3146 if self.shell.automagic:
3164 start_magic = esc_magic+start
3147 start_magic = esc_magic+start
3165 else:
3148 else:
3166 start_magic = start
3149 start_magic = start
3167 # Look through the input history in reverse
3150 # Look through the input history in reverse
3168 for n in range(len(self.shell.input_hist)-2,0,-1):
3151 for n in range(len(self.shell.input_hist)-2,0,-1):
3169 input = self.shell.input_hist[n]
3152 input = self.shell.input_hist[n]
3170 # skip plain 'r' lines so we don't recurse to infinity
3153 # skip plain 'r' lines so we don't recurse to infinity
3171 if input != '_ip.magic("r")\n' and \
3154 if input != '_ip.magic("r")\n' and \
3172 (input.startswith(start) or input.startswith(start_magic)):
3155 (input.startswith(start) or input.startswith(start_magic)):
3173 #print 'match',`input` # dbg
3156 #print 'match',`input` # dbg
3174 print 'Executing:',input,
3157 print 'Executing:',input,
3175 self.shell.runlines(input)
3158 self.shell.runlines(input)
3176 return
3159 return
3177 print 'No previous input matching `%s` found.' % start
3160 print 'No previous input matching `%s` found.' % start
3178
3161
3179
3162
3180 def magic_bookmark(self, parameter_s=''):
3163 def magic_bookmark(self, parameter_s=''):
3181 """Manage IPython's bookmark system.
3164 """Manage IPython's bookmark system.
3182
3165
3183 %bookmark <name> - set bookmark to current dir
3166 %bookmark <name> - set bookmark to current dir
3184 %bookmark <name> <dir> - set bookmark to <dir>
3167 %bookmark <name> <dir> - set bookmark to <dir>
3185 %bookmark -l - list all bookmarks
3168 %bookmark -l - list all bookmarks
3186 %bookmark -d <name> - remove bookmark
3169 %bookmark -d <name> - remove bookmark
3187 %bookmark -r - remove all bookmarks
3170 %bookmark -r - remove all bookmarks
3188
3171
3189 You can later on access a bookmarked folder with:
3172 You can later on access a bookmarked folder with:
3190 %cd -b <name>
3173 %cd -b <name>
3191 or simply '%cd <name>' if there is no directory called <name> AND
3174 or simply '%cd <name>' if there is no directory called <name> AND
3192 there is such a bookmark defined.
3175 there is such a bookmark defined.
3193
3176
3194 Your bookmarks persist through IPython sessions, but they are
3177 Your bookmarks persist through IPython sessions, but they are
3195 associated with each profile."""
3178 associated with each profile."""
3196
3179
3197 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3180 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3198 if len(args) > 2:
3181 if len(args) > 2:
3199 raise UsageError("%bookmark: too many arguments")
3182 raise UsageError("%bookmark: too many arguments")
3200
3183
3201 bkms = self.db.get('bookmarks',{})
3184 bkms = self.db.get('bookmarks',{})
3202
3185
3203 if opts.has_key('d'):
3186 if opts.has_key('d'):
3204 try:
3187 try:
3205 todel = args[0]
3188 todel = args[0]
3206 except IndexError:
3189 except IndexError:
3207 raise UsageError(
3190 raise UsageError(
3208 "%bookmark -d: must provide a bookmark to delete")
3191 "%bookmark -d: must provide a bookmark to delete")
3209 else:
3192 else:
3210 try:
3193 try:
3211 del bkms[todel]
3194 del bkms[todel]
3212 except KeyError:
3195 except KeyError:
3213 raise UsageError(
3196 raise UsageError(
3214 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3197 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3215
3198
3216 elif opts.has_key('r'):
3199 elif opts.has_key('r'):
3217 bkms = {}
3200 bkms = {}
3218 elif opts.has_key('l'):
3201 elif opts.has_key('l'):
3219 bks = bkms.keys()
3202 bks = bkms.keys()
3220 bks.sort()
3203 bks.sort()
3221 if bks:
3204 if bks:
3222 size = max(map(len,bks))
3205 size = max(map(len,bks))
3223 else:
3206 else:
3224 size = 0
3207 size = 0
3225 fmt = '%-'+str(size)+'s -> %s'
3208 fmt = '%-'+str(size)+'s -> %s'
3226 print 'Current bookmarks:'
3209 print 'Current bookmarks:'
3227 for bk in bks:
3210 for bk in bks:
3228 print fmt % (bk,bkms[bk])
3211 print fmt % (bk,bkms[bk])
3229 else:
3212 else:
3230 if not args:
3213 if not args:
3231 raise UsageError("%bookmark: You must specify the bookmark name")
3214 raise UsageError("%bookmark: You must specify the bookmark name")
3232 elif len(args)==1:
3215 elif len(args)==1:
3233 bkms[args[0]] = os.getcwd()
3216 bkms[args[0]] = os.getcwd()
3234 elif len(args)==2:
3217 elif len(args)==2:
3235 bkms[args[0]] = args[1]
3218 bkms[args[0]] = args[1]
3236 self.db['bookmarks'] = bkms
3219 self.db['bookmarks'] = bkms
3237
3220
3238 def magic_pycat(self, parameter_s=''):
3221 def magic_pycat(self, parameter_s=''):
3239 """Show a syntax-highlighted file through a pager.
3222 """Show a syntax-highlighted file through a pager.
3240
3223
3241 This magic is similar to the cat utility, but it will assume the file
3224 This magic is similar to the cat utility, but it will assume the file
3242 to be Python source and will show it with syntax highlighting. """
3225 to be Python source and will show it with syntax highlighting. """
3243
3226
3244 try:
3227 try:
3245 filename = get_py_filename(parameter_s)
3228 filename = get_py_filename(parameter_s)
3246 cont = file_read(filename)
3229 cont = file_read(filename)
3247 except IOError:
3230 except IOError:
3248 try:
3231 try:
3249 cont = eval(parameter_s,self.user_ns)
3232 cont = eval(parameter_s,self.user_ns)
3250 except NameError:
3233 except NameError:
3251 cont = None
3234 cont = None
3252 if cont is None:
3235 if cont is None:
3253 print "Error: no such file or variable"
3236 print "Error: no such file or variable"
3254 return
3237 return
3255
3238
3256 page.page(self.shell.pycolorize(cont))
3239 page.page(self.shell.pycolorize(cont))
3257
3240
3258 def _rerun_pasted(self):
3241 def _rerun_pasted(self):
3259 """ Rerun a previously pasted command.
3242 """ Rerun a previously pasted command.
3260 """
3243 """
3261 b = self.user_ns.get('pasted_block', None)
3244 b = self.user_ns.get('pasted_block', None)
3262 if b is None:
3245 if b is None:
3263 raise UsageError('No previous pasted block available')
3246 raise UsageError('No previous pasted block available')
3264 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3247 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3265 exec b in self.user_ns
3248 exec b in self.user_ns
3266
3249
3267 def _get_pasted_lines(self, sentinel):
3250 def _get_pasted_lines(self, sentinel):
3268 """ Yield pasted lines until the user enters the given sentinel value.
3251 """ Yield pasted lines until the user enters the given sentinel value.
3269 """
3252 """
3270 from IPython.core import interactiveshell
3253 from IPython.core import interactiveshell
3271 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3254 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3272 while True:
3255 while True:
3273 l = interactiveshell.raw_input_original(':')
3256 l = interactiveshell.raw_input_original(':')
3274 if l == sentinel:
3257 if l == sentinel:
3275 return
3258 return
3276 else:
3259 else:
3277 yield l
3260 yield l
3278
3261
3279 def _strip_pasted_lines_for_code(self, raw_lines):
3262 def _strip_pasted_lines_for_code(self, raw_lines):
3280 """ Strip non-code parts of a sequence of lines to return a block of
3263 """ Strip non-code parts of a sequence of lines to return a block of
3281 code.
3264 code.
3282 """
3265 """
3283 # Regular expressions that declare text we strip from the input:
3266 # Regular expressions that declare text we strip from the input:
3284 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3267 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3285 r'^\s*(\s?>)+', # Python input prompt
3268 r'^\s*(\s?>)+', # Python input prompt
3286 r'^\s*\.{3,}', # Continuation prompts
3269 r'^\s*\.{3,}', # Continuation prompts
3287 r'^\++',
3270 r'^\++',
3288 ]
3271 ]
3289
3272
3290 strip_from_start = map(re.compile,strip_re)
3273 strip_from_start = map(re.compile,strip_re)
3291
3274
3292 lines = []
3275 lines = []
3293 for l in raw_lines:
3276 for l in raw_lines:
3294 for pat in strip_from_start:
3277 for pat in strip_from_start:
3295 l = pat.sub('',l)
3278 l = pat.sub('',l)
3296 lines.append(l)
3279 lines.append(l)
3297
3280
3298 block = "\n".join(lines) + '\n'
3281 block = "\n".join(lines) + '\n'
3299 #print "block:\n",block
3282 #print "block:\n",block
3300 return block
3283 return block
3301
3284
3302 def _execute_block(self, block, par):
3285 def _execute_block(self, block, par):
3303 """ Execute a block, or store it in a variable, per the user's request.
3286 """ Execute a block, or store it in a variable, per the user's request.
3304 """
3287 """
3305 if not par:
3288 if not par:
3306 b = textwrap.dedent(block)
3289 b = textwrap.dedent(block)
3307 self.user_ns['pasted_block'] = b
3290 self.user_ns['pasted_block'] = b
3308 exec b in self.user_ns
3291 exec b in self.user_ns
3309 else:
3292 else:
3310 self.user_ns[par] = SList(block.splitlines())
3293 self.user_ns[par] = SList(block.splitlines())
3311 print "Block assigned to '%s'" % par
3294 print "Block assigned to '%s'" % par
3312
3295
3313 def magic_cpaste(self, parameter_s=''):
3296 def magic_cpaste(self, parameter_s=''):
3314 """Allows you to paste & execute a pre-formatted code block from clipboard.
3297 """Allows you to paste & execute a pre-formatted code block from clipboard.
3315
3298
3316 You must terminate the block with '--' (two minus-signs) alone on the
3299 You must terminate the block with '--' (two minus-signs) alone on the
3317 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3300 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3318 is the new sentinel for this operation)
3301 is the new sentinel for this operation)
3319
3302
3320 The block is dedented prior to execution to enable execution of method
3303 The block is dedented prior to execution to enable execution of method
3321 definitions. '>' and '+' characters at the beginning of a line are
3304 definitions. '>' and '+' characters at the beginning of a line are
3322 ignored, to allow pasting directly from e-mails, diff files and
3305 ignored, to allow pasting directly from e-mails, diff files and
3323 doctests (the '...' continuation prompt is also stripped). The
3306 doctests (the '...' continuation prompt is also stripped). The
3324 executed block is also assigned to variable named 'pasted_block' for
3307 executed block is also assigned to variable named 'pasted_block' for
3325 later editing with '%edit pasted_block'.
3308 later editing with '%edit pasted_block'.
3326
3309
3327 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3310 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3328 This assigns the pasted block to variable 'foo' as string, without
3311 This assigns the pasted block to variable 'foo' as string, without
3329 dedenting or executing it (preceding >>> and + is still stripped)
3312 dedenting or executing it (preceding >>> and + is still stripped)
3330
3313
3331 '%cpaste -r' re-executes the block previously entered by cpaste.
3314 '%cpaste -r' re-executes the block previously entered by cpaste.
3332
3315
3333 Do not be alarmed by garbled output on Windows (it's a readline bug).
3316 Do not be alarmed by garbled output on Windows (it's a readline bug).
3334 Just press enter and type -- (and press enter again) and the block
3317 Just press enter and type -- (and press enter again) and the block
3335 will be what was just pasted.
3318 will be what was just pasted.
3336
3319
3337 IPython statements (magics, shell escapes) are not supported (yet).
3320 IPython statements (magics, shell escapes) are not supported (yet).
3338
3321
3339 See also
3322 See also
3340 --------
3323 --------
3341 paste: automatically pull code from clipboard.
3324 paste: automatically pull code from clipboard.
3342 """
3325 """
3343
3326
3344 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3327 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3345 par = args.strip()
3328 par = args.strip()
3346 if opts.has_key('r'):
3329 if opts.has_key('r'):
3347 self._rerun_pasted()
3330 self._rerun_pasted()
3348 return
3331 return
3349
3332
3350 sentinel = opts.get('s','--')
3333 sentinel = opts.get('s','--')
3351
3334
3352 block = self._strip_pasted_lines_for_code(
3335 block = self._strip_pasted_lines_for_code(
3353 self._get_pasted_lines(sentinel))
3336 self._get_pasted_lines(sentinel))
3354
3337
3355 self._execute_block(block, par)
3338 self._execute_block(block, par)
3356
3339
3357 def magic_paste(self, parameter_s=''):
3340 def magic_paste(self, parameter_s=''):
3358 """Allows you to paste & execute a pre-formatted code block from clipboard.
3341 """Allows you to paste & execute a pre-formatted code block from clipboard.
3359
3342
3360 The text is pulled directly from the clipboard without user
3343 The text is pulled directly from the clipboard without user
3361 intervention and printed back on the screen before execution (unless
3344 intervention and printed back on the screen before execution (unless
3362 the -q flag is given to force quiet mode).
3345 the -q flag is given to force quiet mode).
3363
3346
3364 The block is dedented prior to execution to enable execution of method
3347 The block is dedented prior to execution to enable execution of method
3365 definitions. '>' and '+' characters at the beginning of a line are
3348 definitions. '>' and '+' characters at the beginning of a line are
3366 ignored, to allow pasting directly from e-mails, diff files and
3349 ignored, to allow pasting directly from e-mails, diff files and
3367 doctests (the '...' continuation prompt is also stripped). The
3350 doctests (the '...' continuation prompt is also stripped). The
3368 executed block is also assigned to variable named 'pasted_block' for
3351 executed block is also assigned to variable named 'pasted_block' for
3369 later editing with '%edit pasted_block'.
3352 later editing with '%edit pasted_block'.
3370
3353
3371 You can also pass a variable name as an argument, e.g. '%paste foo'.
3354 You can also pass a variable name as an argument, e.g. '%paste foo'.
3372 This assigns the pasted block to variable 'foo' as string, without
3355 This assigns the pasted block to variable 'foo' as string, without
3373 dedenting or executing it (preceding >>> and + is still stripped)
3356 dedenting or executing it (preceding >>> and + is still stripped)
3374
3357
3375 Options
3358 Options
3376 -------
3359 -------
3377
3360
3378 -r: re-executes the block previously entered by cpaste.
3361 -r: re-executes the block previously entered by cpaste.
3379
3362
3380 -q: quiet mode: do not echo the pasted text back to the terminal.
3363 -q: quiet mode: do not echo the pasted text back to the terminal.
3381
3364
3382 IPython statements (magics, shell escapes) are not supported (yet).
3365 IPython statements (magics, shell escapes) are not supported (yet).
3383
3366
3384 See also
3367 See also
3385 --------
3368 --------
3386 cpaste: manually paste code into terminal until you mark its end.
3369 cpaste: manually paste code into terminal until you mark its end.
3387 """
3370 """
3388 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3371 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3389 par = args.strip()
3372 par = args.strip()
3390 if opts.has_key('r'):
3373 if opts.has_key('r'):
3391 self._rerun_pasted()
3374 self._rerun_pasted()
3392 return
3375 return
3393
3376
3394 text = self.shell.hooks.clipboard_get()
3377 text = self.shell.hooks.clipboard_get()
3395 block = self._strip_pasted_lines_for_code(text.splitlines())
3378 block = self._strip_pasted_lines_for_code(text.splitlines())
3396
3379
3397 # By default, echo back to terminal unless quiet mode is requested
3380 # By default, echo back to terminal unless quiet mode is requested
3398 if not opts.has_key('q'):
3381 if not opts.has_key('q'):
3399 write = self.shell.write
3382 write = self.shell.write
3400 write(self.shell.pycolorize(block))
3383 write(self.shell.pycolorize(block))
3401 if not block.endswith('\n'):
3384 if not block.endswith('\n'):
3402 write('\n')
3385 write('\n')
3403 write("## -- End pasted text --\n")
3386 write("## -- End pasted text --\n")
3404
3387
3405 self._execute_block(block, par)
3388 self._execute_block(block, par)
3406
3389
3407 def magic_quickref(self,arg):
3390 def magic_quickref(self,arg):
3408 """ Show a quick reference sheet """
3391 """ Show a quick reference sheet """
3409 import IPython.core.usage
3392 import IPython.core.usage
3410 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3393 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3411
3394
3412 page.page(qr)
3395 page.page(qr)
3413
3396
3414 def magic_doctest_mode(self,parameter_s=''):
3397 def magic_doctest_mode(self,parameter_s=''):
3415 """Toggle doctest mode on and off.
3398 """Toggle doctest mode on and off.
3416
3399
3417 This mode allows you to toggle the prompt behavior between normal
3400 This mode allows you to toggle the prompt behavior between normal
3418 IPython prompts and ones that are as similar to the default IPython
3401 IPython prompts and ones that are as similar to the default IPython
3419 interpreter as possible.
3402 interpreter as possible.
3420
3403
3421 It also supports the pasting of code snippets that have leading '>>>'
3404 It also supports the pasting of code snippets that have leading '>>>'
3422 and '...' prompts in them. This means that you can paste doctests from
3405 and '...' prompts in them. This means that you can paste doctests from
3423 files or docstrings (even if they have leading whitespace), and the
3406 files or docstrings (even if they have leading whitespace), and the
3424 code will execute correctly. You can then use '%history -tn' to see
3407 code will execute correctly. You can then use '%history -tn' to see
3425 the translated history without line numbers; this will give you the
3408 the translated history without line numbers; this will give you the
3426 input after removal of all the leading prompts and whitespace, which
3409 input after removal of all the leading prompts and whitespace, which
3427 can be pasted back into an editor.
3410 can be pasted back into an editor.
3428
3411
3429 With these features, you can switch into this mode easily whenever you
3412 With these features, you can switch into this mode easily whenever you
3430 need to do testing and changes to doctests, without having to leave
3413 need to do testing and changes to doctests, without having to leave
3431 your existing IPython session.
3414 your existing IPython session.
3432 """
3415 """
3433
3416
3434 from IPython.utils.ipstruct import Struct
3417 from IPython.utils.ipstruct import Struct
3435
3418
3436 # Shorthands
3419 # Shorthands
3437 shell = self.shell
3420 shell = self.shell
3438 oc = shell.displayhook
3421 oc = shell.displayhook
3439 meta = shell.meta
3422 meta = shell.meta
3440 # dstore is a data store kept in the instance metadata bag to track any
3423 # dstore is a data store kept in the instance metadata bag to track any
3441 # changes we make, so we can undo them later.
3424 # changes we make, so we can undo them later.
3442 dstore = meta.setdefault('doctest_mode',Struct())
3425 dstore = meta.setdefault('doctest_mode',Struct())
3443 save_dstore = dstore.setdefault
3426 save_dstore = dstore.setdefault
3444
3427
3445 # save a few values we'll need to recover later
3428 # save a few values we'll need to recover later
3446 mode = save_dstore('mode',False)
3429 mode = save_dstore('mode',False)
3447 save_dstore('rc_pprint',shell.pprint)
3430 save_dstore('rc_pprint',shell.pprint)
3448 save_dstore('xmode',shell.InteractiveTB.mode)
3431 save_dstore('xmode',shell.InteractiveTB.mode)
3449 save_dstore('rc_separate_out',shell.separate_out)
3432 save_dstore('rc_separate_out',shell.separate_out)
3450 save_dstore('rc_separate_out2',shell.separate_out2)
3433 save_dstore('rc_separate_out2',shell.separate_out2)
3451 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3434 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3452 save_dstore('rc_separate_in',shell.separate_in)
3435 save_dstore('rc_separate_in',shell.separate_in)
3453
3436
3454 if mode == False:
3437 if mode == False:
3455 # turn on
3438 # turn on
3456 oc.prompt1.p_template = '>>> '
3439 oc.prompt1.p_template = '>>> '
3457 oc.prompt2.p_template = '... '
3440 oc.prompt2.p_template = '... '
3458 oc.prompt_out.p_template = ''
3441 oc.prompt_out.p_template = ''
3459
3442
3460 # Prompt separators like plain python
3443 # Prompt separators like plain python
3461 oc.input_sep = oc.prompt1.sep = ''
3444 oc.input_sep = oc.prompt1.sep = ''
3462 oc.output_sep = ''
3445 oc.output_sep = ''
3463 oc.output_sep2 = ''
3446 oc.output_sep2 = ''
3464
3447
3465 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3448 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3466 oc.prompt_out.pad_left = False
3449 oc.prompt_out.pad_left = False
3467
3450
3468 shell.pprint = False
3451 shell.pprint = False
3469
3452
3470 shell.magic_xmode('Plain')
3453 shell.magic_xmode('Plain')
3471
3454
3472 else:
3455 else:
3473 # turn off
3456 # turn off
3474 oc.prompt1.p_template = shell.prompt_in1
3457 oc.prompt1.p_template = shell.prompt_in1
3475 oc.prompt2.p_template = shell.prompt_in2
3458 oc.prompt2.p_template = shell.prompt_in2
3476 oc.prompt_out.p_template = shell.prompt_out
3459 oc.prompt_out.p_template = shell.prompt_out
3477
3460
3478 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3461 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3479
3462
3480 oc.output_sep = dstore.rc_separate_out
3463 oc.output_sep = dstore.rc_separate_out
3481 oc.output_sep2 = dstore.rc_separate_out2
3464 oc.output_sep2 = dstore.rc_separate_out2
3482
3465
3483 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3466 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3484 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3467 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3485
3468
3486 shell.pprint = dstore.rc_pprint
3469 shell.pprint = dstore.rc_pprint
3487
3470
3488 shell.magic_xmode(dstore.xmode)
3471 shell.magic_xmode(dstore.xmode)
3489
3472
3490 # Store new mode and inform
3473 # Store new mode and inform
3491 dstore.mode = bool(1-int(mode))
3474 dstore.mode = bool(1-int(mode))
3492 print 'Doctest mode is:',
3475 print 'Doctest mode is:',
3493 print ['OFF','ON'][dstore.mode]
3476 print ['OFF','ON'][dstore.mode]
3494
3477
3495 def magic_gui(self, parameter_s=''):
3478 def magic_gui(self, parameter_s=''):
3496 """Enable or disable IPython GUI event loop integration.
3479 """Enable or disable IPython GUI event loop integration.
3497
3480
3498 %gui [-a] [GUINAME]
3481 %gui [-a] [GUINAME]
3499
3482
3500 This magic replaces IPython's threaded shells that were activated
3483 This magic replaces IPython's threaded shells that were activated
3501 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3484 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3502 can now be enabled, disabled and swtiched at runtime and keyboard
3485 can now be enabled, disabled and swtiched at runtime and keyboard
3503 interrupts should work without any problems. The following toolkits
3486 interrupts should work without any problems. The following toolkits
3504 are supported: wxPython, PyQt4, PyGTK, and Tk::
3487 are supported: wxPython, PyQt4, PyGTK, and Tk::
3505
3488
3506 %gui wx # enable wxPython event loop integration
3489 %gui wx # enable wxPython event loop integration
3507 %gui qt4|qt # enable PyQt4 event loop integration
3490 %gui qt4|qt # enable PyQt4 event loop integration
3508 %gui gtk # enable PyGTK event loop integration
3491 %gui gtk # enable PyGTK event loop integration
3509 %gui tk # enable Tk event loop integration
3492 %gui tk # enable Tk event loop integration
3510 %gui # disable all event loop integration
3493 %gui # disable all event loop integration
3511
3494
3512 WARNING: after any of these has been called you can simply create
3495 WARNING: after any of these has been called you can simply create
3513 an application object, but DO NOT start the event loop yourself, as
3496 an application object, but DO NOT start the event loop yourself, as
3514 we have already handled that.
3497 we have already handled that.
3515
3498
3516 If you want us to create an appropriate application object add the
3499 If you want us to create an appropriate application object add the
3517 "-a" flag to your command::
3500 "-a" flag to your command::
3518
3501
3519 %gui -a wx
3502 %gui -a wx
3520
3503
3521 This is highly recommended for most users.
3504 This is highly recommended for most users.
3522 """
3505 """
3523 opts, arg = self.parse_options(parameter_s,'a')
3506 opts, arg = self.parse_options(parameter_s,'a')
3524 if arg=='': arg = None
3507 if arg=='': arg = None
3525 return enable_gui(arg, 'a' in opts)
3508 return enable_gui(arg, 'a' in opts)
3526
3509
3527 def magic_load_ext(self, module_str):
3510 def magic_load_ext(self, module_str):
3528 """Load an IPython extension by its module name."""
3511 """Load an IPython extension by its module name."""
3529 return self.extension_manager.load_extension(module_str)
3512 return self.extension_manager.load_extension(module_str)
3530
3513
3531 def magic_unload_ext(self, module_str):
3514 def magic_unload_ext(self, module_str):
3532 """Unload an IPython extension by its module name."""
3515 """Unload an IPython extension by its module name."""
3533 self.extension_manager.unload_extension(module_str)
3516 self.extension_manager.unload_extension(module_str)
3534
3517
3535 def magic_reload_ext(self, module_str):
3518 def magic_reload_ext(self, module_str):
3536 """Reload an IPython extension by its module name."""
3519 """Reload an IPython extension by its module name."""
3537 self.extension_manager.reload_extension(module_str)
3520 self.extension_manager.reload_extension(module_str)
3538
3521
3539 @testdec.skip_doctest
3522 @testdec.skip_doctest
3540 def magic_install_profiles(self, s):
3523 def magic_install_profiles(self, s):
3541 """Install the default IPython profiles into the .ipython dir.
3524 """Install the default IPython profiles into the .ipython dir.
3542
3525
3543 If the default profiles have already been installed, they will not
3526 If the default profiles have already been installed, they will not
3544 be overwritten. You can force overwriting them by using the ``-o``
3527 be overwritten. You can force overwriting them by using the ``-o``
3545 option::
3528 option::
3546
3529
3547 In [1]: %install_profiles -o
3530 In [1]: %install_profiles -o
3548 """
3531 """
3549 if '-o' in s:
3532 if '-o' in s:
3550 overwrite = True
3533 overwrite = True
3551 else:
3534 else:
3552 overwrite = False
3535 overwrite = False
3553 from IPython.config import profile
3536 from IPython.config import profile
3554 profile_dir = os.path.split(profile.__file__)[0]
3537 profile_dir = os.path.split(profile.__file__)[0]
3555 ipython_dir = self.ipython_dir
3538 ipython_dir = self.ipython_dir
3556 files = os.listdir(profile_dir)
3539 files = os.listdir(profile_dir)
3557
3540
3558 to_install = []
3541 to_install = []
3559 for f in files:
3542 for f in files:
3560 if f.startswith('ipython_config'):
3543 if f.startswith('ipython_config'):
3561 src = os.path.join(profile_dir, f)
3544 src = os.path.join(profile_dir, f)
3562 dst = os.path.join(ipython_dir, f)
3545 dst = os.path.join(ipython_dir, f)
3563 if (not os.path.isfile(dst)) or overwrite:
3546 if (not os.path.isfile(dst)) or overwrite:
3564 to_install.append((f, src, dst))
3547 to_install.append((f, src, dst))
3565 if len(to_install)>0:
3548 if len(to_install)>0:
3566 print "Installing profiles to: ", ipython_dir
3549 print "Installing profiles to: ", ipython_dir
3567 for (f, src, dst) in to_install:
3550 for (f, src, dst) in to_install:
3568 shutil.copy(src, dst)
3551 shutil.copy(src, dst)
3569 print " %s" % f
3552 print " %s" % f
3570
3553
3571 def magic_install_default_config(self, s):
3554 def magic_install_default_config(self, s):
3572 """Install IPython's default config file into the .ipython dir.
3555 """Install IPython's default config file into the .ipython dir.
3573
3556
3574 If the default config file (:file:`ipython_config.py`) is already
3557 If the default config file (:file:`ipython_config.py`) is already
3575 installed, it will not be overwritten. You can force overwriting
3558 installed, it will not be overwritten. You can force overwriting
3576 by using the ``-o`` option::
3559 by using the ``-o`` option::
3577
3560
3578 In [1]: %install_default_config
3561 In [1]: %install_default_config
3579 """
3562 """
3580 if '-o' in s:
3563 if '-o' in s:
3581 overwrite = True
3564 overwrite = True
3582 else:
3565 else:
3583 overwrite = False
3566 overwrite = False
3584 from IPython.config import default
3567 from IPython.config import default
3585 config_dir = os.path.split(default.__file__)[0]
3568 config_dir = os.path.split(default.__file__)[0]
3586 ipython_dir = self.ipython_dir
3569 ipython_dir = self.ipython_dir
3587 default_config_file_name = 'ipython_config.py'
3570 default_config_file_name = 'ipython_config.py'
3588 src = os.path.join(config_dir, default_config_file_name)
3571 src = os.path.join(config_dir, default_config_file_name)
3589 dst = os.path.join(ipython_dir, default_config_file_name)
3572 dst = os.path.join(ipython_dir, default_config_file_name)
3590 if (not os.path.isfile(dst)) or overwrite:
3573 if (not os.path.isfile(dst)) or overwrite:
3591 shutil.copy(src, dst)
3574 shutil.copy(src, dst)
3592 print "Installing default config file: %s" % dst
3575 print "Installing default config file: %s" % dst
3593
3576
3594 # Pylab support: simple wrappers that activate pylab, load gui input
3577 # Pylab support: simple wrappers that activate pylab, load gui input
3595 # handling and modify slightly %run
3578 # handling and modify slightly %run
3596
3579
3597 @testdec.skip_doctest
3580 @testdec.skip_doctest
3598 def _pylab_magic_run(self, parameter_s=''):
3581 def _pylab_magic_run(self, parameter_s=''):
3599 Magic.magic_run(self, parameter_s,
3582 Magic.magic_run(self, parameter_s,
3600 runner=mpl_runner(self.shell.safe_execfile))
3583 runner=mpl_runner(self.shell.safe_execfile))
3601
3584
3602 _pylab_magic_run.__doc__ = magic_run.__doc__
3585 _pylab_magic_run.__doc__ = magic_run.__doc__
3603
3586
3604 @testdec.skip_doctest
3587 @testdec.skip_doctest
3605 def magic_pylab(self, s):
3588 def magic_pylab(self, s):
3606 """Load numpy and matplotlib to work interactively.
3589 """Load numpy and matplotlib to work interactively.
3607
3590
3608 %pylab [GUINAME]
3591 %pylab [GUINAME]
3609
3592
3610 This function lets you activate pylab (matplotlib, numpy and
3593 This function lets you activate pylab (matplotlib, numpy and
3611 interactive support) at any point during an IPython session.
3594 interactive support) at any point during an IPython session.
3612
3595
3613 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3596 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3614 pylab and mlab, as well as all names from numpy and pylab.
3597 pylab and mlab, as well as all names from numpy and pylab.
3615
3598
3616 Parameters
3599 Parameters
3617 ----------
3600 ----------
3618 guiname : optional
3601 guiname : optional
3619 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3602 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3620 'tk'). If given, the corresponding Matplotlib backend is used,
3603 'tk'). If given, the corresponding Matplotlib backend is used,
3621 otherwise matplotlib's default (which you can override in your
3604 otherwise matplotlib's default (which you can override in your
3622 matplotlib config file) is used.
3605 matplotlib config file) is used.
3623
3606
3624 Examples
3607 Examples
3625 --------
3608 --------
3626 In this case, where the MPL default is TkAgg:
3609 In this case, where the MPL default is TkAgg:
3627 In [2]: %pylab
3610 In [2]: %pylab
3628
3611
3629 Welcome to pylab, a matplotlib-based Python environment.
3612 Welcome to pylab, a matplotlib-based Python environment.
3630 Backend in use: TkAgg
3613 Backend in use: TkAgg
3631 For more information, type 'help(pylab)'.
3614 For more information, type 'help(pylab)'.
3632
3615
3633 But you can explicitly request a different backend:
3616 But you can explicitly request a different backend:
3634 In [3]: %pylab qt
3617 In [3]: %pylab qt
3635
3618
3636 Welcome to pylab, a matplotlib-based Python environment.
3619 Welcome to pylab, a matplotlib-based Python environment.
3637 Backend in use: Qt4Agg
3620 Backend in use: Qt4Agg
3638 For more information, type 'help(pylab)'.
3621 For more information, type 'help(pylab)'.
3639 """
3622 """
3640 self.shell.enable_pylab(s)
3623 self.shell.enable_pylab(s)
3641
3624
3642 def magic_tb(self, s):
3625 def magic_tb(self, s):
3643 """Print the last traceback with the currently active exception mode.
3626 """Print the last traceback with the currently active exception mode.
3644
3627
3645 See %xmode for changing exception reporting modes."""
3628 See %xmode for changing exception reporting modes."""
3646 self.shell.showtraceback()
3629 self.shell.showtraceback()
3647
3630
3648 # end Magic
3631 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now