##// END OF EJS Templates
Merging upstream changes.
Brian Granger -
r1784:ede4ef79 merge
parent child Browse files
Show More
@@ -1,87 +1,88 b''
1 """ 'editor' hooks for common editors that work well with ipython
1 """ 'editor' hooks for common editors that work well with ipython
2
2
3 They should honor the line number argument, at least.
3 They should honor the line number argument, at least.
4
4
5 Contributions are *very* welcome.
5 Contributions are *very* welcome.
6 """
6 """
7
7
8 import IPython.ipapi
8 import IPython.ipapi
9 ip = IPython.ipapi.get()
9 ip = IPython.ipapi.get()
10
10
11 from IPython.Itpl import itplns
11 from IPython.Itpl import itplns
12 import os
12 import os
13
13
14 def install_editor(run_template, wait = False):
14 def install_editor(run_template, wait = False):
15 """ Gets a template in format "myeditor bah bah $file bah bah $line"
15 """ Gets a template in format "myeditor bah bah $file bah bah $line"
16
16
17 $file will be replaced by file name, $line by line number (or 0).
17 $file will be replaced by file name, $line by line number (or 0).
18 Installs the editor that is called by IPython, instead of the default
18 Installs the editor that is called by IPython, instead of the default
19 notepad or vi.
19 notepad or vi.
20
20
21 If wait is true, wait until the user presses enter before returning,
21 If wait is true, wait until the user presses enter before returning,
22 to facilitate non-blocking editors that exit immediately after
22 to facilitate non-blocking editors that exit immediately after
23 the call.
23 the call.
24 """
24 """
25
25
26 def call_editor(self, file, line=0):
26 def call_editor(self, file, line=0):
27 if line is None:
27 if line is None:
28 line = 0
28 line = 0
29 cmd = itplns(run_template, locals())
29 cmd = itplns(run_template, locals())
30 print ">",cmd
30 print ">",cmd
31 os.system(cmd)
31 if os.system(cmd) != 0:
32 raise IPython.ipapi.TryNext()
32 if wait:
33 if wait:
33 raw_input("Press Enter when done editing:")
34 raw_input("Press Enter when done editing:")
34
35
35 ip.set_hook('editor',call_editor)
36 ip.set_hook('editor',call_editor)
36
37
37
38
38 # in these, exe is always the path/name of the executable. Useful
39 # in these, exe is always the path/name of the executable. Useful
39 # if you don't have the editor directory in your path
40 # if you don't have the editor directory in your path
40
41
41 def komodo(exe = 'komodo'):
42 def komodo(exe = 'komodo'):
42 """ Activestate Komodo [Edit] """
43 """ Activestate Komodo [Edit] """
43 install_editor(exe + ' -l $line "$file"', wait = True)
44 install_editor(exe + ' -l $line "$file"', wait = True)
44
45
45 def scite(exe = "scite"):
46 def scite(exe = "scite"):
46 """ SciTE or Sc1 """
47 """ SciTE or Sc1 """
47 install_editor(exe + ' "$file" -goto:$line')
48 install_editor(exe + ' "$file" -goto:$line')
48
49
49 def notepadplusplus(exe = 'notepad++'):
50 def notepadplusplus(exe = 'notepad++'):
50 """ Notepad++ http://notepad-plus.sourceforge.net """
51 """ Notepad++ http://notepad-plus.sourceforge.net """
51 install_editor(exe + ' -n$line "$file"')
52 install_editor(exe + ' -n$line "$file"')
52
53
53 def jed(exe = 'jed'):
54 def jed(exe = 'jed'):
54 """ JED, the lightweight emacsish editor """
55 """ JED, the lightweight emacsish editor """
55 install_editor(exe + ' +$line "$file"')
56 install_editor(exe + ' +$line "$file"')
56
57
57 def idle(exe = None):
58 def idle(exe = None):
58 """ Idle, the editor bundled with python
59 """ Idle, the editor bundled with python
59
60
60 Should be pretty smart about finding the executable.
61 Should be pretty smart about finding the executable.
61 """
62 """
62 if exe is None:
63 if exe is None:
63 import idlelib
64 import idlelib
64 p = os.path.dirname(idlelib.__file__)
65 p = os.path.dirname(idlelib.__file__)
65 exe = p + '/idle.py'
66 exe = p + '/idle.py'
66 install_editor(exe + ' "$file"')
67 install_editor(exe + ' "$file"')
67
68
68 def mate(exe = 'mate'):
69 def mate(exe = 'mate'):
69 """ TextMate, the missing editor"""
70 """ TextMate, the missing editor"""
70 install_editor(exe + ' -w -l $line "$file"')
71 install_editor(exe + ' -w -l $line "$file"')
71
72
72 # these are untested, report any problems
73 # these are untested, report any problems
73
74
74 def emacs(exe = 'emacs'):
75 def emacs(exe = 'emacs'):
75 install_editor(exe + ' +$line "$file"')
76 install_editor(exe + ' +$line "$file"')
76
77
77 def gnuclient(exe= 'gnuclient'):
78 def gnuclient(exe= 'gnuclient'):
78 install_editor(exe + ' -nw +$line "$file"')
79 install_editor(exe + ' -nw +$line "$file"')
79
80
80 def crimson_editor(exe = 'cedt.exe'):
81 def crimson_editor(exe = 'cedt.exe'):
81 install_editor(exe + ' /L:$line "$file"')
82 install_editor(exe + ' /L:$line "$file"')
82
83
83 def kate(exe = 'kate'):
84 def kate(exe = 'kate'):
84 install_editor(exe + ' -u -l $line "$file"')
85 install_editor(exe + ' -u -l $line "$file"')
85
86
86
87
87 No newline at end of file
88
@@ -1,270 +1,270 b''
1 """Shell mode for IPython.
1 """Shell mode for IPython.
2
2
3 Start ipython in shell mode by invoking "ipython -p sh"
3 Start ipython in shell mode by invoking "ipython -p sh"
4
4
5 (the old version, "ipython -p pysh" still works but this is the more "modern"
5 (the old version, "ipython -p pysh" still works but this is the more "modern"
6 shell mode and is recommended for users who don't care about pysh-mode
6 shell mode and is recommended for users who don't care about pysh-mode
7 compatibility)
7 compatibility)
8 """
8 """
9
9
10 from IPython import ipapi
10 from IPython import ipapi
11 import os,textwrap
11 import os,re,textwrap
12
12
13 # The import below effectively obsoletes your old-style ipythonrc[.ini],
13 # The import below effectively obsoletes your old-style ipythonrc[.ini],
14 # so consider yourself warned!
14 # so consider yourself warned!
15
15
16 import ipy_defaults
16 import ipy_defaults
17
17
18 def main():
18 def main():
19 ip = ipapi.get()
19 ip = ipapi.get()
20 o = ip.options
20 o = ip.options
21 # autocall to "full" mode (smart mode is default, I like full mode)
21 # autocall to "full" mode (smart mode is default, I like full mode)
22
22
23 o.autocall = 2
23 o.autocall = 2
24
24
25 # Jason Orendorff's path class is handy to have in user namespace
25 # Jason Orendorff's path class is handy to have in user namespace
26 # if you are doing shell-like stuff
26 # if you are doing shell-like stuff
27 try:
27 try:
28 ip.ex("from IPython.external.path import path" )
28 ip.ex("from IPython.external.path import path" )
29 except ImportError:
29 except ImportError:
30 pass
30 pass
31
31
32 # beefed up %env is handy in shell mode
32 # beefed up %env is handy in shell mode
33 import envpersist
33 import envpersist
34
34
35 # To see where mycmd resides (in path/aliases), do %which mycmd
35 # To see where mycmd resides (in path/aliases), do %which mycmd
36 import ipy_which
36 import ipy_which
37
37
38 # tab completers for hg, svn, ...
38 # tab completers for hg, svn, ...
39 import ipy_app_completers
39 import ipy_app_completers
40
40
41 # To make executables foo and bar in mybin usable without PATH change, do:
41 # To make executables foo and bar in mybin usable without PATH change, do:
42 # %rehashdir c:/mybin
42 # %rehashdir c:/mybin
43 # %store foo
43 # %store foo
44 # %store bar
44 # %store bar
45 import ipy_rehashdir
45 import ipy_rehashdir
46
46
47 # does not work without subprocess module!
47 # does not work without subprocess module!
48 #import ipy_signals
48 #import ipy_signals
49
49
50 ip.ex('import os')
50 ip.ex('import os')
51 ip.ex("def up(): os.chdir('..')")
51 ip.ex("def up(): os.chdir('..')")
52 ip.user_ns['LA'] = LastArgFinder()
52 ip.user_ns['LA'] = LastArgFinder()
53
53
54 # You can assign to _prompt_title variable
54 # You can assign to _prompt_title variable
55 # to provide some extra information for prompt
55 # to provide some extra information for prompt
56 # (e.g. the current mode, host/username...)
56 # (e.g. the current mode, host/username...)
57
57
58 ip.user_ns['_prompt_title'] = ''
58 ip.user_ns['_prompt_title'] = ''
59
59
60 # Nice prompt
60 # Nice prompt
61 o.prompt_in1= r'\C_Green${_prompt_title}\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> '
61 o.prompt_in1= r'\C_Green${_prompt_title}\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> '
62 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> '
62 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> '
63 o.prompt_out= '<\#> '
63 o.prompt_out= '<\#> '
64
64
65 from IPython import Release
65 from IPython import Release
66
66
67 import sys
67 import sys
68 # Non-chatty banner
68 # Non-chatty banner
69 o.banner = "IPython %s [on Py %s]\n" % (Release.version,sys.version.split(None,1)[0])
69 o.banner = "IPython %s [on Py %s]\n" % (Release.version,sys.version.split(None,1)[0])
70
70
71
71
72 ip.IP.default_option('cd','-q')
72 ip.IP.default_option('cd','-q')
73 ip.IP.default_option('macro', '-r')
73 ip.IP.default_option('macro', '-r')
74 # If you only rarely want to execute the things you %edit...
74 # If you only rarely want to execute the things you %edit...
75 #ip.IP.default_option('edit','-x')
75 #ip.IP.default_option('edit','-x')
76
76
77
77
78 o.prompts_pad_left="1"
78 o.prompts_pad_left="1"
79 # Remove all blank lines in between prompts, like a normal shell.
79 # Remove all blank lines in between prompts, like a normal shell.
80 o.separate_in="0"
80 o.separate_in="0"
81 o.separate_out="0"
81 o.separate_out="0"
82 o.separate_out2="0"
82 o.separate_out2="0"
83
83
84 # now alias all syscommands
84 # now alias all syscommands
85
85
86 db = ip.db
86 db = ip.db
87
87
88 syscmds = db.get("syscmdlist",[] )
88 syscmds = db.get("syscmdlist",[] )
89 if not syscmds:
89 if not syscmds:
90 print textwrap.dedent("""
90 print textwrap.dedent("""
91 System command list not initialized, probably the first run...
91 System command list not initialized, probably the first run...
92 running %rehashx to refresh the command list. Run %rehashx
92 running %rehashx to refresh the command list. Run %rehashx
93 again to refresh command list (after installing new software etc.)
93 again to refresh command list (after installing new software etc.)
94 """)
94 """)
95 ip.magic('rehashx')
95 ip.magic('rehashx')
96 syscmds = db.get("syscmdlist")
96 syscmds = db.get("syscmdlist")
97
97
98 # lowcase aliases on win32 only
98 # lowcase aliases on win32 only
99 if os.name == 'posix':
99 if os.name == 'posix':
100 mapper = lambda s:s
100 mapper = lambda s:s
101 else:
101 else:
102 def mapper(s): return s.lower()
102 def mapper(s): return s.lower()
103
103
104 for cmd in syscmds:
104 for cmd in syscmds:
105 # print "sys",cmd #dbg
105 # print "sys",cmd #dbg
106 noext, ext = os.path.splitext(cmd)
106 noext, ext = os.path.splitext(cmd)
107 if ext.lower() == '.exe':
107 if ext.lower() == '.exe':
108 cmd = noext
108 cmd = noext
109
109
110 key = mapper(cmd)
110 key = mapper(cmd)
111 if key not in ip.IP.alias_table:
111 if key not in ip.IP.alias_table:
112 # Dots will be removed from alias names, since ipython
112 # Dots will be removed from alias names, since ipython
113 # assumes names with dots to be python code
113 # assumes names with dots to be python code
114
114
115 ip.defalias(key.replace('.',''), cmd)
115 ip.defalias(key.replace('.',''), cmd)
116
116
117 # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more
117 # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more
118 ip.load("IPython.external.mglob")
118 ip.load("IPython.external.mglob")
119
119
120 # win32 is crippled w/o cygwin, try to help it a little bit
120 # win32 is crippled w/o cygwin, try to help it a little bit
121 if sys.platform == 'win32':
121 if sys.platform == 'win32':
122 if 'cygwin' in os.environ['PATH'].lower():
122 if 'cygwin' in os.environ['PATH'].lower():
123 # use the colors of cygwin ls (recommended)
123 # use the colors of cygwin ls (recommended)
124 ip.defalias('d', 'ls -F --color=auto')
124 ip.defalias('d', 'ls -F --color=auto')
125 else:
125 else:
126 # get icp, imv, imkdir, igrep, irm,...
126 # get icp, imv, imkdir, igrep, irm,...
127 ip.load('ipy_fsops')
127 ip.load('ipy_fsops')
128
128
129 # and the next best thing to real 'ls -F'
129 # and the next best thing to real 'ls -F'
130 ip.defalias('d','dir /w /og /on')
130 ip.defalias('d','dir /w /og /on')
131
131
132 ip.set_hook('input_prefilter', dotslash_prefilter_f)
132 ip.set_hook('input_prefilter', slash_prefilter_f)
133 extend_shell_behavior(ip)
133 extend_shell_behavior(ip)
134
134
135 class LastArgFinder:
135 class LastArgFinder:
136 """ Allow $LA to work as "last argument of previous command", like $! in bash
136 """ Allow $LA to work as "last argument of previous command", like $! in bash
137
137
138 To call this in normal IPython code, do LA()
138 To call this in normal IPython code, do LA()
139 """
139 """
140 def __call__(self, hist_idx = None):
140 def __call__(self, hist_idx = None):
141 ip = ipapi.get()
141 ip = ipapi.get()
142 if hist_idx is None:
142 if hist_idx is None:
143 return str(self)
143 return str(self)
144 return ip.IP.input_hist_raw[hist_idx].strip().split()[-1]
144 return ip.IP.input_hist_raw[hist_idx].strip().split()[-1]
145 def __str__(self):
145 def __str__(self):
146 ip = ipapi.get()
146 ip = ipapi.get()
147 for cmd in reversed(ip.IP.input_hist_raw):
147 for cmd in reversed(ip.IP.input_hist_raw):
148 parts = cmd.strip().split()
148 parts = cmd.strip().split()
149 if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']:
149 if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']:
150 continue
150 continue
151 return parts[-1]
151 return parts[-1]
152 return ""
152 return ""
153
153
154 def dotslash_prefilter_f(self,line):
154 def slash_prefilter_f(self,line):
155 """ ./foo now runs foo as system command
155 """ ./foo, ~/foo and /bin/foo now run foo as system command
156
156
157 Removes the need for doing !./foo
157 Removes the need for doing !./foo, !~/foo or !/bin/foo
158 """
158 """
159 import IPython.genutils
159 import IPython.genutils
160 if line.startswith("./"):
160 if re.match('(?:[.~]|/[a-zA-Z_0-9]+)/', line):
161 return "_ip.system(" + IPython.genutils.make_quoted_expr(line)+")"
161 return "_ip.system(" + IPython.genutils.make_quoted_expr(line)+")"
162 raise ipapi.TryNext
162 raise ipapi.TryNext
163
163
164 # XXX You do not need to understand the next function!
164 # XXX You do not need to understand the next function!
165 # This should probably be moved out of profile
165 # This should probably be moved out of profile
166
166
167 def extend_shell_behavior(ip):
167 def extend_shell_behavior(ip):
168
168
169 # Instead of making signature a global variable tie it to IPSHELL.
169 # Instead of making signature a global variable tie it to IPSHELL.
170 # In future if it is required to distinguish between different
170 # In future if it is required to distinguish between different
171 # shells we can assign a signature per shell basis
171 # shells we can assign a signature per shell basis
172 ip.IP.__sig__ = 0xa005
172 ip.IP.__sig__ = 0xa005
173 # mark the IPSHELL with this signature
173 # mark the IPSHELL with this signature
174 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
174 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
175
175
176 from IPython.Itpl import ItplNS
176 from IPython.Itpl import ItplNS
177 from IPython.genutils import shell
177 from IPython.genutils import shell
178 # utility to expand user variables via Itpl
178 # utility to expand user variables via Itpl
179 # xxx do something sensible with depth?
179 # xxx do something sensible with depth?
180 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
180 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
181 str(ItplNS(cmd, ip.IP.user_ns, get_locals()))
181 str(ItplNS(cmd, ip.IP.user_ns, get_locals()))
182
182
183 def get_locals():
183 def get_locals():
184 """ Substituting a variable through Itpl deep inside the IPSHELL stack
184 """ Substituting a variable through Itpl deep inside the IPSHELL stack
185 requires the knowledge of all the variables in scope upto the last
185 requires the knowledge of all the variables in scope upto the last
186 IPSHELL frame. This routine simply merges all the local variables
186 IPSHELL frame. This routine simply merges all the local variables
187 on the IPSHELL stack without worrying about their scope rules
187 on the IPSHELL stack without worrying about their scope rules
188 """
188 """
189 import sys
189 import sys
190 # note lambda expression constitues a function call
190 # note lambda expression constitues a function call
191 # hence fno should be incremented by one
191 # hence fno should be incremented by one
192 getsig = lambda fno: sys._getframe(fno+1).f_globals \
192 getsig = lambda fno: sys._getframe(fno+1).f_globals \
193 ['__builtins__'].__dict__['__sig__']
193 ['__builtins__'].__dict__['__sig__']
194 getlvars = lambda fno: sys._getframe(fno+1).f_locals
194 getlvars = lambda fno: sys._getframe(fno+1).f_locals
195 # trackback until we enter the IPSHELL
195 # trackback until we enter the IPSHELL
196 frame_no = 1
196 frame_no = 1
197 sig = ip.IP.__sig__
197 sig = ip.IP.__sig__
198 fsig = ~sig
198 fsig = ~sig
199 while fsig != sig :
199 while fsig != sig :
200 try:
200 try:
201 fsig = getsig(frame_no)
201 fsig = getsig(frame_no)
202 except (AttributeError, KeyError):
202 except (AttributeError, KeyError):
203 frame_no += 1
203 frame_no += 1
204 except ValueError:
204 except ValueError:
205 # stack is depleted
205 # stack is depleted
206 # call did not originate from IPSHELL
206 # call did not originate from IPSHELL
207 return {}
207 return {}
208 first_frame = frame_no
208 first_frame = frame_no
209 # walk further back until we exit from IPSHELL or deplete stack
209 # walk further back until we exit from IPSHELL or deplete stack
210 try:
210 try:
211 while(sig == getsig(frame_no+1)):
211 while(sig == getsig(frame_no+1)):
212 frame_no += 1
212 frame_no += 1
213 except (AttributeError, KeyError, ValueError):
213 except (AttributeError, KeyError, ValueError):
214 pass
214 pass
215 # merge the locals from top down hence overriding
215 # merge the locals from top down hence overriding
216 # any re-definitions of variables, functions etc.
216 # any re-definitions of variables, functions etc.
217 lvars = {}
217 lvars = {}
218 for fno in range(frame_no, first_frame-1, -1):
218 for fno in range(frame_no, first_frame-1, -1):
219 lvars.update(getlvars(fno))
219 lvars.update(getlvars(fno))
220 #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg
220 #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg
221 return lvars
221 return lvars
222
222
223 def _runlines(lines):
223 def _runlines(lines):
224 """Run a string of one or more lines of source.
224 """Run a string of one or more lines of source.
225
225
226 This method is capable of running a string containing multiple source
226 This method is capable of running a string containing multiple source
227 lines, as if they had been entered at the IPython prompt. Since it
227 lines, as if they had been entered at the IPython prompt. Since it
228 exposes IPython's processing machinery, the given strings can contain
228 exposes IPython's processing machinery, the given strings can contain
229 magic calls (%magic), special shell access (!cmd), etc."""
229 magic calls (%magic), special shell access (!cmd), etc."""
230
230
231 # We must start with a clean buffer, in case this is run from an
231 # We must start with a clean buffer, in case this is run from an
232 # interactive IPython session (via a magic, for example).
232 # interactive IPython session (via a magic, for example).
233 ip.IP.resetbuffer()
233 ip.IP.resetbuffer()
234 lines = lines.split('\n')
234 lines = lines.split('\n')
235 more = 0
235 more = 0
236 command = ''
236 command = ''
237 for line in lines:
237 for line in lines:
238 # skip blank lines so we don't mess up the prompt counter, but do
238 # skip blank lines so we don't mess up the prompt counter, but do
239 # NOT skip even a blank line if we are in a code block (more is
239 # NOT skip even a blank line if we are in a code block (more is
240 # true)
240 # true)
241 # if command is not empty trim the line
241 # if command is not empty trim the line
242 if command != '' :
242 if command != '' :
243 line = line.strip()
243 line = line.strip()
244 # add the broken line to the command
244 # add the broken line to the command
245 if line and line[-1] == '\\' :
245 if line and line[-1] == '\\' :
246 command += line[0:-1] + ' '
246 command += line[0:-1] + ' '
247 more = True
247 more = True
248 continue
248 continue
249 else :
249 else :
250 # add the last (current) line to the command
250 # add the last (current) line to the command
251 command += line
251 command += line
252 if command or more:
252 if command or more:
253 # push to raw history, so hist line numbers stay in sync
253 # push to raw history, so hist line numbers stay in sync
254 ip.IP.input_hist_raw.append("# " + command + "\n")
254 ip.IP.input_hist_raw.append("# " + command + "\n")
255
255
256 more = ip.IP.push(ip.IP.prefilter(command,more))
256 more = ip.IP.push(ip.IP.prefilter(command,more))
257 command = ''
257 command = ''
258 # IPython's runsource returns None if there was an error
258 # IPython's runsource returns None if there was an error
259 # compiling the code. This allows us to stop processing right
259 # compiling the code. This allows us to stop processing right
260 # away, so the user gets the error message at the right place.
260 # away, so the user gets the error message at the right place.
261 if more is None:
261 if more is None:
262 break
262 break
263 # final newline in case the input didn't have it, so that the code
263 # final newline in case the input didn't have it, so that the code
264 # actually does get executed
264 # actually does get executed
265 if more:
265 if more:
266 ip.IP.push('\n')
266 ip.IP.push('\n')
267
267
268 ip.IP.runlines = _runlines
268 ip.IP.runlines = _runlines
269
269
270 main()
270 main()
@@ -1,3397 +1,3405 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $"""
4 $Id: Magic.py 2996 2008-01-30 06:31:39Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38 from sets import Set
38 from sets import Set
39
39
40 # cProfile was added in Python2.5
40 # cProfile was added in Python2.5
41 try:
41 try:
42 import cProfile as profile
42 import cProfile as profile
43 import pstats
43 import pstats
44 except ImportError:
44 except ImportError:
45 # profile isn't bundled by default in Debian for license reasons
45 # profile isn't bundled by default in Debian for license reasons
46 try:
46 try:
47 import profile,pstats
47 import profile,pstats
48 except ImportError:
48 except ImportError:
49 profile = pstats = None
49 profile = pstats = None
50
50
51 # Homebrewed
51 # Homebrewed
52 import IPython
52 import IPython
53 from IPython import Debugger, OInspect, wildcard
53 from IPython import Debugger, OInspect, wildcard
54 from IPython.FakeModule import FakeModule
54 from IPython.FakeModule import FakeModule
55 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 from IPython.Itpl import Itpl, itpl, printpl,itplns
56 from IPython.PyColorize import Parser
56 from IPython.PyColorize import Parser
57 from IPython.ipstruct import Struct
57 from IPython.ipstruct import Struct
58 from IPython.macro import Macro
58 from IPython.macro import Macro
59 from IPython.genutils import *
59 from IPython.genutils import *
60 from IPython import platutils
60 from IPython import platutils
61 import IPython.generics
61 import IPython.generics
62 import IPython.ipapi
62 import IPython.ipapi
63 from IPython.ipapi import UsageError
63 from IPython.ipapi import UsageError
64 from IPython.testing import decorators as testdec
64 from IPython.testing import decorators as testdec
65
65
66 #***************************************************************************
66 #***************************************************************************
67 # Utility functions
67 # Utility functions
68 def on_off(tag):
68 def on_off(tag):
69 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
69 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 return ['OFF','ON'][tag]
70 return ['OFF','ON'][tag]
71
71
72 class Bunch: pass
72 class Bunch: pass
73
73
74 def compress_dhist(dh):
74 def compress_dhist(dh):
75 head, tail = dh[:-10], dh[-10:]
75 head, tail = dh[:-10], dh[-10:]
76
76
77 newhead = []
77 newhead = []
78 done = Set()
78 done = Set()
79 for h in head:
79 for h in head:
80 if h in done:
80 if h in done:
81 continue
81 continue
82 newhead.append(h)
82 newhead.append(h)
83 done.add(h)
83 done.add(h)
84
84
85 return newhead + tail
85 return newhead + tail
86
86
87
87
88 #***************************************************************************
88 #***************************************************************************
89 # Main class implementing Magic functionality
89 # Main class implementing Magic functionality
90 class Magic:
90 class Magic:
91 """Magic functions for InteractiveShell.
91 """Magic functions for InteractiveShell.
92
92
93 Shell functions which can be reached as %function_name. All magic
93 Shell functions which can be reached as %function_name. All magic
94 functions should accept a string, which they can parse for their own
94 functions should accept a string, which they can parse for their own
95 needs. This can make some functions easier to type, eg `%cd ../`
95 needs. This can make some functions easier to type, eg `%cd ../`
96 vs. `%cd("../")`
96 vs. `%cd("../")`
97
97
98 ALL definitions MUST begin with the prefix magic_. The user won't need it
98 ALL definitions MUST begin with the prefix magic_. The user won't need it
99 at the command line, but it is is needed in the definition. """
99 at the command line, but it is is needed in the definition. """
100
100
101 # class globals
101 # class globals
102 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
102 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
103 'Automagic is ON, % prefix NOT needed for magic functions.']
103 'Automagic is ON, % prefix NOT needed for magic functions.']
104
104
105 #......................................................................
105 #......................................................................
106 # some utility functions
106 # some utility functions
107
107
108 def __init__(self,shell):
108 def __init__(self,shell):
109
109
110 self.options_table = {}
110 self.options_table = {}
111 if profile is None:
111 if profile is None:
112 self.magic_prun = self.profile_missing_notice
112 self.magic_prun = self.profile_missing_notice
113 self.shell = shell
113 self.shell = shell
114
114
115 # namespace for holding state we may need
115 # namespace for holding state we may need
116 self._magic_state = Bunch()
116 self._magic_state = Bunch()
117
117
118 def profile_missing_notice(self, *args, **kwargs):
118 def profile_missing_notice(self, *args, **kwargs):
119 error("""\
119 error("""\
120 The profile module could not be found. It has been removed from the standard
120 The profile module could not be found. It has been removed from the standard
121 python packages because of its non-free license. To use profiling, install the
121 python packages because of its non-free license. To use profiling, install the
122 python-profiler package from non-free.""")
122 python-profiler package from non-free.""")
123
123
124 def default_option(self,fn,optstr):
124 def default_option(self,fn,optstr):
125 """Make an entry in the options_table for fn, with value optstr"""
125 """Make an entry in the options_table for fn, with value optstr"""
126
126
127 if fn not in self.lsmagic():
127 if fn not in self.lsmagic():
128 error("%s is not a magic function" % fn)
128 error("%s is not a magic function" % fn)
129 self.options_table[fn] = optstr
129 self.options_table[fn] = optstr
130
130
131 def lsmagic(self):
131 def lsmagic(self):
132 """Return a list of currently available magic functions.
132 """Return a list of currently available magic functions.
133
133
134 Gives a list of the bare names after mangling (['ls','cd', ...], not
134 Gives a list of the bare names after mangling (['ls','cd', ...], not
135 ['magic_ls','magic_cd',...]"""
135 ['magic_ls','magic_cd',...]"""
136
136
137 # FIXME. This needs a cleanup, in the way the magics list is built.
137 # FIXME. This needs a cleanup, in the way the magics list is built.
138
138
139 # magics in class definition
139 # magics in class definition
140 class_magic = lambda fn: fn.startswith('magic_') and \
140 class_magic = lambda fn: fn.startswith('magic_') and \
141 callable(Magic.__dict__[fn])
141 callable(Magic.__dict__[fn])
142 # in instance namespace (run-time user additions)
142 # in instance namespace (run-time user additions)
143 inst_magic = lambda fn: fn.startswith('magic_') and \
143 inst_magic = lambda fn: fn.startswith('magic_') and \
144 callable(self.__dict__[fn])
144 callable(self.__dict__[fn])
145 # and bound magics by user (so they can access self):
145 # and bound magics by user (so they can access self):
146 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
146 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
147 callable(self.__class__.__dict__[fn])
147 callable(self.__class__.__dict__[fn])
148 magics = filter(class_magic,Magic.__dict__.keys()) + \
148 magics = filter(class_magic,Magic.__dict__.keys()) + \
149 filter(inst_magic,self.__dict__.keys()) + \
149 filter(inst_magic,self.__dict__.keys()) + \
150 filter(inst_bound_magic,self.__class__.__dict__.keys())
150 filter(inst_bound_magic,self.__class__.__dict__.keys())
151 out = []
151 out = []
152 for fn in Set(magics):
152 for fn in Set(magics):
153 out.append(fn.replace('magic_','',1))
153 out.append(fn.replace('magic_','',1))
154 out.sort()
154 out.sort()
155 return out
155 return out
156
156
157 def extract_input_slices(self,slices,raw=False):
157 def extract_input_slices(self,slices,raw=False):
158 """Return as a string a set of input history slices.
158 """Return as a string a set of input history slices.
159
159
160 Inputs:
160 Inputs:
161
161
162 - slices: the set of slices is given as a list of strings (like
162 - slices: the set of slices is given as a list of strings (like
163 ['1','4:8','9'], since this function is for use by magic functions
163 ['1','4:8','9'], since this function is for use by magic functions
164 which get their arguments as strings.
164 which get their arguments as strings.
165
165
166 Optional inputs:
166 Optional inputs:
167
167
168 - raw(False): by default, the processed input is used. If this is
168 - raw(False): by default, the processed input is used. If this is
169 true, the raw input history is used instead.
169 true, the raw input history is used instead.
170
170
171 Note that slices can be called with two notations:
171 Note that slices can be called with two notations:
172
172
173 N:M -> standard python form, means including items N...(M-1).
173 N:M -> standard python form, means including items N...(M-1).
174
174
175 N-M -> include items N..M (closed endpoint)."""
175 N-M -> include items N..M (closed endpoint)."""
176
176
177 if raw:
177 if raw:
178 hist = self.shell.input_hist_raw
178 hist = self.shell.input_hist_raw
179 else:
179 else:
180 hist = self.shell.input_hist
180 hist = self.shell.input_hist
181
181
182 cmds = []
182 cmds = []
183 for chunk in slices:
183 for chunk in slices:
184 if ':' in chunk:
184 if ':' in chunk:
185 ini,fin = map(int,chunk.split(':'))
185 ini,fin = map(int,chunk.split(':'))
186 elif '-' in chunk:
186 elif '-' in chunk:
187 ini,fin = map(int,chunk.split('-'))
187 ini,fin = map(int,chunk.split('-'))
188 fin += 1
188 fin += 1
189 else:
189 else:
190 ini = int(chunk)
190 ini = int(chunk)
191 fin = ini+1
191 fin = ini+1
192 cmds.append(hist[ini:fin])
192 cmds.append(hist[ini:fin])
193 return cmds
193 return cmds
194
194
195 def _ofind(self, oname, namespaces=None):
195 def _ofind(self, oname, namespaces=None):
196 """Find an object in the available namespaces.
196 """Find an object in the available namespaces.
197
197
198 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
198 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
199
199
200 Has special code to detect magic functions.
200 Has special code to detect magic functions.
201 """
201 """
202
202
203 oname = oname.strip()
203 oname = oname.strip()
204
204
205 alias_ns = None
205 alias_ns = None
206 if namespaces is None:
206 if namespaces is None:
207 # Namespaces to search in:
207 # Namespaces to search in:
208 # Put them in a list. The order is important so that we
208 # Put them in a list. The order is important so that we
209 # find things in the same order that Python finds them.
209 # find things in the same order that Python finds them.
210 namespaces = [ ('Interactive', self.shell.user_ns),
210 namespaces = [ ('Interactive', self.shell.user_ns),
211 ('IPython internal', self.shell.internal_ns),
211 ('IPython internal', self.shell.internal_ns),
212 ('Python builtin', __builtin__.__dict__),
212 ('Python builtin', __builtin__.__dict__),
213 ('Alias', self.shell.alias_table),
213 ('Alias', self.shell.alias_table),
214 ]
214 ]
215 alias_ns = self.shell.alias_table
215 alias_ns = self.shell.alias_table
216
216
217 # initialize results to 'null'
217 # initialize results to 'null'
218 found = 0; obj = None; ospace = None; ds = None;
218 found = 0; obj = None; ospace = None; ds = None;
219 ismagic = 0; isalias = 0; parent = None
219 ismagic = 0; isalias = 0; parent = None
220
220
221 # Look for the given name by splitting it in parts. If the head is
221 # Look for the given name by splitting it in parts. If the head is
222 # found, then we look for all the remaining parts as members, and only
222 # found, then we look for all the remaining parts as members, and only
223 # declare success if we can find them all.
223 # declare success if we can find them all.
224 oname_parts = oname.split('.')
224 oname_parts = oname.split('.')
225 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
225 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
226 for nsname,ns in namespaces:
226 for nsname,ns in namespaces:
227 try:
227 try:
228 obj = ns[oname_head]
228 obj = ns[oname_head]
229 except KeyError:
229 except KeyError:
230 continue
230 continue
231 else:
231 else:
232 #print 'oname_rest:', oname_rest # dbg
232 #print 'oname_rest:', oname_rest # dbg
233 for part in oname_rest:
233 for part in oname_rest:
234 try:
234 try:
235 parent = obj
235 parent = obj
236 obj = getattr(obj,part)
236 obj = getattr(obj,part)
237 except:
237 except:
238 # Blanket except b/c some badly implemented objects
238 # Blanket except b/c some badly implemented objects
239 # allow __getattr__ to raise exceptions other than
239 # allow __getattr__ to raise exceptions other than
240 # AttributeError, which then crashes IPython.
240 # AttributeError, which then crashes IPython.
241 break
241 break
242 else:
242 else:
243 # If we finish the for loop (no break), we got all members
243 # If we finish the for loop (no break), we got all members
244 found = 1
244 found = 1
245 ospace = nsname
245 ospace = nsname
246 if ns == alias_ns:
246 if ns == alias_ns:
247 isalias = 1
247 isalias = 1
248 break # namespace loop
248 break # namespace loop
249
249
250 # Try to see if it's magic
250 # Try to see if it's magic
251 if not found:
251 if not found:
252 if oname.startswith(self.shell.ESC_MAGIC):
252 if oname.startswith(self.shell.ESC_MAGIC):
253 oname = oname[1:]
253 oname = oname[1:]
254 obj = getattr(self,'magic_'+oname,None)
254 obj = getattr(self,'magic_'+oname,None)
255 if obj is not None:
255 if obj is not None:
256 found = 1
256 found = 1
257 ospace = 'IPython internal'
257 ospace = 'IPython internal'
258 ismagic = 1
258 ismagic = 1
259
259
260 # Last try: special-case some literals like '', [], {}, etc:
260 # Last try: special-case some literals like '', [], {}, etc:
261 if not found and oname_head in ["''",'""','[]','{}','()']:
261 if not found and oname_head in ["''",'""','[]','{}','()']:
262 obj = eval(oname_head)
262 obj = eval(oname_head)
263 found = 1
263 found = 1
264 ospace = 'Interactive'
264 ospace = 'Interactive'
265
265
266 return {'found':found, 'obj':obj, 'namespace':ospace,
266 return {'found':found, 'obj':obj, 'namespace':ospace,
267 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
267 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
268
268
269 def arg_err(self,func):
269 def arg_err(self,func):
270 """Print docstring if incorrect arguments were passed"""
270 """Print docstring if incorrect arguments were passed"""
271 print 'Error in arguments:'
271 print 'Error in arguments:'
272 print OInspect.getdoc(func)
272 print OInspect.getdoc(func)
273
273
274 def format_latex(self,strng):
274 def format_latex(self,strng):
275 """Format a string for latex inclusion."""
275 """Format a string for latex inclusion."""
276
276
277 # Characters that need to be escaped for latex:
277 # Characters that need to be escaped for latex:
278 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
278 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
279 # Magic command names as headers:
279 # Magic command names as headers:
280 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
280 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
281 re.MULTILINE)
281 re.MULTILINE)
282 # Magic commands
282 # Magic commands
283 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
283 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
284 re.MULTILINE)
284 re.MULTILINE)
285 # Paragraph continue
285 # Paragraph continue
286 par_re = re.compile(r'\\$',re.MULTILINE)
286 par_re = re.compile(r'\\$',re.MULTILINE)
287
287
288 # The "\n" symbol
288 # The "\n" symbol
289 newline_re = re.compile(r'\\n')
289 newline_re = re.compile(r'\\n')
290
290
291 # Now build the string for output:
291 # Now build the string for output:
292 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
292 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
293 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
293 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
294 strng)
294 strng)
295 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
295 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
296 strng = par_re.sub(r'\\\\',strng)
296 strng = par_re.sub(r'\\\\',strng)
297 strng = escape_re.sub(r'\\\1',strng)
297 strng = escape_re.sub(r'\\\1',strng)
298 strng = newline_re.sub(r'\\textbackslash{}n',strng)
298 strng = newline_re.sub(r'\\textbackslash{}n',strng)
299 return strng
299 return strng
300
300
301 def format_screen(self,strng):
301 def format_screen(self,strng):
302 """Format a string for screen printing.
302 """Format a string for screen printing.
303
303
304 This removes some latex-type format codes."""
304 This removes some latex-type format codes."""
305 # Paragraph continue
305 # Paragraph continue
306 par_re = re.compile(r'\\$',re.MULTILINE)
306 par_re = re.compile(r'\\$',re.MULTILINE)
307 strng = par_re.sub('',strng)
307 strng = par_re.sub('',strng)
308 return strng
308 return strng
309
309
310 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
310 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
311 """Parse options passed to an argument string.
311 """Parse options passed to an argument string.
312
312
313 The interface is similar to that of getopt(), but it returns back a
313 The interface is similar to that of getopt(), but it returns back a
314 Struct with the options as keys and the stripped argument string still
314 Struct with the options as keys and the stripped argument string still
315 as a string.
315 as a string.
316
316
317 arg_str is quoted as a true sys.argv vector by using shlex.split.
317 arg_str is quoted as a true sys.argv vector by using shlex.split.
318 This allows us to easily expand variables, glob files, quote
318 This allows us to easily expand variables, glob files, quote
319 arguments, etc.
319 arguments, etc.
320
320
321 Options:
321 Options:
322 -mode: default 'string'. If given as 'list', the argument string is
322 -mode: default 'string'. If given as 'list', the argument string is
323 returned as a list (split on whitespace) instead of a string.
323 returned as a list (split on whitespace) instead of a string.
324
324
325 -list_all: put all option values in lists. Normally only options
325 -list_all: put all option values in lists. Normally only options
326 appearing more than once are put in a list.
326 appearing more than once are put in a list.
327
327
328 -posix (True): whether to split the input line in POSIX mode or not,
328 -posix (True): whether to split the input line in POSIX mode or not,
329 as per the conventions outlined in the shlex module from the
329 as per the conventions outlined in the shlex module from the
330 standard library."""
330 standard library."""
331
331
332 # inject default options at the beginning of the input line
332 # inject default options at the beginning of the input line
333 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
333 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
334 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
334 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
335
335
336 mode = kw.get('mode','string')
336 mode = kw.get('mode','string')
337 if mode not in ['string','list']:
337 if mode not in ['string','list']:
338 raise ValueError,'incorrect mode given: %s' % mode
338 raise ValueError,'incorrect mode given: %s' % mode
339 # Get options
339 # Get options
340 list_all = kw.get('list_all',0)
340 list_all = kw.get('list_all',0)
341 posix = kw.get('posix',True)
341 posix = kw.get('posix',True)
342
342
343 # Check if we have more than one argument to warrant extra processing:
343 # Check if we have more than one argument to warrant extra processing:
344 odict = {} # Dictionary with options
344 odict = {} # Dictionary with options
345 args = arg_str.split()
345 args = arg_str.split()
346 if len(args) >= 1:
346 if len(args) >= 1:
347 # If the list of inputs only has 0 or 1 thing in it, there's no
347 # If the list of inputs only has 0 or 1 thing in it, there's no
348 # need to look for options
348 # need to look for options
349 argv = arg_split(arg_str,posix)
349 argv = arg_split(arg_str,posix)
350 # Do regular option processing
350 # Do regular option processing
351 try:
351 try:
352 opts,args = getopt(argv,opt_str,*long_opts)
352 opts,args = getopt(argv,opt_str,*long_opts)
353 except GetoptError,e:
353 except GetoptError,e:
354 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
354 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
355 " ".join(long_opts)))
355 " ".join(long_opts)))
356 for o,a in opts:
356 for o,a in opts:
357 if o.startswith('--'):
357 if o.startswith('--'):
358 o = o[2:]
358 o = o[2:]
359 else:
359 else:
360 o = o[1:]
360 o = o[1:]
361 try:
361 try:
362 odict[o].append(a)
362 odict[o].append(a)
363 except AttributeError:
363 except AttributeError:
364 odict[o] = [odict[o],a]
364 odict[o] = [odict[o],a]
365 except KeyError:
365 except KeyError:
366 if list_all:
366 if list_all:
367 odict[o] = [a]
367 odict[o] = [a]
368 else:
368 else:
369 odict[o] = a
369 odict[o] = a
370
370
371 # Prepare opts,args for return
371 # Prepare opts,args for return
372 opts = Struct(odict)
372 opts = Struct(odict)
373 if mode == 'string':
373 if mode == 'string':
374 args = ' '.join(args)
374 args = ' '.join(args)
375
375
376 return opts,args
376 return opts,args
377
377
378 #......................................................................
378 #......................................................................
379 # And now the actual magic functions
379 # And now the actual magic functions
380
380
381 # Functions for IPython shell work (vars,funcs, config, etc)
381 # Functions for IPython shell work (vars,funcs, config, etc)
382 def magic_lsmagic(self, parameter_s = ''):
382 def magic_lsmagic(self, parameter_s = ''):
383 """List currently available magic functions."""
383 """List currently available magic functions."""
384 mesc = self.shell.ESC_MAGIC
384 mesc = self.shell.ESC_MAGIC
385 print 'Available magic functions:\n'+mesc+\
385 print 'Available magic functions:\n'+mesc+\
386 (' '+mesc).join(self.lsmagic())
386 (' '+mesc).join(self.lsmagic())
387 print '\n' + Magic.auto_status[self.shell.rc.automagic]
387 print '\n' + Magic.auto_status[self.shell.rc.automagic]
388 return None
388 return None
389
389
390 def magic_magic(self, parameter_s = ''):
390 def magic_magic(self, parameter_s = ''):
391 """Print information about the magic function system.
391 """Print information about the magic function system.
392
392
393 Supported formats: -latex, -brief, -rest
393 Supported formats: -latex, -brief, -rest
394 """
394 """
395
395
396 mode = ''
396 mode = ''
397 try:
397 try:
398 if parameter_s.split()[0] == '-latex':
398 if parameter_s.split()[0] == '-latex':
399 mode = 'latex'
399 mode = 'latex'
400 if parameter_s.split()[0] == '-brief':
400 if parameter_s.split()[0] == '-brief':
401 mode = 'brief'
401 mode = 'brief'
402 if parameter_s.split()[0] == '-rest':
402 if parameter_s.split()[0] == '-rest':
403 mode = 'rest'
403 mode = 'rest'
404 rest_docs = []
404 rest_docs = []
405 except:
405 except:
406 pass
406 pass
407
407
408 magic_docs = []
408 magic_docs = []
409 for fname in self.lsmagic():
409 for fname in self.lsmagic():
410 mname = 'magic_' + fname
410 mname = 'magic_' + fname
411 for space in (Magic,self,self.__class__):
411 for space in (Magic,self,self.__class__):
412 try:
412 try:
413 fn = space.__dict__[mname]
413 fn = space.__dict__[mname]
414 except KeyError:
414 except KeyError:
415 pass
415 pass
416 else:
416 else:
417 break
417 break
418 if mode == 'brief':
418 if mode == 'brief':
419 # only first line
419 # only first line
420 if fn.__doc__:
420 if fn.__doc__:
421 fndoc = fn.__doc__.split('\n',1)[0]
421 fndoc = fn.__doc__.split('\n',1)[0]
422 else:
422 else:
423 fndoc = 'No documentation'
423 fndoc = 'No documentation'
424 else:
424 else:
425 if fn.__doc__:
425 fndoc = fn.__doc__.rstrip()
426 fndoc = fn.__doc__.rstrip()
427 else:
428 fndoc = 'No documentation'
429
426
430
427 if mode == 'rest':
431 if mode == 'rest':
428 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
432 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
429 fname,fndoc))
433 fname,fndoc))
430
434
431 else:
435 else:
432 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
436 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
433 fname,fndoc))
437 fname,fndoc))
434
438
435 magic_docs = ''.join(magic_docs)
439 magic_docs = ''.join(magic_docs)
436
440
437 if mode == 'rest':
441 if mode == 'rest':
438 return "".join(rest_docs)
442 return "".join(rest_docs)
439
443
440 if mode == 'latex':
444 if mode == 'latex':
441 print self.format_latex(magic_docs)
445 print self.format_latex(magic_docs)
442 return
446 return
443 else:
447 else:
444 magic_docs = self.format_screen(magic_docs)
448 magic_docs = self.format_screen(magic_docs)
445 if mode == 'brief':
449 if mode == 'brief':
446 return magic_docs
450 return magic_docs
447
451
448 outmsg = """
452 outmsg = """
449 IPython's 'magic' functions
453 IPython's 'magic' functions
450 ===========================
454 ===========================
451
455
452 The magic function system provides a series of functions which allow you to
456 The magic function system provides a series of functions which allow you to
453 control the behavior of IPython itself, plus a lot of system-type
457 control the behavior of IPython itself, plus a lot of system-type
454 features. All these functions are prefixed with a % character, but parameters
458 features. All these functions are prefixed with a % character, but parameters
455 are given without parentheses or quotes.
459 are given without parentheses or quotes.
456
460
457 NOTE: If you have 'automagic' enabled (via the command line option or with the
461 NOTE: If you have 'automagic' enabled (via the command line option or with the
458 %automagic function), you don't need to type in the % explicitly. By default,
462 %automagic function), you don't need to type in the % explicitly. By default,
459 IPython ships with automagic on, so you should only rarely need the % escape.
463 IPython ships with automagic on, so you should only rarely need the % escape.
460
464
461 Example: typing '%cd mydir' (without the quotes) changes you working directory
465 Example: typing '%cd mydir' (without the quotes) changes you working directory
462 to 'mydir', if it exists.
466 to 'mydir', if it exists.
463
467
464 You can define your own magic functions to extend the system. See the supplied
468 You can define your own magic functions to extend the system. See the supplied
465 ipythonrc and example-magic.py files for details (in your ipython
469 ipythonrc and example-magic.py files for details (in your ipython
466 configuration directory, typically $HOME/.ipython/).
470 configuration directory, typically $HOME/.ipython/).
467
471
468 You can also define your own aliased names for magic functions. In your
472 You can also define your own aliased names for magic functions. In your
469 ipythonrc file, placing a line like:
473 ipythonrc file, placing a line like:
470
474
471 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
475 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
472
476
473 will define %pf as a new name for %profile.
477 will define %pf as a new name for %profile.
474
478
475 You can also call magics in code using the ipmagic() function, which IPython
479 You can also call magics in code using the ipmagic() function, which IPython
476 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
480 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
477
481
478 For a list of the available magic functions, use %lsmagic. For a description
482 For a list of the available magic functions, use %lsmagic. For a description
479 of any of them, type %magic_name?, e.g. '%cd?'.
483 of any of them, type %magic_name?, e.g. '%cd?'.
480
484
481 Currently the magic system has the following functions:\n"""
485 Currently the magic system has the following functions:\n"""
482
486
483 mesc = self.shell.ESC_MAGIC
487 mesc = self.shell.ESC_MAGIC
484 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
488 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
485 "\n\n%s%s\n\n%s" % (outmsg,
489 "\n\n%s%s\n\n%s" % (outmsg,
486 magic_docs,mesc,mesc,
490 magic_docs,mesc,mesc,
487 (' '+mesc).join(self.lsmagic()),
491 (' '+mesc).join(self.lsmagic()),
488 Magic.auto_status[self.shell.rc.automagic] ) )
492 Magic.auto_status[self.shell.rc.automagic] ) )
489
493
490 page(outmsg,screen_lines=self.shell.rc.screen_length)
494 page(outmsg,screen_lines=self.shell.rc.screen_length)
491
495
492
496
493 def magic_autoindent(self, parameter_s = ''):
497 def magic_autoindent(self, parameter_s = ''):
494 """Toggle autoindent on/off (if available)."""
498 """Toggle autoindent on/off (if available)."""
495
499
496 self.shell.set_autoindent()
500 self.shell.set_autoindent()
497 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
501 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
498
502
499
503
500 def magic_automagic(self, parameter_s = ''):
504 def magic_automagic(self, parameter_s = ''):
501 """Make magic functions callable without having to type the initial %.
505 """Make magic functions callable without having to type the initial %.
502
506
503 Without argumentsl toggles on/off (when off, you must call it as
507 Without argumentsl toggles on/off (when off, you must call it as
504 %automagic, of course). With arguments it sets the value, and you can
508 %automagic, of course). With arguments it sets the value, and you can
505 use any of (case insensitive):
509 use any of (case insensitive):
506
510
507 - on,1,True: to activate
511 - on,1,True: to activate
508
512
509 - off,0,False: to deactivate.
513 - off,0,False: to deactivate.
510
514
511 Note that magic functions have lowest priority, so if there's a
515 Note that magic functions have lowest priority, so if there's a
512 variable whose name collides with that of a magic fn, automagic won't
516 variable whose name collides with that of a magic fn, automagic won't
513 work for that function (you get the variable instead). However, if you
517 work for that function (you get the variable instead). However, if you
514 delete the variable (del var), the previously shadowed magic function
518 delete the variable (del var), the previously shadowed magic function
515 becomes visible to automagic again."""
519 becomes visible to automagic again."""
516
520
517 rc = self.shell.rc
521 rc = self.shell.rc
518 arg = parameter_s.lower()
522 arg = parameter_s.lower()
519 if parameter_s in ('on','1','true'):
523 if parameter_s in ('on','1','true'):
520 rc.automagic = True
524 rc.automagic = True
521 elif parameter_s in ('off','0','false'):
525 elif parameter_s in ('off','0','false'):
522 rc.automagic = False
526 rc.automagic = False
523 else:
527 else:
524 rc.automagic = not rc.automagic
528 rc.automagic = not rc.automagic
525 print '\n' + Magic.auto_status[rc.automagic]
529 print '\n' + Magic.auto_status[rc.automagic]
526
530
527 @testdec.skip_doctest
531 @testdec.skip_doctest
528 def magic_autocall(self, parameter_s = ''):
532 def magic_autocall(self, parameter_s = ''):
529 """Make functions callable without having to type parentheses.
533 """Make functions callable without having to type parentheses.
530
534
531 Usage:
535 Usage:
532
536
533 %autocall [mode]
537 %autocall [mode]
534
538
535 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
539 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
536 value is toggled on and off (remembering the previous state).
540 value is toggled on and off (remembering the previous state).
537
541
538 In more detail, these values mean:
542 In more detail, these values mean:
539
543
540 0 -> fully disabled
544 0 -> fully disabled
541
545
542 1 -> active, but do not apply if there are no arguments on the line.
546 1 -> active, but do not apply if there are no arguments on the line.
543
547
544 In this mode, you get:
548 In this mode, you get:
545
549
546 In [1]: callable
550 In [1]: callable
547 Out[1]: <built-in function callable>
551 Out[1]: <built-in function callable>
548
552
549 In [2]: callable 'hello'
553 In [2]: callable 'hello'
550 ------> callable('hello')
554 ------> callable('hello')
551 Out[2]: False
555 Out[2]: False
552
556
553 2 -> Active always. Even if no arguments are present, the callable
557 2 -> Active always. Even if no arguments are present, the callable
554 object is called:
558 object is called:
555
559
556 In [2]: float
560 In [2]: float
557 ------> float()
561 ------> float()
558 Out[2]: 0.0
562 Out[2]: 0.0
559
563
560 Note that even with autocall off, you can still use '/' at the start of
564 Note that even with autocall off, you can still use '/' at the start of
561 a line to treat the first argument on the command line as a function
565 a line to treat the first argument on the command line as a function
562 and add parentheses to it:
566 and add parentheses to it:
563
567
564 In [8]: /str 43
568 In [8]: /str 43
565 ------> str(43)
569 ------> str(43)
566 Out[8]: '43'
570 Out[8]: '43'
567
571
568 # all-random (note for auto-testing)
572 # all-random (note for auto-testing)
569 """
573 """
570
574
571 rc = self.shell.rc
575 rc = self.shell.rc
572
576
573 if parameter_s:
577 if parameter_s:
574 arg = int(parameter_s)
578 arg = int(parameter_s)
575 else:
579 else:
576 arg = 'toggle'
580 arg = 'toggle'
577
581
578 if not arg in (0,1,2,'toggle'):
582 if not arg in (0,1,2,'toggle'):
579 error('Valid modes: (0->Off, 1->Smart, 2->Full')
583 error('Valid modes: (0->Off, 1->Smart, 2->Full')
580 return
584 return
581
585
582 if arg in (0,1,2):
586 if arg in (0,1,2):
583 rc.autocall = arg
587 rc.autocall = arg
584 else: # toggle
588 else: # toggle
585 if rc.autocall:
589 if rc.autocall:
586 self._magic_state.autocall_save = rc.autocall
590 self._magic_state.autocall_save = rc.autocall
587 rc.autocall = 0
591 rc.autocall = 0
588 else:
592 else:
589 try:
593 try:
590 rc.autocall = self._magic_state.autocall_save
594 rc.autocall = self._magic_state.autocall_save
591 except AttributeError:
595 except AttributeError:
592 rc.autocall = self._magic_state.autocall_save = 1
596 rc.autocall = self._magic_state.autocall_save = 1
593
597
594 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
598 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
595
599
596 def magic_system_verbose(self, parameter_s = ''):
600 def magic_system_verbose(self, parameter_s = ''):
597 """Set verbose printing of system calls.
601 """Set verbose printing of system calls.
598
602
599 If called without an argument, act as a toggle"""
603 If called without an argument, act as a toggle"""
600
604
601 if parameter_s:
605 if parameter_s:
602 val = bool(eval(parameter_s))
606 val = bool(eval(parameter_s))
603 else:
607 else:
604 val = None
608 val = None
605
609
606 self.shell.rc_set_toggle('system_verbose',val)
610 self.shell.rc_set_toggle('system_verbose',val)
607 print "System verbose printing is:",\
611 print "System verbose printing is:",\
608 ['OFF','ON'][self.shell.rc.system_verbose]
612 ['OFF','ON'][self.shell.rc.system_verbose]
609
613
610
614
611 def magic_page(self, parameter_s=''):
615 def magic_page(self, parameter_s=''):
612 """Pretty print the object and display it through a pager.
616 """Pretty print the object and display it through a pager.
613
617
614 %page [options] OBJECT
618 %page [options] OBJECT
615
619
616 If no object is given, use _ (last output).
620 If no object is given, use _ (last output).
617
621
618 Options:
622 Options:
619
623
620 -r: page str(object), don't pretty-print it."""
624 -r: page str(object), don't pretty-print it."""
621
625
622 # After a function contributed by Olivier Aubert, slightly modified.
626 # After a function contributed by Olivier Aubert, slightly modified.
623
627
624 # Process options/args
628 # Process options/args
625 opts,args = self.parse_options(parameter_s,'r')
629 opts,args = self.parse_options(parameter_s,'r')
626 raw = 'r' in opts
630 raw = 'r' in opts
627
631
628 oname = args and args or '_'
632 oname = args and args or '_'
629 info = self._ofind(oname)
633 info = self._ofind(oname)
630 if info['found']:
634 if info['found']:
631 txt = (raw and str or pformat)( info['obj'] )
635 txt = (raw and str or pformat)( info['obj'] )
632 page(txt)
636 page(txt)
633 else:
637 else:
634 print 'Object `%s` not found' % oname
638 print 'Object `%s` not found' % oname
635
639
636 def magic_profile(self, parameter_s=''):
640 def magic_profile(self, parameter_s=''):
637 """Print your currently active IPyhton profile."""
641 """Print your currently active IPyhton profile."""
638 if self.shell.rc.profile:
642 if self.shell.rc.profile:
639 printpl('Current IPython profile: $self.shell.rc.profile.')
643 printpl('Current IPython profile: $self.shell.rc.profile.')
640 else:
644 else:
641 print 'No profile active.'
645 print 'No profile active.'
642
646
643 def magic_pinfo(self, parameter_s='', namespaces=None):
647 def magic_pinfo(self, parameter_s='', namespaces=None):
644 """Provide detailed information about an object.
648 """Provide detailed information about an object.
645
649
646 '%pinfo object' is just a synonym for object? or ?object."""
650 '%pinfo object' is just a synonym for object? or ?object."""
647
651
648 #print 'pinfo par: <%s>' % parameter_s # dbg
652 #print 'pinfo par: <%s>' % parameter_s # dbg
649
653
650
654
651 # detail_level: 0 -> obj? , 1 -> obj??
655 # detail_level: 0 -> obj? , 1 -> obj??
652 detail_level = 0
656 detail_level = 0
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
657 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # happen if the user types 'pinfo foo?' at the cmd line.
658 # happen if the user types 'pinfo foo?' at the cmd line.
655 pinfo,qmark1,oname,qmark2 = \
659 pinfo,qmark1,oname,qmark2 = \
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
660 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 if pinfo or qmark1 or qmark2:
661 if pinfo or qmark1 or qmark2:
658 detail_level = 1
662 detail_level = 1
659 if "*" in oname:
663 if "*" in oname:
660 self.magic_psearch(oname)
664 self.magic_psearch(oname)
661 else:
665 else:
662 self._inspect('pinfo', oname, detail_level=detail_level,
666 self._inspect('pinfo', oname, detail_level=detail_level,
663 namespaces=namespaces)
667 namespaces=namespaces)
664
668
665 def magic_pdef(self, parameter_s='', namespaces=None):
669 def magic_pdef(self, parameter_s='', namespaces=None):
666 """Print the definition header for any callable object.
670 """Print the definition header for any callable object.
667
671
668 If the object is a class, print the constructor information."""
672 If the object is a class, print the constructor information."""
669 self._inspect('pdef',parameter_s, namespaces)
673 self._inspect('pdef',parameter_s, namespaces)
670
674
671 def magic_pdoc(self, parameter_s='', namespaces=None):
675 def magic_pdoc(self, parameter_s='', namespaces=None):
672 """Print the docstring for an object.
676 """Print the docstring for an object.
673
677
674 If the given object is a class, it will print both the class and the
678 If the given object is a class, it will print both the class and the
675 constructor docstrings."""
679 constructor docstrings."""
676 self._inspect('pdoc',parameter_s, namespaces)
680 self._inspect('pdoc',parameter_s, namespaces)
677
681
678 def magic_psource(self, parameter_s='', namespaces=None):
682 def magic_psource(self, parameter_s='', namespaces=None):
679 """Print (or run through pager) the source code for an object."""
683 """Print (or run through pager) the source code for an object."""
680 self._inspect('psource',parameter_s, namespaces)
684 self._inspect('psource',parameter_s, namespaces)
681
685
682 def magic_pfile(self, parameter_s=''):
686 def magic_pfile(self, parameter_s=''):
683 """Print (or run through pager) the file where an object is defined.
687 """Print (or run through pager) the file where an object is defined.
684
688
685 The file opens at the line where the object definition begins. IPython
689 The file opens at the line where the object definition begins. IPython
686 will honor the environment variable PAGER if set, and otherwise will
690 will honor the environment variable PAGER if set, and otherwise will
687 do its best to print the file in a convenient form.
691 do its best to print the file in a convenient form.
688
692
689 If the given argument is not an object currently defined, IPython will
693 If the given argument is not an object currently defined, IPython will
690 try to interpret it as a filename (automatically adding a .py extension
694 try to interpret it as a filename (automatically adding a .py extension
691 if needed). You can thus use %pfile as a syntax highlighting code
695 if needed). You can thus use %pfile as a syntax highlighting code
692 viewer."""
696 viewer."""
693
697
694 # first interpret argument as an object name
698 # first interpret argument as an object name
695 out = self._inspect('pfile',parameter_s)
699 out = self._inspect('pfile',parameter_s)
696 # if not, try the input as a filename
700 # if not, try the input as a filename
697 if out == 'not found':
701 if out == 'not found':
698 try:
702 try:
699 filename = get_py_filename(parameter_s)
703 filename = get_py_filename(parameter_s)
700 except IOError,msg:
704 except IOError,msg:
701 print msg
705 print msg
702 return
706 return
703 page(self.shell.inspector.format(file(filename).read()))
707 page(self.shell.inspector.format(file(filename).read()))
704
708
705 def _inspect(self,meth,oname,namespaces=None,**kw):
709 def _inspect(self,meth,oname,namespaces=None,**kw):
706 """Generic interface to the inspector system.
710 """Generic interface to the inspector system.
707
711
708 This function is meant to be called by pdef, pdoc & friends."""
712 This function is meant to be called by pdef, pdoc & friends."""
709
713
710 #oname = oname.strip()
714 #oname = oname.strip()
711 #print '1- oname: <%r>' % oname # dbg
715 #print '1- oname: <%r>' % oname # dbg
712 try:
716 try:
713 oname = oname.strip().encode('ascii')
717 oname = oname.strip().encode('ascii')
714 #print '2- oname: <%r>' % oname # dbg
718 #print '2- oname: <%r>' % oname # dbg
715 except UnicodeEncodeError:
719 except UnicodeEncodeError:
716 print 'Python identifiers can only contain ascii characters.'
720 print 'Python identifiers can only contain ascii characters.'
717 return 'not found'
721 return 'not found'
718
722
719 info = Struct(self._ofind(oname, namespaces))
723 info = Struct(self._ofind(oname, namespaces))
720
724
721 if info.found:
725 if info.found:
722 try:
726 try:
723 IPython.generics.inspect_object(info.obj)
727 IPython.generics.inspect_object(info.obj)
724 return
728 return
725 except IPython.ipapi.TryNext:
729 except IPython.ipapi.TryNext:
726 pass
730 pass
727 # Get the docstring of the class property if it exists.
731 # Get the docstring of the class property if it exists.
728 path = oname.split('.')
732 path = oname.split('.')
729 root = '.'.join(path[:-1])
733 root = '.'.join(path[:-1])
730 if info.parent is not None:
734 if info.parent is not None:
731 try:
735 try:
732 target = getattr(info.parent, '__class__')
736 target = getattr(info.parent, '__class__')
733 # The object belongs to a class instance.
737 # The object belongs to a class instance.
734 try:
738 try:
735 target = getattr(target, path[-1])
739 target = getattr(target, path[-1])
736 # The class defines the object.
740 # The class defines the object.
737 if isinstance(target, property):
741 if isinstance(target, property):
738 oname = root + '.__class__.' + path[-1]
742 oname = root + '.__class__.' + path[-1]
739 info = Struct(self._ofind(oname))
743 info = Struct(self._ofind(oname))
740 except AttributeError: pass
744 except AttributeError: pass
741 except AttributeError: pass
745 except AttributeError: pass
742
746
743 pmethod = getattr(self.shell.inspector,meth)
747 pmethod = getattr(self.shell.inspector,meth)
744 formatter = info.ismagic and self.format_screen or None
748 formatter = info.ismagic and self.format_screen or None
745 if meth == 'pdoc':
749 if meth == 'pdoc':
746 pmethod(info.obj,oname,formatter)
750 pmethod(info.obj,oname,formatter)
747 elif meth == 'pinfo':
751 elif meth == 'pinfo':
748 pmethod(info.obj,oname,formatter,info,**kw)
752 pmethod(info.obj,oname,formatter,info,**kw)
749 else:
753 else:
750 pmethod(info.obj,oname)
754 pmethod(info.obj,oname)
751 else:
755 else:
752 print 'Object `%s` not found.' % oname
756 print 'Object `%s` not found.' % oname
753 return 'not found' # so callers can take other action
757 return 'not found' # so callers can take other action
754
758
755 def magic_psearch(self, parameter_s=''):
759 def magic_psearch(self, parameter_s=''):
756 """Search for object in namespaces by wildcard.
760 """Search for object in namespaces by wildcard.
757
761
758 %psearch [options] PATTERN [OBJECT TYPE]
762 %psearch [options] PATTERN [OBJECT TYPE]
759
763
760 Note: ? can be used as a synonym for %psearch, at the beginning or at
764 Note: ? can be used as a synonym for %psearch, at the beginning or at
761 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
765 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
762 rest of the command line must be unchanged (options come first), so
766 rest of the command line must be unchanged (options come first), so
763 for example the following forms are equivalent
767 for example the following forms are equivalent
764
768
765 %psearch -i a* function
769 %psearch -i a* function
766 -i a* function?
770 -i a* function?
767 ?-i a* function
771 ?-i a* function
768
772
769 Arguments:
773 Arguments:
770
774
771 PATTERN
775 PATTERN
772
776
773 where PATTERN is a string containing * as a wildcard similar to its
777 where PATTERN is a string containing * as a wildcard similar to its
774 use in a shell. The pattern is matched in all namespaces on the
778 use in a shell. The pattern is matched in all namespaces on the
775 search path. By default objects starting with a single _ are not
779 search path. By default objects starting with a single _ are not
776 matched, many IPython generated objects have a single
780 matched, many IPython generated objects have a single
777 underscore. The default is case insensitive matching. Matching is
781 underscore. The default is case insensitive matching. Matching is
778 also done on the attributes of objects and not only on the objects
782 also done on the attributes of objects and not only on the objects
779 in a module.
783 in a module.
780
784
781 [OBJECT TYPE]
785 [OBJECT TYPE]
782
786
783 Is the name of a python type from the types module. The name is
787 Is the name of a python type from the types module. The name is
784 given in lowercase without the ending type, ex. StringType is
788 given in lowercase without the ending type, ex. StringType is
785 written string. By adding a type here only objects matching the
789 written string. By adding a type here only objects matching the
786 given type are matched. Using all here makes the pattern match all
790 given type are matched. Using all here makes the pattern match all
787 types (this is the default).
791 types (this is the default).
788
792
789 Options:
793 Options:
790
794
791 -a: makes the pattern match even objects whose names start with a
795 -a: makes the pattern match even objects whose names start with a
792 single underscore. These names are normally ommitted from the
796 single underscore. These names are normally ommitted from the
793 search.
797 search.
794
798
795 -i/-c: make the pattern case insensitive/sensitive. If neither of
799 -i/-c: make the pattern case insensitive/sensitive. If neither of
796 these options is given, the default is read from your ipythonrc
800 these options is given, the default is read from your ipythonrc
797 file. The option name which sets this value is
801 file. The option name which sets this value is
798 'wildcards_case_sensitive'. If this option is not specified in your
802 'wildcards_case_sensitive'. If this option is not specified in your
799 ipythonrc file, IPython's internal default is to do a case sensitive
803 ipythonrc file, IPython's internal default is to do a case sensitive
800 search.
804 search.
801
805
802 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
806 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
803 specifiy can be searched in any of the following namespaces:
807 specifiy can be searched in any of the following namespaces:
804 'builtin', 'user', 'user_global','internal', 'alias', where
808 'builtin', 'user', 'user_global','internal', 'alias', where
805 'builtin' and 'user' are the search defaults. Note that you should
809 'builtin' and 'user' are the search defaults. Note that you should
806 not use quotes when specifying namespaces.
810 not use quotes when specifying namespaces.
807
811
808 'Builtin' contains the python module builtin, 'user' contains all
812 'Builtin' contains the python module builtin, 'user' contains all
809 user data, 'alias' only contain the shell aliases and no python
813 user data, 'alias' only contain the shell aliases and no python
810 objects, 'internal' contains objects used by IPython. The
814 objects, 'internal' contains objects used by IPython. The
811 'user_global' namespace is only used by embedded IPython instances,
815 'user_global' namespace is only used by embedded IPython instances,
812 and it contains module-level globals. You can add namespaces to the
816 and it contains module-level globals. You can add namespaces to the
813 search with -s or exclude them with -e (these options can be given
817 search with -s or exclude them with -e (these options can be given
814 more than once).
818 more than once).
815
819
816 Examples:
820 Examples:
817
821
818 %psearch a* -> objects beginning with an a
822 %psearch a* -> objects beginning with an a
819 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
823 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
820 %psearch a* function -> all functions beginning with an a
824 %psearch a* function -> all functions beginning with an a
821 %psearch re.e* -> objects beginning with an e in module re
825 %psearch re.e* -> objects beginning with an e in module re
822 %psearch r*.e* -> objects that start with e in modules starting in r
826 %psearch r*.e* -> objects that start with e in modules starting in r
823 %psearch r*.* string -> all strings in modules beginning with r
827 %psearch r*.* string -> all strings in modules beginning with r
824
828
825 Case sensitve search:
829 Case sensitve search:
826
830
827 %psearch -c a* list all object beginning with lower case a
831 %psearch -c a* list all object beginning with lower case a
828
832
829 Show objects beginning with a single _:
833 Show objects beginning with a single _:
830
834
831 %psearch -a _* list objects beginning with a single underscore"""
835 %psearch -a _* list objects beginning with a single underscore"""
832 try:
836 try:
833 parameter_s = parameter_s.encode('ascii')
837 parameter_s = parameter_s.encode('ascii')
834 except UnicodeEncodeError:
838 except UnicodeEncodeError:
835 print 'Python identifiers can only contain ascii characters.'
839 print 'Python identifiers can only contain ascii characters.'
836 return
840 return
837
841
838 # default namespaces to be searched
842 # default namespaces to be searched
839 def_search = ['user','builtin']
843 def_search = ['user','builtin']
840
844
841 # Process options/args
845 # Process options/args
842 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
846 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
843 opt = opts.get
847 opt = opts.get
844 shell = self.shell
848 shell = self.shell
845 psearch = shell.inspector.psearch
849 psearch = shell.inspector.psearch
846
850
847 # select case options
851 # select case options
848 if opts.has_key('i'):
852 if opts.has_key('i'):
849 ignore_case = True
853 ignore_case = True
850 elif opts.has_key('c'):
854 elif opts.has_key('c'):
851 ignore_case = False
855 ignore_case = False
852 else:
856 else:
853 ignore_case = not shell.rc.wildcards_case_sensitive
857 ignore_case = not shell.rc.wildcards_case_sensitive
854
858
855 # Build list of namespaces to search from user options
859 # Build list of namespaces to search from user options
856 def_search.extend(opt('s',[]))
860 def_search.extend(opt('s',[]))
857 ns_exclude = ns_exclude=opt('e',[])
861 ns_exclude = ns_exclude=opt('e',[])
858 ns_search = [nm for nm in def_search if nm not in ns_exclude]
862 ns_search = [nm for nm in def_search if nm not in ns_exclude]
859
863
860 # Call the actual search
864 # Call the actual search
861 try:
865 try:
862 psearch(args,shell.ns_table,ns_search,
866 psearch(args,shell.ns_table,ns_search,
863 show_all=opt('a'),ignore_case=ignore_case)
867 show_all=opt('a'),ignore_case=ignore_case)
864 except:
868 except:
865 shell.showtraceback()
869 shell.showtraceback()
866
870
867 def magic_who_ls(self, parameter_s=''):
871 def magic_who_ls(self, parameter_s=''):
868 """Return a sorted list of all interactive variables.
872 """Return a sorted list of all interactive variables.
869
873
870 If arguments are given, only variables of types matching these
874 If arguments are given, only variables of types matching these
871 arguments are returned."""
875 arguments are returned."""
872
876
873 user_ns = self.shell.user_ns
877 user_ns = self.shell.user_ns
874 internal_ns = self.shell.internal_ns
878 internal_ns = self.shell.internal_ns
875 user_config_ns = self.shell.user_config_ns
879 user_config_ns = self.shell.user_config_ns
876 out = []
880 out = []
877 typelist = parameter_s.split()
881 typelist = parameter_s.split()
878
882
879 for i in user_ns:
883 for i in user_ns:
880 if not (i.startswith('_') or i.startswith('_i')) \
884 if not (i.startswith('_') or i.startswith('_i')) \
881 and not (i in internal_ns or i in user_config_ns):
885 and not (i in internal_ns or i in user_config_ns):
882 if typelist:
886 if typelist:
883 if type(user_ns[i]).__name__ in typelist:
887 if type(user_ns[i]).__name__ in typelist:
884 out.append(i)
888 out.append(i)
885 else:
889 else:
886 out.append(i)
890 out.append(i)
887 out.sort()
891 out.sort()
888 return out
892 return out
889
893
890 def magic_who(self, parameter_s=''):
894 def magic_who(self, parameter_s=''):
891 """Print all interactive variables, with some minimal formatting.
895 """Print all interactive variables, with some minimal formatting.
892
896
893 If any arguments are given, only variables whose type matches one of
897 If any arguments are given, only variables whose type matches one of
894 these are printed. For example:
898 these are printed. For example:
895
899
896 %who function str
900 %who function str
897
901
898 will only list functions and strings, excluding all other types of
902 will only list functions and strings, excluding all other types of
899 variables. To find the proper type names, simply use type(var) at a
903 variables. To find the proper type names, simply use type(var) at a
900 command line to see how python prints type names. For example:
904 command line to see how python prints type names. For example:
901
905
902 In [1]: type('hello')\\
906 In [1]: type('hello')\\
903 Out[1]: <type 'str'>
907 Out[1]: <type 'str'>
904
908
905 indicates that the type name for strings is 'str'.
909 indicates that the type name for strings is 'str'.
906
910
907 %who always excludes executed names loaded through your configuration
911 %who always excludes executed names loaded through your configuration
908 file and things which are internal to IPython.
912 file and things which are internal to IPython.
909
913
910 This is deliberate, as typically you may load many modules and the
914 This is deliberate, as typically you may load many modules and the
911 purpose of %who is to show you only what you've manually defined."""
915 purpose of %who is to show you only what you've manually defined."""
912
916
913 varlist = self.magic_who_ls(parameter_s)
917 varlist = self.magic_who_ls(parameter_s)
914 if not varlist:
918 if not varlist:
915 if parameter_s:
919 if parameter_s:
916 print 'No variables match your requested type.'
920 print 'No variables match your requested type.'
917 else:
921 else:
918 print 'Interactive namespace is empty.'
922 print 'Interactive namespace is empty.'
919 return
923 return
920
924
921 # if we have variables, move on...
925 # if we have variables, move on...
922 count = 0
926 count = 0
923 for i in varlist:
927 for i in varlist:
924 print i+'\t',
928 print i+'\t',
925 count += 1
929 count += 1
926 if count > 8:
930 if count > 8:
927 count = 0
931 count = 0
928 print
932 print
929 print
933 print
930
934
931 def magic_whos(self, parameter_s=''):
935 def magic_whos(self, parameter_s=''):
932 """Like %who, but gives some extra information about each variable.
936 """Like %who, but gives some extra information about each variable.
933
937
934 The same type filtering of %who can be applied here.
938 The same type filtering of %who can be applied here.
935
939
936 For all variables, the type is printed. Additionally it prints:
940 For all variables, the type is printed. Additionally it prints:
937
941
938 - For {},[],(): their length.
942 - For {},[],(): their length.
939
943
940 - For numpy and Numeric arrays, a summary with shape, number of
944 - For numpy and Numeric arrays, a summary with shape, number of
941 elements, typecode and size in memory.
945 elements, typecode and size in memory.
942
946
943 - Everything else: a string representation, snipping their middle if
947 - Everything else: a string representation, snipping their middle if
944 too long."""
948 too long."""
945
949
946 varnames = self.magic_who_ls(parameter_s)
950 varnames = self.magic_who_ls(parameter_s)
947 if not varnames:
951 if not varnames:
948 if parameter_s:
952 if parameter_s:
949 print 'No variables match your requested type.'
953 print 'No variables match your requested type.'
950 else:
954 else:
951 print 'Interactive namespace is empty.'
955 print 'Interactive namespace is empty.'
952 return
956 return
953
957
954 # if we have variables, move on...
958 # if we have variables, move on...
955
959
956 # for these types, show len() instead of data:
960 # for these types, show len() instead of data:
957 seq_types = [types.DictType,types.ListType,types.TupleType]
961 seq_types = [types.DictType,types.ListType,types.TupleType]
958
962
959 # for numpy/Numeric arrays, display summary info
963 # for numpy/Numeric arrays, display summary info
960 try:
964 try:
961 import numpy
965 import numpy
962 except ImportError:
966 except ImportError:
963 ndarray_type = None
967 ndarray_type = None
964 else:
968 else:
965 ndarray_type = numpy.ndarray.__name__
969 ndarray_type = numpy.ndarray.__name__
966 try:
970 try:
967 import Numeric
971 import Numeric
968 except ImportError:
972 except ImportError:
969 array_type = None
973 array_type = None
970 else:
974 else:
971 array_type = Numeric.ArrayType.__name__
975 array_type = Numeric.ArrayType.__name__
972
976
973 # Find all variable names and types so we can figure out column sizes
977 # Find all variable names and types so we can figure out column sizes
974 def get_vars(i):
978 def get_vars(i):
975 return self.shell.user_ns[i]
979 return self.shell.user_ns[i]
976
980
977 # some types are well known and can be shorter
981 # some types are well known and can be shorter
978 abbrevs = {'IPython.macro.Macro' : 'Macro'}
982 abbrevs = {'IPython.macro.Macro' : 'Macro'}
979 def type_name(v):
983 def type_name(v):
980 tn = type(v).__name__
984 tn = type(v).__name__
981 return abbrevs.get(tn,tn)
985 return abbrevs.get(tn,tn)
982
986
983 varlist = map(get_vars,varnames)
987 varlist = map(get_vars,varnames)
984
988
985 typelist = []
989 typelist = []
986 for vv in varlist:
990 for vv in varlist:
987 tt = type_name(vv)
991 tt = type_name(vv)
988
992
989 if tt=='instance':
993 if tt=='instance':
990 typelist.append( abbrevs.get(str(vv.__class__),
994 typelist.append( abbrevs.get(str(vv.__class__),
991 str(vv.__class__)))
995 str(vv.__class__)))
992 else:
996 else:
993 typelist.append(tt)
997 typelist.append(tt)
994
998
995 # column labels and # of spaces as separator
999 # column labels and # of spaces as separator
996 varlabel = 'Variable'
1000 varlabel = 'Variable'
997 typelabel = 'Type'
1001 typelabel = 'Type'
998 datalabel = 'Data/Info'
1002 datalabel = 'Data/Info'
999 colsep = 3
1003 colsep = 3
1000 # variable format strings
1004 # variable format strings
1001 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1005 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1002 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1006 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1003 aformat = "%s: %s elems, type `%s`, %s bytes"
1007 aformat = "%s: %s elems, type `%s`, %s bytes"
1004 # find the size of the columns to format the output nicely
1008 # find the size of the columns to format the output nicely
1005 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1009 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1006 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1010 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1007 # table header
1011 # table header
1008 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1012 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1009 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1013 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1010 # and the table itself
1014 # and the table itself
1011 kb = 1024
1015 kb = 1024
1012 Mb = 1048576 # kb**2
1016 Mb = 1048576 # kb**2
1013 for vname,var,vtype in zip(varnames,varlist,typelist):
1017 for vname,var,vtype in zip(varnames,varlist,typelist):
1014 print itpl(vformat),
1018 print itpl(vformat),
1015 if vtype in seq_types:
1019 if vtype in seq_types:
1016 print len(var)
1020 print len(var)
1017 elif vtype in [array_type,ndarray_type]:
1021 elif vtype in [array_type,ndarray_type]:
1018 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1022 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1019 if vtype==ndarray_type:
1023 if vtype==ndarray_type:
1020 # numpy
1024 # numpy
1021 vsize = var.size
1025 vsize = var.size
1022 vbytes = vsize*var.itemsize
1026 vbytes = vsize*var.itemsize
1023 vdtype = var.dtype
1027 vdtype = var.dtype
1024 else:
1028 else:
1025 # Numeric
1029 # Numeric
1026 vsize = Numeric.size(var)
1030 vsize = Numeric.size(var)
1027 vbytes = vsize*var.itemsize()
1031 vbytes = vsize*var.itemsize()
1028 vdtype = var.typecode()
1032 vdtype = var.typecode()
1029
1033
1030 if vbytes < 100000:
1034 if vbytes < 100000:
1031 print aformat % (vshape,vsize,vdtype,vbytes)
1035 print aformat % (vshape,vsize,vdtype,vbytes)
1032 else:
1036 else:
1033 print aformat % (vshape,vsize,vdtype,vbytes),
1037 print aformat % (vshape,vsize,vdtype,vbytes),
1034 if vbytes < Mb:
1038 if vbytes < Mb:
1035 print '(%s kb)' % (vbytes/kb,)
1039 print '(%s kb)' % (vbytes/kb,)
1036 else:
1040 else:
1037 print '(%s Mb)' % (vbytes/Mb,)
1041 print '(%s Mb)' % (vbytes/Mb,)
1038 else:
1042 else:
1039 try:
1043 try:
1040 vstr = str(var)
1044 vstr = str(var)
1041 except UnicodeEncodeError:
1045 except UnicodeEncodeError:
1042 vstr = unicode(var).encode(sys.getdefaultencoding(),
1046 vstr = unicode(var).encode(sys.getdefaultencoding(),
1043 'backslashreplace')
1047 'backslashreplace')
1044 vstr = vstr.replace('\n','\\n')
1048 vstr = vstr.replace('\n','\\n')
1045 if len(vstr) < 50:
1049 if len(vstr) < 50:
1046 print vstr
1050 print vstr
1047 else:
1051 else:
1048 printpl(vfmt_short)
1052 printpl(vfmt_short)
1049
1053
1050 def magic_reset(self, parameter_s=''):
1054 def magic_reset(self, parameter_s=''):
1051 """Resets the namespace by removing all names defined by the user.
1055 """Resets the namespace by removing all names defined by the user.
1052
1056
1053 Input/Output history are left around in case you need them."""
1057 Input/Output history are left around in case you need them."""
1054
1058
1055 ans = self.shell.ask_yes_no(
1059 ans = self.shell.ask_yes_no(
1056 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1060 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1057 if not ans:
1061 if not ans:
1058 print 'Nothing done.'
1062 print 'Nothing done.'
1059 return
1063 return
1060 user_ns = self.shell.user_ns
1064 user_ns = self.shell.user_ns
1061 for i in self.magic_who_ls():
1065 for i in self.magic_who_ls():
1062 del(user_ns[i])
1066 del(user_ns[i])
1063
1067
1064 # Also flush the private list of module references kept for script
1068 # Also flush the private list of module references kept for script
1065 # execution protection
1069 # execution protection
1066 self.shell._user_main_modules[:] = []
1070 self.shell._user_main_modules[:] = []
1067
1071
1068 def magic_logstart(self,parameter_s=''):
1072 def magic_logstart(self,parameter_s=''):
1069 """Start logging anywhere in a session.
1073 """Start logging anywhere in a session.
1070
1074
1071 %logstart [-o|-r|-t] [log_name [log_mode]]
1075 %logstart [-o|-r|-t] [log_name [log_mode]]
1072
1076
1073 If no name is given, it defaults to a file named 'ipython_log.py' in your
1077 If no name is given, it defaults to a file named 'ipython_log.py' in your
1074 current directory, in 'rotate' mode (see below).
1078 current directory, in 'rotate' mode (see below).
1075
1079
1076 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1080 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1077 history up to that point and then continues logging.
1081 history up to that point and then continues logging.
1078
1082
1079 %logstart takes a second optional parameter: logging mode. This can be one
1083 %logstart takes a second optional parameter: logging mode. This can be one
1080 of (note that the modes are given unquoted):\\
1084 of (note that the modes are given unquoted):\\
1081 append: well, that says it.\\
1085 append: well, that says it.\\
1082 backup: rename (if exists) to name~ and start name.\\
1086 backup: rename (if exists) to name~ and start name.\\
1083 global: single logfile in your home dir, appended to.\\
1087 global: single logfile in your home dir, appended to.\\
1084 over : overwrite existing log.\\
1088 over : overwrite existing log.\\
1085 rotate: create rotating logs name.1~, name.2~, etc.
1089 rotate: create rotating logs name.1~, name.2~, etc.
1086
1090
1087 Options:
1091 Options:
1088
1092
1089 -o: log also IPython's output. In this mode, all commands which
1093 -o: log also IPython's output. In this mode, all commands which
1090 generate an Out[NN] prompt are recorded to the logfile, right after
1094 generate an Out[NN] prompt are recorded to the logfile, right after
1091 their corresponding input line. The output lines are always
1095 their corresponding input line. The output lines are always
1092 prepended with a '#[Out]# ' marker, so that the log remains valid
1096 prepended with a '#[Out]# ' marker, so that the log remains valid
1093 Python code.
1097 Python code.
1094
1098
1095 Since this marker is always the same, filtering only the output from
1099 Since this marker is always the same, filtering only the output from
1096 a log is very easy, using for example a simple awk call:
1100 a log is very easy, using for example a simple awk call:
1097
1101
1098 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1102 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1099
1103
1100 -r: log 'raw' input. Normally, IPython's logs contain the processed
1104 -r: log 'raw' input. Normally, IPython's logs contain the processed
1101 input, so that user lines are logged in their final form, converted
1105 input, so that user lines are logged in their final form, converted
1102 into valid Python. For example, %Exit is logged as
1106 into valid Python. For example, %Exit is logged as
1103 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1107 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1104 exactly as typed, with no transformations applied.
1108 exactly as typed, with no transformations applied.
1105
1109
1106 -t: put timestamps before each input line logged (these are put in
1110 -t: put timestamps before each input line logged (these are put in
1107 comments)."""
1111 comments)."""
1108
1112
1109 opts,par = self.parse_options(parameter_s,'ort')
1113 opts,par = self.parse_options(parameter_s,'ort')
1110 log_output = 'o' in opts
1114 log_output = 'o' in opts
1111 log_raw_input = 'r' in opts
1115 log_raw_input = 'r' in opts
1112 timestamp = 't' in opts
1116 timestamp = 't' in opts
1113
1117
1114 rc = self.shell.rc
1118 rc = self.shell.rc
1115 logger = self.shell.logger
1119 logger = self.shell.logger
1116
1120
1117 # if no args are given, the defaults set in the logger constructor by
1121 # if no args are given, the defaults set in the logger constructor by
1118 # ipytohn remain valid
1122 # ipytohn remain valid
1119 if par:
1123 if par:
1120 try:
1124 try:
1121 logfname,logmode = par.split()
1125 logfname,logmode = par.split()
1122 except:
1126 except:
1123 logfname = par
1127 logfname = par
1124 logmode = 'backup'
1128 logmode = 'backup'
1125 else:
1129 else:
1126 logfname = logger.logfname
1130 logfname = logger.logfname
1127 logmode = logger.logmode
1131 logmode = logger.logmode
1128 # put logfname into rc struct as if it had been called on the command
1132 # put logfname into rc struct as if it had been called on the command
1129 # line, so it ends up saved in the log header Save it in case we need
1133 # line, so it ends up saved in the log header Save it in case we need
1130 # to restore it...
1134 # to restore it...
1131 old_logfile = rc.opts.get('logfile','')
1135 old_logfile = rc.opts.get('logfile','')
1132 if logfname:
1136 if logfname:
1133 logfname = os.path.expanduser(logfname)
1137 logfname = os.path.expanduser(logfname)
1134 rc.opts.logfile = logfname
1138 rc.opts.logfile = logfname
1135 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1139 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1136 try:
1140 try:
1137 started = logger.logstart(logfname,loghead,logmode,
1141 started = logger.logstart(logfname,loghead,logmode,
1138 log_output,timestamp,log_raw_input)
1142 log_output,timestamp,log_raw_input)
1139 except:
1143 except:
1140 rc.opts.logfile = old_logfile
1144 rc.opts.logfile = old_logfile
1141 warn("Couldn't start log: %s" % sys.exc_info()[1])
1145 warn("Couldn't start log: %s" % sys.exc_info()[1])
1142 else:
1146 else:
1143 # log input history up to this point, optionally interleaving
1147 # log input history up to this point, optionally interleaving
1144 # output if requested
1148 # output if requested
1145
1149
1146 if timestamp:
1150 if timestamp:
1147 # disable timestamping for the previous history, since we've
1151 # disable timestamping for the previous history, since we've
1148 # lost those already (no time machine here).
1152 # lost those already (no time machine here).
1149 logger.timestamp = False
1153 logger.timestamp = False
1150
1154
1151 if log_raw_input:
1155 if log_raw_input:
1152 input_hist = self.shell.input_hist_raw
1156 input_hist = self.shell.input_hist_raw
1153 else:
1157 else:
1154 input_hist = self.shell.input_hist
1158 input_hist = self.shell.input_hist
1155
1159
1156 if log_output:
1160 if log_output:
1157 log_write = logger.log_write
1161 log_write = logger.log_write
1158 output_hist = self.shell.output_hist
1162 output_hist = self.shell.output_hist
1159 for n in range(1,len(input_hist)-1):
1163 for n in range(1,len(input_hist)-1):
1160 log_write(input_hist[n].rstrip())
1164 log_write(input_hist[n].rstrip())
1161 if n in output_hist:
1165 if n in output_hist:
1162 log_write(repr(output_hist[n]),'output')
1166 log_write(repr(output_hist[n]),'output')
1163 else:
1167 else:
1164 logger.log_write(input_hist[1:])
1168 logger.log_write(input_hist[1:])
1165 if timestamp:
1169 if timestamp:
1166 # re-enable timestamping
1170 # re-enable timestamping
1167 logger.timestamp = True
1171 logger.timestamp = True
1168
1172
1169 print ('Activating auto-logging. '
1173 print ('Activating auto-logging. '
1170 'Current session state plus future input saved.')
1174 'Current session state plus future input saved.')
1171 logger.logstate()
1175 logger.logstate()
1172
1176
1173 def magic_logstop(self,parameter_s=''):
1177 def magic_logstop(self,parameter_s=''):
1174 """Fully stop logging and close log file.
1178 """Fully stop logging and close log file.
1175
1179
1176 In order to start logging again, a new %logstart call needs to be made,
1180 In order to start logging again, a new %logstart call needs to be made,
1177 possibly (though not necessarily) with a new filename, mode and other
1181 possibly (though not necessarily) with a new filename, mode and other
1178 options."""
1182 options."""
1179 self.logger.logstop()
1183 self.logger.logstop()
1180
1184
1181 def magic_logoff(self,parameter_s=''):
1185 def magic_logoff(self,parameter_s=''):
1182 """Temporarily stop logging.
1186 """Temporarily stop logging.
1183
1187
1184 You must have previously started logging."""
1188 You must have previously started logging."""
1185 self.shell.logger.switch_log(0)
1189 self.shell.logger.switch_log(0)
1186
1190
1187 def magic_logon(self,parameter_s=''):
1191 def magic_logon(self,parameter_s=''):
1188 """Restart logging.
1192 """Restart logging.
1189
1193
1190 This function is for restarting logging which you've temporarily
1194 This function is for restarting logging which you've temporarily
1191 stopped with %logoff. For starting logging for the first time, you
1195 stopped with %logoff. For starting logging for the first time, you
1192 must use the %logstart function, which allows you to specify an
1196 must use the %logstart function, which allows you to specify an
1193 optional log filename."""
1197 optional log filename."""
1194
1198
1195 self.shell.logger.switch_log(1)
1199 self.shell.logger.switch_log(1)
1196
1200
1197 def magic_logstate(self,parameter_s=''):
1201 def magic_logstate(self,parameter_s=''):
1198 """Print the status of the logging system."""
1202 """Print the status of the logging system."""
1199
1203
1200 self.shell.logger.logstate()
1204 self.shell.logger.logstate()
1201
1205
1202 def magic_pdb(self, parameter_s=''):
1206 def magic_pdb(self, parameter_s=''):
1203 """Control the automatic calling of the pdb interactive debugger.
1207 """Control the automatic calling of the pdb interactive debugger.
1204
1208
1205 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1209 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1206 argument it works as a toggle.
1210 argument it works as a toggle.
1207
1211
1208 When an exception is triggered, IPython can optionally call the
1212 When an exception is triggered, IPython can optionally call the
1209 interactive pdb debugger after the traceback printout. %pdb toggles
1213 interactive pdb debugger after the traceback printout. %pdb toggles
1210 this feature on and off.
1214 this feature on and off.
1211
1215
1212 The initial state of this feature is set in your ipythonrc
1216 The initial state of this feature is set in your ipythonrc
1213 configuration file (the variable is called 'pdb').
1217 configuration file (the variable is called 'pdb').
1214
1218
1215 If you want to just activate the debugger AFTER an exception has fired,
1219 If you want to just activate the debugger AFTER an exception has fired,
1216 without having to type '%pdb on' and rerunning your code, you can use
1220 without having to type '%pdb on' and rerunning your code, you can use
1217 the %debug magic."""
1221 the %debug magic."""
1218
1222
1219 par = parameter_s.strip().lower()
1223 par = parameter_s.strip().lower()
1220
1224
1221 if par:
1225 if par:
1222 try:
1226 try:
1223 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1227 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1224 except KeyError:
1228 except KeyError:
1225 print ('Incorrect argument. Use on/1, off/0, '
1229 print ('Incorrect argument. Use on/1, off/0, '
1226 'or nothing for a toggle.')
1230 'or nothing for a toggle.')
1227 return
1231 return
1228 else:
1232 else:
1229 # toggle
1233 # toggle
1230 new_pdb = not self.shell.call_pdb
1234 new_pdb = not self.shell.call_pdb
1231
1235
1232 # set on the shell
1236 # set on the shell
1233 self.shell.call_pdb = new_pdb
1237 self.shell.call_pdb = new_pdb
1234 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1238 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1235
1239
1236 def magic_debug(self, parameter_s=''):
1240 def magic_debug(self, parameter_s=''):
1237 """Activate the interactive debugger in post-mortem mode.
1241 """Activate the interactive debugger in post-mortem mode.
1238
1242
1239 If an exception has just occurred, this lets you inspect its stack
1243 If an exception has just occurred, this lets you inspect its stack
1240 frames interactively. Note that this will always work only on the last
1244 frames interactively. Note that this will always work only on the last
1241 traceback that occurred, so you must call this quickly after an
1245 traceback that occurred, so you must call this quickly after an
1242 exception that you wish to inspect has fired, because if another one
1246 exception that you wish to inspect has fired, because if another one
1243 occurs, it clobbers the previous one.
1247 occurs, it clobbers the previous one.
1244
1248
1245 If you want IPython to automatically do this on every exception, see
1249 If you want IPython to automatically do this on every exception, see
1246 the %pdb magic for more details.
1250 the %pdb magic for more details.
1247 """
1251 """
1248
1252
1249 self.shell.debugger(force=True)
1253 self.shell.debugger(force=True)
1250
1254
1251 @testdec.skip_doctest
1255 @testdec.skip_doctest
1252 def magic_prun(self, parameter_s ='',user_mode=1,
1256 def magic_prun(self, parameter_s ='',user_mode=1,
1253 opts=None,arg_lst=None,prog_ns=None):
1257 opts=None,arg_lst=None,prog_ns=None):
1254
1258
1255 """Run a statement through the python code profiler.
1259 """Run a statement through the python code profiler.
1256
1260
1257 Usage:
1261 Usage:
1258 %prun [options] statement
1262 %prun [options] statement
1259
1263
1260 The given statement (which doesn't require quote marks) is run via the
1264 The given statement (which doesn't require quote marks) is run via the
1261 python profiler in a manner similar to the profile.run() function.
1265 python profiler in a manner similar to the profile.run() function.
1262 Namespaces are internally managed to work correctly; profile.run
1266 Namespaces are internally managed to work correctly; profile.run
1263 cannot be used in IPython because it makes certain assumptions about
1267 cannot be used in IPython because it makes certain assumptions about
1264 namespaces which do not hold under IPython.
1268 namespaces which do not hold under IPython.
1265
1269
1266 Options:
1270 Options:
1267
1271
1268 -l <limit>: you can place restrictions on what or how much of the
1272 -l <limit>: you can place restrictions on what or how much of the
1269 profile gets printed. The limit value can be:
1273 profile gets printed. The limit value can be:
1270
1274
1271 * A string: only information for function names containing this string
1275 * A string: only information for function names containing this string
1272 is printed.
1276 is printed.
1273
1277
1274 * An integer: only these many lines are printed.
1278 * An integer: only these many lines are printed.
1275
1279
1276 * A float (between 0 and 1): this fraction of the report is printed
1280 * A float (between 0 and 1): this fraction of the report is printed
1277 (for example, use a limit of 0.4 to see the topmost 40% only).
1281 (for example, use a limit of 0.4 to see the topmost 40% only).
1278
1282
1279 You can combine several limits with repeated use of the option. For
1283 You can combine several limits with repeated use of the option. For
1280 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1284 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1281 information about class constructors.
1285 information about class constructors.
1282
1286
1283 -r: return the pstats.Stats object generated by the profiling. This
1287 -r: return the pstats.Stats object generated by the profiling. This
1284 object has all the information about the profile in it, and you can
1288 object has all the information about the profile in it, and you can
1285 later use it for further analysis or in other functions.
1289 later use it for further analysis or in other functions.
1286
1290
1287 -s <key>: sort profile by given key. You can provide more than one key
1291 -s <key>: sort profile by given key. You can provide more than one key
1288 by using the option several times: '-s key1 -s key2 -s key3...'. The
1292 by using the option several times: '-s key1 -s key2 -s key3...'. The
1289 default sorting key is 'time'.
1293 default sorting key is 'time'.
1290
1294
1291 The following is copied verbatim from the profile documentation
1295 The following is copied verbatim from the profile documentation
1292 referenced below:
1296 referenced below:
1293
1297
1294 When more than one key is provided, additional keys are used as
1298 When more than one key is provided, additional keys are used as
1295 secondary criteria when the there is equality in all keys selected
1299 secondary criteria when the there is equality in all keys selected
1296 before them.
1300 before them.
1297
1301
1298 Abbreviations can be used for any key names, as long as the
1302 Abbreviations can be used for any key names, as long as the
1299 abbreviation is unambiguous. The following are the keys currently
1303 abbreviation is unambiguous. The following are the keys currently
1300 defined:
1304 defined:
1301
1305
1302 Valid Arg Meaning
1306 Valid Arg Meaning
1303 "calls" call count
1307 "calls" call count
1304 "cumulative" cumulative time
1308 "cumulative" cumulative time
1305 "file" file name
1309 "file" file name
1306 "module" file name
1310 "module" file name
1307 "pcalls" primitive call count
1311 "pcalls" primitive call count
1308 "line" line number
1312 "line" line number
1309 "name" function name
1313 "name" function name
1310 "nfl" name/file/line
1314 "nfl" name/file/line
1311 "stdname" standard name
1315 "stdname" standard name
1312 "time" internal time
1316 "time" internal time
1313
1317
1314 Note that all sorts on statistics are in descending order (placing
1318 Note that all sorts on statistics are in descending order (placing
1315 most time consuming items first), where as name, file, and line number
1319 most time consuming items first), where as name, file, and line number
1316 searches are in ascending order (i.e., alphabetical). The subtle
1320 searches are in ascending order (i.e., alphabetical). The subtle
1317 distinction between "nfl" and "stdname" is that the standard name is a
1321 distinction between "nfl" and "stdname" is that the standard name is a
1318 sort of the name as printed, which means that the embedded line
1322 sort of the name as printed, which means that the embedded line
1319 numbers get compared in an odd way. For example, lines 3, 20, and 40
1323 numbers get compared in an odd way. For example, lines 3, 20, and 40
1320 would (if the file names were the same) appear in the string order
1324 would (if the file names were the same) appear in the string order
1321 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1325 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1322 line numbers. In fact, sort_stats("nfl") is the same as
1326 line numbers. In fact, sort_stats("nfl") is the same as
1323 sort_stats("name", "file", "line").
1327 sort_stats("name", "file", "line").
1324
1328
1325 -T <filename>: save profile results as shown on screen to a text
1329 -T <filename>: save profile results as shown on screen to a text
1326 file. The profile is still shown on screen.
1330 file. The profile is still shown on screen.
1327
1331
1328 -D <filename>: save (via dump_stats) profile statistics to given
1332 -D <filename>: save (via dump_stats) profile statistics to given
1329 filename. This data is in a format understod by the pstats module, and
1333 filename. This data is in a format understod by the pstats module, and
1330 is generated by a call to the dump_stats() method of profile
1334 is generated by a call to the dump_stats() method of profile
1331 objects. The profile is still shown on screen.
1335 objects. The profile is still shown on screen.
1332
1336
1333 If you want to run complete programs under the profiler's control, use
1337 If you want to run complete programs under the profiler's control, use
1334 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1338 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1335 contains profiler specific options as described here.
1339 contains profiler specific options as described here.
1336
1340
1337 You can read the complete documentation for the profile module with::
1341 You can read the complete documentation for the profile module with::
1338
1342
1339 In [1]: import profile; profile.help()
1343 In [1]: import profile; profile.help()
1340 """
1344 """
1341
1345
1342 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1346 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1343 # protect user quote marks
1347 # protect user quote marks
1344 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1348 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1345
1349
1346 if user_mode: # regular user call
1350 if user_mode: # regular user call
1347 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1351 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1348 list_all=1)
1352 list_all=1)
1349 namespace = self.shell.user_ns
1353 namespace = self.shell.user_ns
1350 else: # called to run a program by %run -p
1354 else: # called to run a program by %run -p
1351 try:
1355 try:
1352 filename = get_py_filename(arg_lst[0])
1356 filename = get_py_filename(arg_lst[0])
1353 except IOError,msg:
1357 except IOError,msg:
1354 error(msg)
1358 error(msg)
1355 return
1359 return
1356
1360
1357 arg_str = 'execfile(filename,prog_ns)'
1361 arg_str = 'execfile(filename,prog_ns)'
1358 namespace = locals()
1362 namespace = locals()
1359
1363
1360 opts.merge(opts_def)
1364 opts.merge(opts_def)
1361
1365
1362 prof = profile.Profile()
1366 prof = profile.Profile()
1363 try:
1367 try:
1364 prof = prof.runctx(arg_str,namespace,namespace)
1368 prof = prof.runctx(arg_str,namespace,namespace)
1365 sys_exit = ''
1369 sys_exit = ''
1366 except SystemExit:
1370 except SystemExit:
1367 sys_exit = """*** SystemExit exception caught in code being profiled."""
1371 sys_exit = """*** SystemExit exception caught in code being profiled."""
1368
1372
1369 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1373 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1370
1374
1371 lims = opts.l
1375 lims = opts.l
1372 if lims:
1376 if lims:
1373 lims = [] # rebuild lims with ints/floats/strings
1377 lims = [] # rebuild lims with ints/floats/strings
1374 for lim in opts.l:
1378 for lim in opts.l:
1375 try:
1379 try:
1376 lims.append(int(lim))
1380 lims.append(int(lim))
1377 except ValueError:
1381 except ValueError:
1378 try:
1382 try:
1379 lims.append(float(lim))
1383 lims.append(float(lim))
1380 except ValueError:
1384 except ValueError:
1381 lims.append(lim)
1385 lims.append(lim)
1382
1386
1383 # Trap output.
1387 # Trap output.
1384 stdout_trap = StringIO()
1388 stdout_trap = StringIO()
1385
1389
1386 if hasattr(stats,'stream'):
1390 if hasattr(stats,'stream'):
1387 # In newer versions of python, the stats object has a 'stream'
1391 # In newer versions of python, the stats object has a 'stream'
1388 # attribute to write into.
1392 # attribute to write into.
1389 stats.stream = stdout_trap
1393 stats.stream = stdout_trap
1390 stats.print_stats(*lims)
1394 stats.print_stats(*lims)
1391 else:
1395 else:
1392 # For older versions, we manually redirect stdout during printing
1396 # For older versions, we manually redirect stdout during printing
1393 sys_stdout = sys.stdout
1397 sys_stdout = sys.stdout
1394 try:
1398 try:
1395 sys.stdout = stdout_trap
1399 sys.stdout = stdout_trap
1396 stats.print_stats(*lims)
1400 stats.print_stats(*lims)
1397 finally:
1401 finally:
1398 sys.stdout = sys_stdout
1402 sys.stdout = sys_stdout
1399
1403
1400 output = stdout_trap.getvalue()
1404 output = stdout_trap.getvalue()
1401 output = output.rstrip()
1405 output = output.rstrip()
1402
1406
1403 page(output,screen_lines=self.shell.rc.screen_length)
1407 page(output,screen_lines=self.shell.rc.screen_length)
1404 print sys_exit,
1408 print sys_exit,
1405
1409
1406 dump_file = opts.D[0]
1410 dump_file = opts.D[0]
1407 text_file = opts.T[0]
1411 text_file = opts.T[0]
1408 if dump_file:
1412 if dump_file:
1409 prof.dump_stats(dump_file)
1413 prof.dump_stats(dump_file)
1410 print '\n*** Profile stats marshalled to file',\
1414 print '\n*** Profile stats marshalled to file',\
1411 `dump_file`+'.',sys_exit
1415 `dump_file`+'.',sys_exit
1412 if text_file:
1416 if text_file:
1413 pfile = file(text_file,'w')
1417 pfile = file(text_file,'w')
1414 pfile.write(output)
1418 pfile.write(output)
1415 pfile.close()
1419 pfile.close()
1416 print '\n*** Profile printout saved to text file',\
1420 print '\n*** Profile printout saved to text file',\
1417 `text_file`+'.',sys_exit
1421 `text_file`+'.',sys_exit
1418
1422
1419 if opts.has_key('r'):
1423 if opts.has_key('r'):
1420 return stats
1424 return stats
1421 else:
1425 else:
1422 return None
1426 return None
1423
1427
1424 @testdec.skip_doctest
1428 @testdec.skip_doctest
1425 def magic_run(self, parameter_s ='',runner=None):
1429 def magic_run(self, parameter_s ='',runner=None):
1426 """Run the named file inside IPython as a program.
1430 """Run the named file inside IPython as a program.
1427
1431
1428 Usage:\\
1432 Usage:\\
1429 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1433 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1430
1434
1431 Parameters after the filename are passed as command-line arguments to
1435 Parameters after the filename are passed as command-line arguments to
1432 the program (put in sys.argv). Then, control returns to IPython's
1436 the program (put in sys.argv). Then, control returns to IPython's
1433 prompt.
1437 prompt.
1434
1438
1435 This is similar to running at a system prompt:\\
1439 This is similar to running at a system prompt:\\
1436 $ python file args\\
1440 $ python file args\\
1437 but with the advantage of giving you IPython's tracebacks, and of
1441 but with the advantage of giving you IPython's tracebacks, and of
1438 loading all variables into your interactive namespace for further use
1442 loading all variables into your interactive namespace for further use
1439 (unless -p is used, see below).
1443 (unless -p is used, see below).
1440
1444
1441 The file is executed in a namespace initially consisting only of
1445 The file is executed in a namespace initially consisting only of
1442 __name__=='__main__' and sys.argv constructed as indicated. It thus
1446 __name__=='__main__' and sys.argv constructed as indicated. It thus
1443 sees its environment as if it were being run as a stand-alone program
1447 sees its environment as if it were being run as a stand-alone program
1444 (except for sharing global objects such as previously imported
1448 (except for sharing global objects such as previously imported
1445 modules). But after execution, the IPython interactive namespace gets
1449 modules). But after execution, the IPython interactive namespace gets
1446 updated with all variables defined in the program (except for __name__
1450 updated with all variables defined in the program (except for __name__
1447 and sys.argv). This allows for very convenient loading of code for
1451 and sys.argv). This allows for very convenient loading of code for
1448 interactive work, while giving each program a 'clean sheet' to run in.
1452 interactive work, while giving each program a 'clean sheet' to run in.
1449
1453
1450 Options:
1454 Options:
1451
1455
1452 -n: __name__ is NOT set to '__main__', but to the running file's name
1456 -n: __name__ is NOT set to '__main__', but to the running file's name
1453 without extension (as python does under import). This allows running
1457 without extension (as python does under import). This allows running
1454 scripts and reloading the definitions in them without calling code
1458 scripts and reloading the definitions in them without calling code
1455 protected by an ' if __name__ == "__main__" ' clause.
1459 protected by an ' if __name__ == "__main__" ' clause.
1456
1460
1457 -i: run the file in IPython's namespace instead of an empty one. This
1461 -i: run the file in IPython's namespace instead of an empty one. This
1458 is useful if you are experimenting with code written in a text editor
1462 is useful if you are experimenting with code written in a text editor
1459 which depends on variables defined interactively.
1463 which depends on variables defined interactively.
1460
1464
1461 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1465 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1462 being run. This is particularly useful if IPython is being used to
1466 being run. This is particularly useful if IPython is being used to
1463 run unittests, which always exit with a sys.exit() call. In such
1467 run unittests, which always exit with a sys.exit() call. In such
1464 cases you are interested in the output of the test results, not in
1468 cases you are interested in the output of the test results, not in
1465 seeing a traceback of the unittest module.
1469 seeing a traceback of the unittest module.
1466
1470
1467 -t: print timing information at the end of the run. IPython will give
1471 -t: print timing information at the end of the run. IPython will give
1468 you an estimated CPU time consumption for your script, which under
1472 you an estimated CPU time consumption for your script, which under
1469 Unix uses the resource module to avoid the wraparound problems of
1473 Unix uses the resource module to avoid the wraparound problems of
1470 time.clock(). Under Unix, an estimate of time spent on system tasks
1474 time.clock(). Under Unix, an estimate of time spent on system tasks
1471 is also given (for Windows platforms this is reported as 0.0).
1475 is also given (for Windows platforms this is reported as 0.0).
1472
1476
1473 If -t is given, an additional -N<N> option can be given, where <N>
1477 If -t is given, an additional -N<N> option can be given, where <N>
1474 must be an integer indicating how many times you want the script to
1478 must be an integer indicating how many times you want the script to
1475 run. The final timing report will include total and per run results.
1479 run. The final timing report will include total and per run results.
1476
1480
1477 For example (testing the script uniq_stable.py):
1481 For example (testing the script uniq_stable.py):
1478
1482
1479 In [1]: run -t uniq_stable
1483 In [1]: run -t uniq_stable
1480
1484
1481 IPython CPU timings (estimated):\\
1485 IPython CPU timings (estimated):\\
1482 User : 0.19597 s.\\
1486 User : 0.19597 s.\\
1483 System: 0.0 s.\\
1487 System: 0.0 s.\\
1484
1488
1485 In [2]: run -t -N5 uniq_stable
1489 In [2]: run -t -N5 uniq_stable
1486
1490
1487 IPython CPU timings (estimated):\\
1491 IPython CPU timings (estimated):\\
1488 Total runs performed: 5\\
1492 Total runs performed: 5\\
1489 Times : Total Per run\\
1493 Times : Total Per run\\
1490 User : 0.910862 s, 0.1821724 s.\\
1494 User : 0.910862 s, 0.1821724 s.\\
1491 System: 0.0 s, 0.0 s.
1495 System: 0.0 s, 0.0 s.
1492
1496
1493 -d: run your program under the control of pdb, the Python debugger.
1497 -d: run your program under the control of pdb, the Python debugger.
1494 This allows you to execute your program step by step, watch variables,
1498 This allows you to execute your program step by step, watch variables,
1495 etc. Internally, what IPython does is similar to calling:
1499 etc. Internally, what IPython does is similar to calling:
1496
1500
1497 pdb.run('execfile("YOURFILENAME")')
1501 pdb.run('execfile("YOURFILENAME")')
1498
1502
1499 with a breakpoint set on line 1 of your file. You can change the line
1503 with a breakpoint set on line 1 of your file. You can change the line
1500 number for this automatic breakpoint to be <N> by using the -bN option
1504 number for this automatic breakpoint to be <N> by using the -bN option
1501 (where N must be an integer). For example:
1505 (where N must be an integer). For example:
1502
1506
1503 %run -d -b40 myscript
1507 %run -d -b40 myscript
1504
1508
1505 will set the first breakpoint at line 40 in myscript.py. Note that
1509 will set the first breakpoint at line 40 in myscript.py. Note that
1506 the first breakpoint must be set on a line which actually does
1510 the first breakpoint must be set on a line which actually does
1507 something (not a comment or docstring) for it to stop execution.
1511 something (not a comment or docstring) for it to stop execution.
1508
1512
1509 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1513 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1510 first enter 'c' (without qoutes) to start execution up to the first
1514 first enter 'c' (without qoutes) to start execution up to the first
1511 breakpoint.
1515 breakpoint.
1512
1516
1513 Entering 'help' gives information about the use of the debugger. You
1517 Entering 'help' gives information about the use of the debugger. You
1514 can easily see pdb's full documentation with "import pdb;pdb.help()"
1518 can easily see pdb's full documentation with "import pdb;pdb.help()"
1515 at a prompt.
1519 at a prompt.
1516
1520
1517 -p: run program under the control of the Python profiler module (which
1521 -p: run program under the control of the Python profiler module (which
1518 prints a detailed report of execution times, function calls, etc).
1522 prints a detailed report of execution times, function calls, etc).
1519
1523
1520 You can pass other options after -p which affect the behavior of the
1524 You can pass other options after -p which affect the behavior of the
1521 profiler itself. See the docs for %prun for details.
1525 profiler itself. See the docs for %prun for details.
1522
1526
1523 In this mode, the program's variables do NOT propagate back to the
1527 In this mode, the program's variables do NOT propagate back to the
1524 IPython interactive namespace (because they remain in the namespace
1528 IPython interactive namespace (because they remain in the namespace
1525 where the profiler executes them).
1529 where the profiler executes them).
1526
1530
1527 Internally this triggers a call to %prun, see its documentation for
1531 Internally this triggers a call to %prun, see its documentation for
1528 details on the options available specifically for profiling.
1532 details on the options available specifically for profiling.
1529
1533
1530 There is one special usage for which the text above doesn't apply:
1534 There is one special usage for which the text above doesn't apply:
1531 if the filename ends with .ipy, the file is run as ipython script,
1535 if the filename ends with .ipy, the file is run as ipython script,
1532 just as if the commands were written on IPython prompt.
1536 just as if the commands were written on IPython prompt.
1533 """
1537 """
1534
1538
1535 # get arguments and set sys.argv for program to be run.
1539 # get arguments and set sys.argv for program to be run.
1536 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1540 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1537 mode='list',list_all=1)
1541 mode='list',list_all=1)
1538
1542
1539 try:
1543 try:
1540 filename = get_py_filename(arg_lst[0])
1544 filename = get_py_filename(arg_lst[0])
1541 except IndexError:
1545 except IndexError:
1542 warn('you must provide at least a filename.')
1546 warn('you must provide at least a filename.')
1543 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1547 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1544 return
1548 return
1545 except IOError,msg:
1549 except IOError,msg:
1546 error(msg)
1550 error(msg)
1547 return
1551 return
1548
1552
1549 if filename.lower().endswith('.ipy'):
1553 if filename.lower().endswith('.ipy'):
1550 self.api.runlines(open(filename).read())
1554 self.api.runlines(open(filename).read())
1551 return
1555 return
1552
1556
1553 # Control the response to exit() calls made by the script being run
1557 # Control the response to exit() calls made by the script being run
1554 exit_ignore = opts.has_key('e')
1558 exit_ignore = opts.has_key('e')
1555
1559
1556 # Make sure that the running script gets a proper sys.argv as if it
1560 # Make sure that the running script gets a proper sys.argv as if it
1557 # were run from a system shell.
1561 # were run from a system shell.
1558 save_argv = sys.argv # save it for later restoring
1562 save_argv = sys.argv # save it for later restoring
1559 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1563 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1560
1564
1561 if opts.has_key('i'):
1565 if opts.has_key('i'):
1562 # Run in user's interactive namespace
1566 # Run in user's interactive namespace
1563 prog_ns = self.shell.user_ns
1567 prog_ns = self.shell.user_ns
1564 __name__save = self.shell.user_ns['__name__']
1568 __name__save = self.shell.user_ns['__name__']
1565 prog_ns['__name__'] = '__main__'
1569 prog_ns['__name__'] = '__main__'
1566 main_mod = FakeModule(prog_ns)
1570 main_mod = FakeModule(prog_ns)
1567 else:
1571 else:
1568 # Run in a fresh, empty namespace
1572 # Run in a fresh, empty namespace
1569 if opts.has_key('n'):
1573 if opts.has_key('n'):
1570 name = os.path.splitext(os.path.basename(filename))[0]
1574 name = os.path.splitext(os.path.basename(filename))[0]
1571 else:
1575 else:
1572 name = '__main__'
1576 name = '__main__'
1573 main_mod = FakeModule()
1577 main_mod = FakeModule()
1574 prog_ns = main_mod.__dict__
1578 prog_ns = main_mod.__dict__
1575 prog_ns['__name__'] = name
1579 prog_ns['__name__'] = name
1576 # The shell MUST hold a reference to main_mod so after %run exits,
1580 # The shell MUST hold a reference to main_mod so after %run exits,
1577 # the python deletion mechanism doesn't zero it out (leaving
1581 # the python deletion mechanism doesn't zero it out (leaving
1578 # dangling references)
1582 # dangling references)
1579 self.shell._user_main_modules.append(main_mod)
1583 self.shell._user_main_modules.append(main_mod)
1580
1584
1581 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1585 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1582 # set the __file__ global in the script's namespace
1586 # set the __file__ global in the script's namespace
1583 prog_ns['__file__'] = filename
1587 prog_ns['__file__'] = filename
1584
1588
1585 # pickle fix. See iplib for an explanation. But we need to make sure
1589 # pickle fix. See iplib for an explanation. But we need to make sure
1586 # that, if we overwrite __main__, we replace it at the end
1590 # that, if we overwrite __main__, we replace it at the end
1587 main_mod_name = prog_ns['__name__']
1591 main_mod_name = prog_ns['__name__']
1588
1592
1589 if main_mod_name == '__main__':
1593 if main_mod_name == '__main__':
1590 restore_main = sys.modules['__main__']
1594 restore_main = sys.modules['__main__']
1591 else:
1595 else:
1592 restore_main = False
1596 restore_main = False
1593
1597
1594 # This needs to be undone at the end to prevent holding references to
1598 # This needs to be undone at the end to prevent holding references to
1595 # every single object ever created.
1599 # every single object ever created.
1596 sys.modules[main_mod_name] = main_mod
1600 sys.modules[main_mod_name] = main_mod
1597
1601
1598 stats = None
1602 stats = None
1599 try:
1603 try:
1600 self.shell.savehist()
1604 self.shell.savehist()
1601
1605
1602 if opts.has_key('p'):
1606 if opts.has_key('p'):
1603 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1607 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1604 else:
1608 else:
1605 if opts.has_key('d'):
1609 if opts.has_key('d'):
1606 deb = Debugger.Pdb(self.shell.rc.colors)
1610 deb = Debugger.Pdb(self.shell.rc.colors)
1607 # reset Breakpoint state, which is moronically kept
1611 # reset Breakpoint state, which is moronically kept
1608 # in a class
1612 # in a class
1609 bdb.Breakpoint.next = 1
1613 bdb.Breakpoint.next = 1
1610 bdb.Breakpoint.bplist = {}
1614 bdb.Breakpoint.bplist = {}
1611 bdb.Breakpoint.bpbynumber = [None]
1615 bdb.Breakpoint.bpbynumber = [None]
1612 # Set an initial breakpoint to stop execution
1616 # Set an initial breakpoint to stop execution
1613 maxtries = 10
1617 maxtries = 10
1614 bp = int(opts.get('b',[1])[0])
1618 bp = int(opts.get('b',[1])[0])
1615 checkline = deb.checkline(filename,bp)
1619 checkline = deb.checkline(filename,bp)
1616 if not checkline:
1620 if not checkline:
1617 for bp in range(bp+1,bp+maxtries+1):
1621 for bp in range(bp+1,bp+maxtries+1):
1618 if deb.checkline(filename,bp):
1622 if deb.checkline(filename,bp):
1619 break
1623 break
1620 else:
1624 else:
1621 msg = ("\nI failed to find a valid line to set "
1625 msg = ("\nI failed to find a valid line to set "
1622 "a breakpoint\n"
1626 "a breakpoint\n"
1623 "after trying up to line: %s.\n"
1627 "after trying up to line: %s.\n"
1624 "Please set a valid breakpoint manually "
1628 "Please set a valid breakpoint manually "
1625 "with the -b option." % bp)
1629 "with the -b option." % bp)
1626 error(msg)
1630 error(msg)
1627 return
1631 return
1628 # if we find a good linenumber, set the breakpoint
1632 # if we find a good linenumber, set the breakpoint
1629 deb.do_break('%s:%s' % (filename,bp))
1633 deb.do_break('%s:%s' % (filename,bp))
1630 # Start file run
1634 # Start file run
1631 print "NOTE: Enter 'c' at the",
1635 print "NOTE: Enter 'c' at the",
1632 print "%s prompt to start your script." % deb.prompt
1636 print "%s prompt to start your script." % deb.prompt
1633 try:
1637 try:
1634 deb.run('execfile("%s")' % filename,prog_ns)
1638 deb.run('execfile("%s")' % filename,prog_ns)
1635
1639
1636 except:
1640 except:
1637 etype, value, tb = sys.exc_info()
1641 etype, value, tb = sys.exc_info()
1638 # Skip three frames in the traceback: the %run one,
1642 # Skip three frames in the traceback: the %run one,
1639 # one inside bdb.py, and the command-line typed by the
1643 # one inside bdb.py, and the command-line typed by the
1640 # user (run by exec in pdb itself).
1644 # user (run by exec in pdb itself).
1641 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1645 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1642 else:
1646 else:
1643 if runner is None:
1647 if runner is None:
1644 runner = self.shell.safe_execfile
1648 runner = self.shell.safe_execfile
1645 if opts.has_key('t'):
1649 if opts.has_key('t'):
1646 # timed execution
1650 # timed execution
1647 try:
1651 try:
1648 nruns = int(opts['N'][0])
1652 nruns = int(opts['N'][0])
1649 if nruns < 1:
1653 if nruns < 1:
1650 error('Number of runs must be >=1')
1654 error('Number of runs must be >=1')
1651 return
1655 return
1652 except (KeyError):
1656 except (KeyError):
1653 nruns = 1
1657 nruns = 1
1654 if nruns == 1:
1658 if nruns == 1:
1655 t0 = clock2()
1659 t0 = clock2()
1656 runner(filename,prog_ns,prog_ns,
1660 runner(filename,prog_ns,prog_ns,
1657 exit_ignore=exit_ignore)
1661 exit_ignore=exit_ignore)
1658 t1 = clock2()
1662 t1 = clock2()
1659 t_usr = t1[0]-t0[0]
1663 t_usr = t1[0]-t0[0]
1660 t_sys = t1[1]-t1[1]
1664 t_sys = t1[1]-t1[1]
1661 print "\nIPython CPU timings (estimated):"
1665 print "\nIPython CPU timings (estimated):"
1662 print " User : %10s s." % t_usr
1666 print " User : %10s s." % t_usr
1663 print " System: %10s s." % t_sys
1667 print " System: %10s s." % t_sys
1664 else:
1668 else:
1665 runs = range(nruns)
1669 runs = range(nruns)
1666 t0 = clock2()
1670 t0 = clock2()
1667 for nr in runs:
1671 for nr in runs:
1668 runner(filename,prog_ns,prog_ns,
1672 runner(filename,prog_ns,prog_ns,
1669 exit_ignore=exit_ignore)
1673 exit_ignore=exit_ignore)
1670 t1 = clock2()
1674 t1 = clock2()
1671 t_usr = t1[0]-t0[0]
1675 t_usr = t1[0]-t0[0]
1672 t_sys = t1[1]-t1[1]
1676 t_sys = t1[1]-t1[1]
1673 print "\nIPython CPU timings (estimated):"
1677 print "\nIPython CPU timings (estimated):"
1674 print "Total runs performed:",nruns
1678 print "Total runs performed:",nruns
1675 print " Times : %10s %10s" % ('Total','Per run')
1679 print " Times : %10s %10s" % ('Total','Per run')
1676 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1680 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1677 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1681 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1678
1682
1679 else:
1683 else:
1680 # regular execution
1684 # regular execution
1681 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1685 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1682 if opts.has_key('i'):
1686 if opts.has_key('i'):
1683 self.shell.user_ns['__name__'] = __name__save
1687 self.shell.user_ns['__name__'] = __name__save
1684 else:
1688 else:
1685 # update IPython interactive namespace
1689 # update IPython interactive namespace
1686 del prog_ns['__name__']
1690 del prog_ns['__name__']
1687 self.shell.user_ns.update(prog_ns)
1691 self.shell.user_ns.update(prog_ns)
1688 finally:
1692 finally:
1689 # Ensure key global structures are restored
1693 # Ensure key global structures are restored
1690 sys.argv = save_argv
1694 sys.argv = save_argv
1691 if restore_main:
1695 if restore_main:
1692 sys.modules['__main__'] = restore_main
1696 sys.modules['__main__'] = restore_main
1693 else:
1697 else:
1694 # Remove from sys.modules the reference to main_mod we'd
1698 # Remove from sys.modules the reference to main_mod we'd
1695 # added. Otherwise it will trap references to objects
1699 # added. Otherwise it will trap references to objects
1696 # contained therein.
1700 # contained therein.
1697 del sys.modules[main_mod_name]
1701 del sys.modules[main_mod_name]
1698 self.shell.reloadhist()
1702 self.shell.reloadhist()
1699
1703
1700 return stats
1704 return stats
1701
1705
1702 def magic_runlog(self, parameter_s =''):
1706 def magic_runlog(self, parameter_s =''):
1703 """Run files as logs.
1707 """Run files as logs.
1704
1708
1705 Usage:\\
1709 Usage:\\
1706 %runlog file1 file2 ...
1710 %runlog file1 file2 ...
1707
1711
1708 Run the named files (treating them as log files) in sequence inside
1712 Run the named files (treating them as log files) in sequence inside
1709 the interpreter, and return to the prompt. This is much slower than
1713 the interpreter, and return to the prompt. This is much slower than
1710 %run because each line is executed in a try/except block, but it
1714 %run because each line is executed in a try/except block, but it
1711 allows running files with syntax errors in them.
1715 allows running files with syntax errors in them.
1712
1716
1713 Normally IPython will guess when a file is one of its own logfiles, so
1717 Normally IPython will guess when a file is one of its own logfiles, so
1714 you can typically use %run even for logs. This shorthand allows you to
1718 you can typically use %run even for logs. This shorthand allows you to
1715 force any file to be treated as a log file."""
1719 force any file to be treated as a log file."""
1716
1720
1717 for f in parameter_s.split():
1721 for f in parameter_s.split():
1718 self.shell.safe_execfile(f,self.shell.user_ns,
1722 self.shell.safe_execfile(f,self.shell.user_ns,
1719 self.shell.user_ns,islog=1)
1723 self.shell.user_ns,islog=1)
1720
1724
1721 @testdec.skip_doctest
1725 @testdec.skip_doctest
1722 def magic_timeit(self, parameter_s =''):
1726 def magic_timeit(self, parameter_s =''):
1723 """Time execution of a Python statement or expression
1727 """Time execution of a Python statement or expression
1724
1728
1725 Usage:\\
1729 Usage:\\
1726 %timeit [-n<N> -r<R> [-t|-c]] statement
1730 %timeit [-n<N> -r<R> [-t|-c]] statement
1727
1731
1728 Time execution of a Python statement or expression using the timeit
1732 Time execution of a Python statement or expression using the timeit
1729 module.
1733 module.
1730
1734
1731 Options:
1735 Options:
1732 -n<N>: execute the given statement <N> times in a loop. If this value
1736 -n<N>: execute the given statement <N> times in a loop. If this value
1733 is not given, a fitting value is chosen.
1737 is not given, a fitting value is chosen.
1734
1738
1735 -r<R>: repeat the loop iteration <R> times and take the best result.
1739 -r<R>: repeat the loop iteration <R> times and take the best result.
1736 Default: 3
1740 Default: 3
1737
1741
1738 -t: use time.time to measure the time, which is the default on Unix.
1742 -t: use time.time to measure the time, which is the default on Unix.
1739 This function measures wall time.
1743 This function measures wall time.
1740
1744
1741 -c: use time.clock to measure the time, which is the default on
1745 -c: use time.clock to measure the time, which is the default on
1742 Windows and measures wall time. On Unix, resource.getrusage is used
1746 Windows and measures wall time. On Unix, resource.getrusage is used
1743 instead and returns the CPU user time.
1747 instead and returns the CPU user time.
1744
1748
1745 -p<P>: use a precision of <P> digits to display the timing result.
1749 -p<P>: use a precision of <P> digits to display the timing result.
1746 Default: 3
1750 Default: 3
1747
1751
1748
1752
1749 Examples:
1753 Examples:
1750
1754
1751 In [1]: %timeit pass
1755 In [1]: %timeit pass
1752 10000000 loops, best of 3: 53.3 ns per loop
1756 10000000 loops, best of 3: 53.3 ns per loop
1753
1757
1754 In [2]: u = None
1758 In [2]: u = None
1755
1759
1756 In [3]: %timeit u is None
1760 In [3]: %timeit u is None
1757 10000000 loops, best of 3: 184 ns per loop
1761 10000000 loops, best of 3: 184 ns per loop
1758
1762
1759 In [4]: %timeit -r 4 u == None
1763 In [4]: %timeit -r 4 u == None
1760 1000000 loops, best of 4: 242 ns per loop
1764 1000000 loops, best of 4: 242 ns per loop
1761
1765
1762 In [5]: import time
1766 In [5]: import time
1763
1767
1764 In [6]: %timeit -n1 time.sleep(2)
1768 In [6]: %timeit -n1 time.sleep(2)
1765 1 loops, best of 3: 2 s per loop
1769 1 loops, best of 3: 2 s per loop
1766
1770
1767
1771
1768 The times reported by %timeit will be slightly higher than those
1772 The times reported by %timeit will be slightly higher than those
1769 reported by the timeit.py script when variables are accessed. This is
1773 reported by the timeit.py script when variables are accessed. This is
1770 due to the fact that %timeit executes the statement in the namespace
1774 due to the fact that %timeit executes the statement in the namespace
1771 of the shell, compared with timeit.py, which uses a single setup
1775 of the shell, compared with timeit.py, which uses a single setup
1772 statement to import function or create variables. Generally, the bias
1776 statement to import function or create variables. Generally, the bias
1773 does not matter as long as results from timeit.py are not mixed with
1777 does not matter as long as results from timeit.py are not mixed with
1774 those from %timeit."""
1778 those from %timeit."""
1775
1779
1776 import timeit
1780 import timeit
1777 import math
1781 import math
1778
1782
1779 units = [u"s", u"ms", u"\xb5s", u"ns"]
1783 units = [u"s", u"ms", u"\xb5s", u"ns"]
1780 scaling = [1, 1e3, 1e6, 1e9]
1784 scaling = [1, 1e3, 1e6, 1e9]
1781
1785
1782 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1786 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1783 posix=False)
1787 posix=False)
1784 if stmt == "":
1788 if stmt == "":
1785 return
1789 return
1786 timefunc = timeit.default_timer
1790 timefunc = timeit.default_timer
1787 number = int(getattr(opts, "n", 0))
1791 number = int(getattr(opts, "n", 0))
1788 repeat = int(getattr(opts, "r", timeit.default_repeat))
1792 repeat = int(getattr(opts, "r", timeit.default_repeat))
1789 precision = int(getattr(opts, "p", 3))
1793 precision = int(getattr(opts, "p", 3))
1790 if hasattr(opts, "t"):
1794 if hasattr(opts, "t"):
1791 timefunc = time.time
1795 timefunc = time.time
1792 if hasattr(opts, "c"):
1796 if hasattr(opts, "c"):
1793 timefunc = clock
1797 timefunc = clock
1794
1798
1795 timer = timeit.Timer(timer=timefunc)
1799 timer = timeit.Timer(timer=timefunc)
1796 # this code has tight coupling to the inner workings of timeit.Timer,
1800 # this code has tight coupling to the inner workings of timeit.Timer,
1797 # but is there a better way to achieve that the code stmt has access
1801 # but is there a better way to achieve that the code stmt has access
1798 # to the shell namespace?
1802 # to the shell namespace?
1799
1803
1800 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1804 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1801 'setup': "pass"}
1805 'setup': "pass"}
1802 # Track compilation time so it can be reported if too long
1806 # Track compilation time so it can be reported if too long
1803 # Minimum time above which compilation time will be reported
1807 # Minimum time above which compilation time will be reported
1804 tc_min = 0.1
1808 tc_min = 0.1
1805
1809
1806 t0 = clock()
1810 t0 = clock()
1807 code = compile(src, "<magic-timeit>", "exec")
1811 code = compile(src, "<magic-timeit>", "exec")
1808 tc = clock()-t0
1812 tc = clock()-t0
1809
1813
1810 ns = {}
1814 ns = {}
1811 exec code in self.shell.user_ns, ns
1815 exec code in self.shell.user_ns, ns
1812 timer.inner = ns["inner"]
1816 timer.inner = ns["inner"]
1813
1817
1814 if number == 0:
1818 if number == 0:
1815 # determine number so that 0.2 <= total time < 2.0
1819 # determine number so that 0.2 <= total time < 2.0
1816 number = 1
1820 number = 1
1817 for i in range(1, 10):
1821 for i in range(1, 10):
1818 number *= 10
1822 number *= 10
1819 if timer.timeit(number) >= 0.2:
1823 if timer.timeit(number) >= 0.2:
1820 break
1824 break
1821
1825
1822 best = min(timer.repeat(repeat, number)) / number
1826 best = min(timer.repeat(repeat, number)) / number
1823
1827
1824 if best > 0.0:
1828 if best > 0.0:
1825 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1829 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1826 else:
1830 else:
1827 order = 3
1831 order = 3
1828 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1832 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1829 precision,
1833 precision,
1830 best * scaling[order],
1834 best * scaling[order],
1831 units[order])
1835 units[order])
1832 if tc > tc_min:
1836 if tc > tc_min:
1833 print "Compiler time: %.2f s" % tc
1837 print "Compiler time: %.2f s" % tc
1834
1838
1835 @testdec.skip_doctest
1839 @testdec.skip_doctest
1836 def magic_time(self,parameter_s = ''):
1840 def magic_time(self,parameter_s = ''):
1837 """Time execution of a Python statement or expression.
1841 """Time execution of a Python statement or expression.
1838
1842
1839 The CPU and wall clock times are printed, and the value of the
1843 The CPU and wall clock times are printed, and the value of the
1840 expression (if any) is returned. Note that under Win32, system time
1844 expression (if any) is returned. Note that under Win32, system time
1841 is always reported as 0, since it can not be measured.
1845 is always reported as 0, since it can not be measured.
1842
1846
1843 This function provides very basic timing functionality. In Python
1847 This function provides very basic timing functionality. In Python
1844 2.3, the timeit module offers more control and sophistication, so this
1848 2.3, the timeit module offers more control and sophistication, so this
1845 could be rewritten to use it (patches welcome).
1849 could be rewritten to use it (patches welcome).
1846
1850
1847 Some examples:
1851 Some examples:
1848
1852
1849 In [1]: time 2**128
1853 In [1]: time 2**128
1850 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1854 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1851 Wall time: 0.00
1855 Wall time: 0.00
1852 Out[1]: 340282366920938463463374607431768211456L
1856 Out[1]: 340282366920938463463374607431768211456L
1853
1857
1854 In [2]: n = 1000000
1858 In [2]: n = 1000000
1855
1859
1856 In [3]: time sum(range(n))
1860 In [3]: time sum(range(n))
1857 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1861 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1858 Wall time: 1.37
1862 Wall time: 1.37
1859 Out[3]: 499999500000L
1863 Out[3]: 499999500000L
1860
1864
1861 In [4]: time print 'hello world'
1865 In [4]: time print 'hello world'
1862 hello world
1866 hello world
1863 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1867 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1864 Wall time: 0.00
1868 Wall time: 0.00
1865
1869
1866 Note that the time needed by Python to compile the given expression
1870 Note that the time needed by Python to compile the given expression
1867 will be reported if it is more than 0.1s. In this example, the
1871 will be reported if it is more than 0.1s. In this example, the
1868 actual exponentiation is done by Python at compilation time, so while
1872 actual exponentiation is done by Python at compilation time, so while
1869 the expression can take a noticeable amount of time to compute, that
1873 the expression can take a noticeable amount of time to compute, that
1870 time is purely due to the compilation:
1874 time is purely due to the compilation:
1871
1875
1872 In [5]: time 3**9999;
1876 In [5]: time 3**9999;
1873 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1877 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1874 Wall time: 0.00 s
1878 Wall time: 0.00 s
1875
1879
1876 In [6]: time 3**999999;
1880 In [6]: time 3**999999;
1877 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1881 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1878 Wall time: 0.00 s
1882 Wall time: 0.00 s
1879 Compiler : 0.78 s
1883 Compiler : 0.78 s
1880 """
1884 """
1881
1885
1882 # fail immediately if the given expression can't be compiled
1886 # fail immediately if the given expression can't be compiled
1883
1887
1884 expr = self.shell.prefilter(parameter_s,False)
1888 expr = self.shell.prefilter(parameter_s,False)
1885
1889
1886 # Minimum time above which compilation time will be reported
1890 # Minimum time above which compilation time will be reported
1887 tc_min = 0.1
1891 tc_min = 0.1
1888
1892
1889 try:
1893 try:
1890 mode = 'eval'
1894 mode = 'eval'
1891 t0 = clock()
1895 t0 = clock()
1892 code = compile(expr,'<timed eval>',mode)
1896 code = compile(expr,'<timed eval>',mode)
1893 tc = clock()-t0
1897 tc = clock()-t0
1894 except SyntaxError:
1898 except SyntaxError:
1895 mode = 'exec'
1899 mode = 'exec'
1896 t0 = clock()
1900 t0 = clock()
1897 code = compile(expr,'<timed exec>',mode)
1901 code = compile(expr,'<timed exec>',mode)
1898 tc = clock()-t0
1902 tc = clock()-t0
1899 # skew measurement as little as possible
1903 # skew measurement as little as possible
1900 glob = self.shell.user_ns
1904 glob = self.shell.user_ns
1901 clk = clock2
1905 clk = clock2
1902 wtime = time.time
1906 wtime = time.time
1903 # time execution
1907 # time execution
1904 wall_st = wtime()
1908 wall_st = wtime()
1905 if mode=='eval':
1909 if mode=='eval':
1906 st = clk()
1910 st = clk()
1907 out = eval(code,glob)
1911 out = eval(code,glob)
1908 end = clk()
1912 end = clk()
1909 else:
1913 else:
1910 st = clk()
1914 st = clk()
1911 exec code in glob
1915 exec code in glob
1912 end = clk()
1916 end = clk()
1913 out = None
1917 out = None
1914 wall_end = wtime()
1918 wall_end = wtime()
1915 # Compute actual times and report
1919 # Compute actual times and report
1916 wall_time = wall_end-wall_st
1920 wall_time = wall_end-wall_st
1917 cpu_user = end[0]-st[0]
1921 cpu_user = end[0]-st[0]
1918 cpu_sys = end[1]-st[1]
1922 cpu_sys = end[1]-st[1]
1919 cpu_tot = cpu_user+cpu_sys
1923 cpu_tot = cpu_user+cpu_sys
1920 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1924 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1921 (cpu_user,cpu_sys,cpu_tot)
1925 (cpu_user,cpu_sys,cpu_tot)
1922 print "Wall time: %.2f s" % wall_time
1926 print "Wall time: %.2f s" % wall_time
1923 if tc > tc_min:
1927 if tc > tc_min:
1924 print "Compiler : %.2f s" % tc
1928 print "Compiler : %.2f s" % tc
1925 return out
1929 return out
1926
1930
1927 @testdec.skip_doctest
1931 @testdec.skip_doctest
1928 def magic_macro(self,parameter_s = ''):
1932 def magic_macro(self,parameter_s = ''):
1929 """Define a set of input lines as a macro for future re-execution.
1933 """Define a set of input lines as a macro for future re-execution.
1930
1934
1931 Usage:\\
1935 Usage:\\
1932 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1936 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1933
1937
1934 Options:
1938 Options:
1935
1939
1936 -r: use 'raw' input. By default, the 'processed' history is used,
1940 -r: use 'raw' input. By default, the 'processed' history is used,
1937 so that magics are loaded in their transformed version to valid
1941 so that magics are loaded in their transformed version to valid
1938 Python. If this option is given, the raw input as typed as the
1942 Python. If this option is given, the raw input as typed as the
1939 command line is used instead.
1943 command line is used instead.
1940
1944
1941 This will define a global variable called `name` which is a string
1945 This will define a global variable called `name` which is a string
1942 made of joining the slices and lines you specify (n1,n2,... numbers
1946 made of joining the slices and lines you specify (n1,n2,... numbers
1943 above) from your input history into a single string. This variable
1947 above) from your input history into a single string. This variable
1944 acts like an automatic function which re-executes those lines as if
1948 acts like an automatic function which re-executes those lines as if
1945 you had typed them. You just type 'name' at the prompt and the code
1949 you had typed them. You just type 'name' at the prompt and the code
1946 executes.
1950 executes.
1947
1951
1948 The notation for indicating number ranges is: n1-n2 means 'use line
1952 The notation for indicating number ranges is: n1-n2 means 'use line
1949 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1953 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1950 using the lines numbered 5,6 and 7.
1954 using the lines numbered 5,6 and 7.
1951
1955
1952 Note: as a 'hidden' feature, you can also use traditional python slice
1956 Note: as a 'hidden' feature, you can also use traditional python slice
1953 notation, where N:M means numbers N through M-1.
1957 notation, where N:M means numbers N through M-1.
1954
1958
1955 For example, if your history contains (%hist prints it):
1959 For example, if your history contains (%hist prints it):
1956
1960
1957 44: x=1
1961 44: x=1
1958 45: y=3
1962 45: y=3
1959 46: z=x+y
1963 46: z=x+y
1960 47: print x
1964 47: print x
1961 48: a=5
1965 48: a=5
1962 49: print 'x',x,'y',y
1966 49: print 'x',x,'y',y
1963
1967
1964 you can create a macro with lines 44 through 47 (included) and line 49
1968 you can create a macro with lines 44 through 47 (included) and line 49
1965 called my_macro with:
1969 called my_macro with:
1966
1970
1967 In [55]: %macro my_macro 44-47 49
1971 In [55]: %macro my_macro 44-47 49
1968
1972
1969 Now, typing `my_macro` (without quotes) will re-execute all this code
1973 Now, typing `my_macro` (without quotes) will re-execute all this code
1970 in one pass.
1974 in one pass.
1971
1975
1972 You don't need to give the line-numbers in order, and any given line
1976 You don't need to give the line-numbers in order, and any given line
1973 number can appear multiple times. You can assemble macros with any
1977 number can appear multiple times. You can assemble macros with any
1974 lines from your input history in any order.
1978 lines from your input history in any order.
1975
1979
1976 The macro is a simple object which holds its value in an attribute,
1980 The macro is a simple object which holds its value in an attribute,
1977 but IPython's display system checks for macros and executes them as
1981 but IPython's display system checks for macros and executes them as
1978 code instead of printing them when you type their name.
1982 code instead of printing them when you type their name.
1979
1983
1980 You can view a macro's contents by explicitly printing it with:
1984 You can view a macro's contents by explicitly printing it with:
1981
1985
1982 'print macro_name'.
1986 'print macro_name'.
1983
1987
1984 For one-off cases which DON'T contain magic function calls in them you
1988 For one-off cases which DON'T contain magic function calls in them you
1985 can obtain similar results by explicitly executing slices from your
1989 can obtain similar results by explicitly executing slices from your
1986 input history with:
1990 input history with:
1987
1991
1988 In [60]: exec In[44:48]+In[49]"""
1992 In [60]: exec In[44:48]+In[49]"""
1989
1993
1990 opts,args = self.parse_options(parameter_s,'r',mode='list')
1994 opts,args = self.parse_options(parameter_s,'r',mode='list')
1991 if not args:
1995 if not args:
1992 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1996 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
1993 macs.sort()
1997 macs.sort()
1994 return macs
1998 return macs
1995 if len(args) == 1:
1999 if len(args) == 1:
1996 raise UsageError(
2000 raise UsageError(
1997 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2001 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1998 name,ranges = args[0], args[1:]
2002 name,ranges = args[0], args[1:]
1999
2003
2000 #print 'rng',ranges # dbg
2004 #print 'rng',ranges # dbg
2001 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2005 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2002 macro = Macro(lines)
2006 macro = Macro(lines)
2003 self.shell.user_ns.update({name:macro})
2007 self.shell.user_ns.update({name:macro})
2004 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2008 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2005 print 'Macro contents:'
2009 print 'Macro contents:'
2006 print macro,
2010 print macro,
2007
2011
2008 def magic_save(self,parameter_s = ''):
2012 def magic_save(self,parameter_s = ''):
2009 """Save a set of lines to a given filename.
2013 """Save a set of lines to a given filename.
2010
2014
2011 Usage:\\
2015 Usage:\\
2012 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2016 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2013
2017
2014 Options:
2018 Options:
2015
2019
2016 -r: use 'raw' input. By default, the 'processed' history is used,
2020 -r: use 'raw' input. By default, the 'processed' history is used,
2017 so that magics are loaded in their transformed version to valid
2021 so that magics are loaded in their transformed version to valid
2018 Python. If this option is given, the raw input as typed as the
2022 Python. If this option is given, the raw input as typed as the
2019 command line is used instead.
2023 command line is used instead.
2020
2024
2021 This function uses the same syntax as %macro for line extraction, but
2025 This function uses the same syntax as %macro for line extraction, but
2022 instead of creating a macro it saves the resulting string to the
2026 instead of creating a macro it saves the resulting string to the
2023 filename you specify.
2027 filename you specify.
2024
2028
2025 It adds a '.py' extension to the file if you don't do so yourself, and
2029 It adds a '.py' extension to the file if you don't do so yourself, and
2026 it asks for confirmation before overwriting existing files."""
2030 it asks for confirmation before overwriting existing files."""
2027
2031
2028 opts,args = self.parse_options(parameter_s,'r',mode='list')
2032 opts,args = self.parse_options(parameter_s,'r',mode='list')
2029 fname,ranges = args[0], args[1:]
2033 fname,ranges = args[0], args[1:]
2030 if not fname.endswith('.py'):
2034 if not fname.endswith('.py'):
2031 fname += '.py'
2035 fname += '.py'
2032 if os.path.isfile(fname):
2036 if os.path.isfile(fname):
2033 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2037 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2034 if ans.lower() not in ['y','yes']:
2038 if ans.lower() not in ['y','yes']:
2035 print 'Operation cancelled.'
2039 print 'Operation cancelled.'
2036 return
2040 return
2037 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2041 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2038 f = file(fname,'w')
2042 f = file(fname,'w')
2039 f.write(cmds)
2043 f.write(cmds)
2040 f.close()
2044 f.close()
2041 print 'The following commands were written to file `%s`:' % fname
2045 print 'The following commands were written to file `%s`:' % fname
2042 print cmds
2046 print cmds
2043
2047
2044 def _edit_macro(self,mname,macro):
2048 def _edit_macro(self,mname,macro):
2045 """open an editor with the macro data in a file"""
2049 """open an editor with the macro data in a file"""
2046 filename = self.shell.mktempfile(macro.value)
2050 filename = self.shell.mktempfile(macro.value)
2047 self.shell.hooks.editor(filename)
2051 self.shell.hooks.editor(filename)
2048
2052
2049 # and make a new macro object, to replace the old one
2053 # and make a new macro object, to replace the old one
2050 mfile = open(filename)
2054 mfile = open(filename)
2051 mvalue = mfile.read()
2055 mvalue = mfile.read()
2052 mfile.close()
2056 mfile.close()
2053 self.shell.user_ns[mname] = Macro(mvalue)
2057 self.shell.user_ns[mname] = Macro(mvalue)
2054
2058
2055 def magic_ed(self,parameter_s=''):
2059 def magic_ed(self,parameter_s=''):
2056 """Alias to %edit."""
2060 """Alias to %edit."""
2057 return self.magic_edit(parameter_s)
2061 return self.magic_edit(parameter_s)
2058
2062
2059 @testdec.skip_doctest
2063 @testdec.skip_doctest
2060 def magic_edit(self,parameter_s='',last_call=['','']):
2064 def magic_edit(self,parameter_s='',last_call=['','']):
2061 """Bring up an editor and execute the resulting code.
2065 """Bring up an editor and execute the resulting code.
2062
2066
2063 Usage:
2067 Usage:
2064 %edit [options] [args]
2068 %edit [options] [args]
2065
2069
2066 %edit runs IPython's editor hook. The default version of this hook is
2070 %edit runs IPython's editor hook. The default version of this hook is
2067 set to call the __IPYTHON__.rc.editor command. This is read from your
2071 set to call the __IPYTHON__.rc.editor command. This is read from your
2068 environment variable $EDITOR. If this isn't found, it will default to
2072 environment variable $EDITOR. If this isn't found, it will default to
2069 vi under Linux/Unix and to notepad under Windows. See the end of this
2073 vi under Linux/Unix and to notepad under Windows. See the end of this
2070 docstring for how to change the editor hook.
2074 docstring for how to change the editor hook.
2071
2075
2072 You can also set the value of this editor via the command line option
2076 You can also set the value of this editor via the command line option
2073 '-editor' or in your ipythonrc file. This is useful if you wish to use
2077 '-editor' or in your ipythonrc file. This is useful if you wish to use
2074 specifically for IPython an editor different from your typical default
2078 specifically for IPython an editor different from your typical default
2075 (and for Windows users who typically don't set environment variables).
2079 (and for Windows users who typically don't set environment variables).
2076
2080
2077 This command allows you to conveniently edit multi-line code right in
2081 This command allows you to conveniently edit multi-line code right in
2078 your IPython session.
2082 your IPython session.
2079
2083
2080 If called without arguments, %edit opens up an empty editor with a
2084 If called without arguments, %edit opens up an empty editor with a
2081 temporary file and will execute the contents of this file when you
2085 temporary file and will execute the contents of this file when you
2082 close it (don't forget to save it!).
2086 close it (don't forget to save it!).
2083
2087
2084
2088
2085 Options:
2089 Options:
2086
2090
2087 -n <number>: open the editor at a specified line number. By default,
2091 -n <number>: open the editor at a specified line number. By default,
2088 the IPython editor hook uses the unix syntax 'editor +N filename', but
2092 the IPython editor hook uses the unix syntax 'editor +N filename', but
2089 you can configure this by providing your own modified hook if your
2093 you can configure this by providing your own modified hook if your
2090 favorite editor supports line-number specifications with a different
2094 favorite editor supports line-number specifications with a different
2091 syntax.
2095 syntax.
2092
2096
2093 -p: this will call the editor with the same data as the previous time
2097 -p: this will call the editor with the same data as the previous time
2094 it was used, regardless of how long ago (in your current session) it
2098 it was used, regardless of how long ago (in your current session) it
2095 was.
2099 was.
2096
2100
2097 -r: use 'raw' input. This option only applies to input taken from the
2101 -r: use 'raw' input. This option only applies to input taken from the
2098 user's history. By default, the 'processed' history is used, so that
2102 user's history. By default, the 'processed' history is used, so that
2099 magics are loaded in their transformed version to valid Python. If
2103 magics are loaded in their transformed version to valid Python. If
2100 this option is given, the raw input as typed as the command line is
2104 this option is given, the raw input as typed as the command line is
2101 used instead. When you exit the editor, it will be executed by
2105 used instead. When you exit the editor, it will be executed by
2102 IPython's own processor.
2106 IPython's own processor.
2103
2107
2104 -x: do not execute the edited code immediately upon exit. This is
2108 -x: do not execute the edited code immediately upon exit. This is
2105 mainly useful if you are editing programs which need to be called with
2109 mainly useful if you are editing programs which need to be called with
2106 command line arguments, which you can then do using %run.
2110 command line arguments, which you can then do using %run.
2107
2111
2108
2112
2109 Arguments:
2113 Arguments:
2110
2114
2111 If arguments are given, the following possibilites exist:
2115 If arguments are given, the following possibilites exist:
2112
2116
2113 - The arguments are numbers or pairs of colon-separated numbers (like
2117 - The arguments are numbers or pairs of colon-separated numbers (like
2114 1 4:8 9). These are interpreted as lines of previous input to be
2118 1 4:8 9). These are interpreted as lines of previous input to be
2115 loaded into the editor. The syntax is the same of the %macro command.
2119 loaded into the editor. The syntax is the same of the %macro command.
2116
2120
2117 - If the argument doesn't start with a number, it is evaluated as a
2121 - If the argument doesn't start with a number, it is evaluated as a
2118 variable and its contents loaded into the editor. You can thus edit
2122 variable and its contents loaded into the editor. You can thus edit
2119 any string which contains python code (including the result of
2123 any string which contains python code (including the result of
2120 previous edits).
2124 previous edits).
2121
2125
2122 - If the argument is the name of an object (other than a string),
2126 - If the argument is the name of an object (other than a string),
2123 IPython will try to locate the file where it was defined and open the
2127 IPython will try to locate the file where it was defined and open the
2124 editor at the point where it is defined. You can use `%edit function`
2128 editor at the point where it is defined. You can use `%edit function`
2125 to load an editor exactly at the point where 'function' is defined,
2129 to load an editor exactly at the point where 'function' is defined,
2126 edit it and have the file be executed automatically.
2130 edit it and have the file be executed automatically.
2127
2131
2128 If the object is a macro (see %macro for details), this opens up your
2132 If the object is a macro (see %macro for details), this opens up your
2129 specified editor with a temporary file containing the macro's data.
2133 specified editor with a temporary file containing the macro's data.
2130 Upon exit, the macro is reloaded with the contents of the file.
2134 Upon exit, the macro is reloaded with the contents of the file.
2131
2135
2132 Note: opening at an exact line is only supported under Unix, and some
2136 Note: opening at an exact line is only supported under Unix, and some
2133 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2137 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2134 '+NUMBER' parameter necessary for this feature. Good editors like
2138 '+NUMBER' parameter necessary for this feature. Good editors like
2135 (X)Emacs, vi, jed, pico and joe all do.
2139 (X)Emacs, vi, jed, pico and joe all do.
2136
2140
2137 - If the argument is not found as a variable, IPython will look for a
2141 - If the argument is not found as a variable, IPython will look for a
2138 file with that name (adding .py if necessary) and load it into the
2142 file with that name (adding .py if necessary) and load it into the
2139 editor. It will execute its contents with execfile() when you exit,
2143 editor. It will execute its contents with execfile() when you exit,
2140 loading any code in the file into your interactive namespace.
2144 loading any code in the file into your interactive namespace.
2141
2145
2142 After executing your code, %edit will return as output the code you
2146 After executing your code, %edit will return as output the code you
2143 typed in the editor (except when it was an existing file). This way
2147 typed in the editor (except when it was an existing file). This way
2144 you can reload the code in further invocations of %edit as a variable,
2148 you can reload the code in further invocations of %edit as a variable,
2145 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2149 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2146 the output.
2150 the output.
2147
2151
2148 Note that %edit is also available through the alias %ed.
2152 Note that %edit is also available through the alias %ed.
2149
2153
2150 This is an example of creating a simple function inside the editor and
2154 This is an example of creating a simple function inside the editor and
2151 then modifying it. First, start up the editor:
2155 then modifying it. First, start up the editor:
2152
2156
2153 In [1]: ed
2157 In [1]: ed
2154 Editing... done. Executing edited code...
2158 Editing... done. Executing edited code...
2155 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2159 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2156
2160
2157 We can then call the function foo():
2161 We can then call the function foo():
2158
2162
2159 In [2]: foo()
2163 In [2]: foo()
2160 foo() was defined in an editing session
2164 foo() was defined in an editing session
2161
2165
2162 Now we edit foo. IPython automatically loads the editor with the
2166 Now we edit foo. IPython automatically loads the editor with the
2163 (temporary) file where foo() was previously defined:
2167 (temporary) file where foo() was previously defined:
2164
2168
2165 In [3]: ed foo
2169 In [3]: ed foo
2166 Editing... done. Executing edited code...
2170 Editing... done. Executing edited code...
2167
2171
2168 And if we call foo() again we get the modified version:
2172 And if we call foo() again we get the modified version:
2169
2173
2170 In [4]: foo()
2174 In [4]: foo()
2171 foo() has now been changed!
2175 foo() has now been changed!
2172
2176
2173 Here is an example of how to edit a code snippet successive
2177 Here is an example of how to edit a code snippet successive
2174 times. First we call the editor:
2178 times. First we call the editor:
2175
2179
2176 In [5]: ed
2180 In [5]: ed
2177 Editing... done. Executing edited code...
2181 Editing... done. Executing edited code...
2178 hello
2182 hello
2179 Out[5]: "print 'hello'n"
2183 Out[5]: "print 'hello'n"
2180
2184
2181 Now we call it again with the previous output (stored in _):
2185 Now we call it again with the previous output (stored in _):
2182
2186
2183 In [6]: ed _
2187 In [6]: ed _
2184 Editing... done. Executing edited code...
2188 Editing... done. Executing edited code...
2185 hello world
2189 hello world
2186 Out[6]: "print 'hello world'n"
2190 Out[6]: "print 'hello world'n"
2187
2191
2188 Now we call it with the output #8 (stored in _8, also as Out[8]):
2192 Now we call it with the output #8 (stored in _8, also as Out[8]):
2189
2193
2190 In [7]: ed _8
2194 In [7]: ed _8
2191 Editing... done. Executing edited code...
2195 Editing... done. Executing edited code...
2192 hello again
2196 hello again
2193 Out[7]: "print 'hello again'n"
2197 Out[7]: "print 'hello again'n"
2194
2198
2195
2199
2196 Changing the default editor hook:
2200 Changing the default editor hook:
2197
2201
2198 If you wish to write your own editor hook, you can put it in a
2202 If you wish to write your own editor hook, you can put it in a
2199 configuration file which you load at startup time. The default hook
2203 configuration file which you load at startup time. The default hook
2200 is defined in the IPython.hooks module, and you can use that as a
2204 is defined in the IPython.hooks module, and you can use that as a
2201 starting example for further modifications. That file also has
2205 starting example for further modifications. That file also has
2202 general instructions on how to set a new hook for use once you've
2206 general instructions on how to set a new hook for use once you've
2203 defined it."""
2207 defined it."""
2204
2208
2205 # FIXME: This function has become a convoluted mess. It needs a
2209 # FIXME: This function has become a convoluted mess. It needs a
2206 # ground-up rewrite with clean, simple logic.
2210 # ground-up rewrite with clean, simple logic.
2207
2211
2208 def make_filename(arg):
2212 def make_filename(arg):
2209 "Make a filename from the given args"
2213 "Make a filename from the given args"
2210 try:
2214 try:
2211 filename = get_py_filename(arg)
2215 filename = get_py_filename(arg)
2212 except IOError:
2216 except IOError:
2213 if args.endswith('.py'):
2217 if args.endswith('.py'):
2214 filename = arg
2218 filename = arg
2215 else:
2219 else:
2216 filename = None
2220 filename = None
2217 return filename
2221 return filename
2218
2222
2219 # custom exceptions
2223 # custom exceptions
2220 class DataIsObject(Exception): pass
2224 class DataIsObject(Exception): pass
2221
2225
2222 opts,args = self.parse_options(parameter_s,'prxn:')
2226 opts,args = self.parse_options(parameter_s,'prxn:')
2223 # Set a few locals from the options for convenience:
2227 # Set a few locals from the options for convenience:
2224 opts_p = opts.has_key('p')
2228 opts_p = opts.has_key('p')
2225 opts_r = opts.has_key('r')
2229 opts_r = opts.has_key('r')
2226
2230
2227 # Default line number value
2231 # Default line number value
2228 lineno = opts.get('n',None)
2232 lineno = opts.get('n',None)
2229
2233
2230 if opts_p:
2234 if opts_p:
2231 args = '_%s' % last_call[0]
2235 args = '_%s' % last_call[0]
2232 if not self.shell.user_ns.has_key(args):
2236 if not self.shell.user_ns.has_key(args):
2233 args = last_call[1]
2237 args = last_call[1]
2234
2238
2235 # use last_call to remember the state of the previous call, but don't
2239 # use last_call to remember the state of the previous call, but don't
2236 # let it be clobbered by successive '-p' calls.
2240 # let it be clobbered by successive '-p' calls.
2237 try:
2241 try:
2238 last_call[0] = self.shell.outputcache.prompt_count
2242 last_call[0] = self.shell.outputcache.prompt_count
2239 if not opts_p:
2243 if not opts_p:
2240 last_call[1] = parameter_s
2244 last_call[1] = parameter_s
2241 except:
2245 except:
2242 pass
2246 pass
2243
2247
2244 # by default this is done with temp files, except when the given
2248 # by default this is done with temp files, except when the given
2245 # arg is a filename
2249 # arg is a filename
2246 use_temp = 1
2250 use_temp = 1
2247
2251
2248 if re.match(r'\d',args):
2252 if re.match(r'\d',args):
2249 # Mode where user specifies ranges of lines, like in %macro.
2253 # Mode where user specifies ranges of lines, like in %macro.
2250 # This means that you can't edit files whose names begin with
2254 # This means that you can't edit files whose names begin with
2251 # numbers this way. Tough.
2255 # numbers this way. Tough.
2252 ranges = args.split()
2256 ranges = args.split()
2253 data = ''.join(self.extract_input_slices(ranges,opts_r))
2257 data = ''.join(self.extract_input_slices(ranges,opts_r))
2254 elif args.endswith('.py'):
2258 elif args.endswith('.py'):
2255 filename = make_filename(args)
2259 filename = make_filename(args)
2256 data = ''
2260 data = ''
2257 use_temp = 0
2261 use_temp = 0
2258 elif args:
2262 elif args:
2259 try:
2263 try:
2260 # Load the parameter given as a variable. If not a string,
2264 # Load the parameter given as a variable. If not a string,
2261 # process it as an object instead (below)
2265 # process it as an object instead (below)
2262
2266
2263 #print '*** args',args,'type',type(args) # dbg
2267 #print '*** args',args,'type',type(args) # dbg
2264 data = eval(args,self.shell.user_ns)
2268 data = eval(args,self.shell.user_ns)
2265 if not type(data) in StringTypes:
2269 if not type(data) in StringTypes:
2266 raise DataIsObject
2270 raise DataIsObject
2267
2271
2268 except (NameError,SyntaxError):
2272 except (NameError,SyntaxError):
2269 # given argument is not a variable, try as a filename
2273 # given argument is not a variable, try as a filename
2270 filename = make_filename(args)
2274 filename = make_filename(args)
2271 if filename is None:
2275 if filename is None:
2272 warn("Argument given (%s) can't be found as a variable "
2276 warn("Argument given (%s) can't be found as a variable "
2273 "or as a filename." % args)
2277 "or as a filename." % args)
2274 return
2278 return
2275
2279
2276 data = ''
2280 data = ''
2277 use_temp = 0
2281 use_temp = 0
2278 except DataIsObject:
2282 except DataIsObject:
2279
2283
2280 # macros have a special edit function
2284 # macros have a special edit function
2281 if isinstance(data,Macro):
2285 if isinstance(data,Macro):
2282 self._edit_macro(args,data)
2286 self._edit_macro(args,data)
2283 return
2287 return
2284
2288
2285 # For objects, try to edit the file where they are defined
2289 # For objects, try to edit the file where they are defined
2286 try:
2290 try:
2287 filename = inspect.getabsfile(data)
2291 filename = inspect.getabsfile(data)
2288 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2292 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2289 # class created by %edit? Try to find source
2293 # class created by %edit? Try to find source
2290 # by looking for method definitions instead, the
2294 # by looking for method definitions instead, the
2291 # __module__ in those classes is FakeModule.
2295 # __module__ in those classes is FakeModule.
2292 attrs = [getattr(data, aname) for aname in dir(data)]
2296 attrs = [getattr(data, aname) for aname in dir(data)]
2293 for attr in attrs:
2297 for attr in attrs:
2294 if not inspect.ismethod(attr):
2298 if not inspect.ismethod(attr):
2295 continue
2299 continue
2296 filename = inspect.getabsfile(attr)
2300 filename = inspect.getabsfile(attr)
2297 if filename and 'fakemodule' not in filename.lower():
2301 if filename and 'fakemodule' not in filename.lower():
2298 # change the attribute to be the edit target instead
2302 # change the attribute to be the edit target instead
2299 data = attr
2303 data = attr
2300 break
2304 break
2301
2305
2302 datafile = 1
2306 datafile = 1
2303 except TypeError:
2307 except TypeError:
2304 filename = make_filename(args)
2308 filename = make_filename(args)
2305 datafile = 1
2309 datafile = 1
2306 warn('Could not find file where `%s` is defined.\n'
2310 warn('Could not find file where `%s` is defined.\n'
2307 'Opening a file named `%s`' % (args,filename))
2311 'Opening a file named `%s`' % (args,filename))
2308 # Now, make sure we can actually read the source (if it was in
2312 # Now, make sure we can actually read the source (if it was in
2309 # a temp file it's gone by now).
2313 # a temp file it's gone by now).
2310 if datafile:
2314 if datafile:
2311 try:
2315 try:
2312 if lineno is None:
2316 if lineno is None:
2313 lineno = inspect.getsourcelines(data)[1]
2317 lineno = inspect.getsourcelines(data)[1]
2314 except IOError:
2318 except IOError:
2315 filename = make_filename(args)
2319 filename = make_filename(args)
2316 if filename is None:
2320 if filename is None:
2317 warn('The file `%s` where `%s` was defined cannot '
2321 warn('The file `%s` where `%s` was defined cannot '
2318 'be read.' % (filename,data))
2322 'be read.' % (filename,data))
2319 return
2323 return
2320 use_temp = 0
2324 use_temp = 0
2321 else:
2325 else:
2322 data = ''
2326 data = ''
2323
2327
2324 if use_temp:
2328 if use_temp:
2325 filename = self.shell.mktempfile(data)
2329 filename = self.shell.mktempfile(data)
2326 print 'IPython will make a temporary file named:',filename
2330 print 'IPython will make a temporary file named:',filename
2327
2331
2328 # do actual editing here
2332 # do actual editing here
2329 print 'Editing...',
2333 print 'Editing...',
2330 sys.stdout.flush()
2334 sys.stdout.flush()
2335 try:
2331 self.shell.hooks.editor(filename,lineno)
2336 self.shell.hooks.editor(filename,lineno)
2337 except IPython.ipapi.TryNext:
2338 warn('Could not open editor')
2339 return
2332
2340
2333 # XXX TODO: should this be generalized for all string vars?
2341 # XXX TODO: should this be generalized for all string vars?
2334 # For now, this is special-cased to blocks created by cpaste
2342 # For now, this is special-cased to blocks created by cpaste
2335 if args.strip() == 'pasted_block':
2343 if args.strip() == 'pasted_block':
2336 self.shell.user_ns['pasted_block'] = file_read(filename)
2344 self.shell.user_ns['pasted_block'] = file_read(filename)
2337
2345
2338 if opts.has_key('x'): # -x prevents actual execution
2346 if opts.has_key('x'): # -x prevents actual execution
2339 print
2347 print
2340 else:
2348 else:
2341 print 'done. Executing edited code...'
2349 print 'done. Executing edited code...'
2342 if opts_r:
2350 if opts_r:
2343 self.shell.runlines(file_read(filename))
2351 self.shell.runlines(file_read(filename))
2344 else:
2352 else:
2345 self.shell.safe_execfile(filename,self.shell.user_ns,
2353 self.shell.safe_execfile(filename,self.shell.user_ns,
2346 self.shell.user_ns)
2354 self.shell.user_ns)
2347
2355
2348
2356
2349 if use_temp:
2357 if use_temp:
2350 try:
2358 try:
2351 return open(filename).read()
2359 return open(filename).read()
2352 except IOError,msg:
2360 except IOError,msg:
2353 if msg.filename == filename:
2361 if msg.filename == filename:
2354 warn('File not found. Did you forget to save?')
2362 warn('File not found. Did you forget to save?')
2355 return
2363 return
2356 else:
2364 else:
2357 self.shell.showtraceback()
2365 self.shell.showtraceback()
2358
2366
2359 def magic_xmode(self,parameter_s = ''):
2367 def magic_xmode(self,parameter_s = ''):
2360 """Switch modes for the exception handlers.
2368 """Switch modes for the exception handlers.
2361
2369
2362 Valid modes: Plain, Context and Verbose.
2370 Valid modes: Plain, Context and Verbose.
2363
2371
2364 If called without arguments, acts as a toggle."""
2372 If called without arguments, acts as a toggle."""
2365
2373
2366 def xmode_switch_err(name):
2374 def xmode_switch_err(name):
2367 warn('Error changing %s exception modes.\n%s' %
2375 warn('Error changing %s exception modes.\n%s' %
2368 (name,sys.exc_info()[1]))
2376 (name,sys.exc_info()[1]))
2369
2377
2370 shell = self.shell
2378 shell = self.shell
2371 new_mode = parameter_s.strip().capitalize()
2379 new_mode = parameter_s.strip().capitalize()
2372 try:
2380 try:
2373 shell.InteractiveTB.set_mode(mode=new_mode)
2381 shell.InteractiveTB.set_mode(mode=new_mode)
2374 print 'Exception reporting mode:',shell.InteractiveTB.mode
2382 print 'Exception reporting mode:',shell.InteractiveTB.mode
2375 except:
2383 except:
2376 xmode_switch_err('user')
2384 xmode_switch_err('user')
2377
2385
2378 # threaded shells use a special handler in sys.excepthook
2386 # threaded shells use a special handler in sys.excepthook
2379 if shell.isthreaded:
2387 if shell.isthreaded:
2380 try:
2388 try:
2381 shell.sys_excepthook.set_mode(mode=new_mode)
2389 shell.sys_excepthook.set_mode(mode=new_mode)
2382 except:
2390 except:
2383 xmode_switch_err('threaded')
2391 xmode_switch_err('threaded')
2384
2392
2385 def magic_colors(self,parameter_s = ''):
2393 def magic_colors(self,parameter_s = ''):
2386 """Switch color scheme for prompts, info system and exception handlers.
2394 """Switch color scheme for prompts, info system and exception handlers.
2387
2395
2388 Currently implemented schemes: NoColor, Linux, LightBG.
2396 Currently implemented schemes: NoColor, Linux, LightBG.
2389
2397
2390 Color scheme names are not case-sensitive."""
2398 Color scheme names are not case-sensitive."""
2391
2399
2392 def color_switch_err(name):
2400 def color_switch_err(name):
2393 warn('Error changing %s color schemes.\n%s' %
2401 warn('Error changing %s color schemes.\n%s' %
2394 (name,sys.exc_info()[1]))
2402 (name,sys.exc_info()[1]))
2395
2403
2396
2404
2397 new_scheme = parameter_s.strip()
2405 new_scheme = parameter_s.strip()
2398 if not new_scheme:
2406 if not new_scheme:
2399 raise UsageError(
2407 raise UsageError(
2400 "%colors: you must specify a color scheme. See '%colors?'")
2408 "%colors: you must specify a color scheme. See '%colors?'")
2401 return
2409 return
2402 # local shortcut
2410 # local shortcut
2403 shell = self.shell
2411 shell = self.shell
2404
2412
2405 import IPython.rlineimpl as readline
2413 import IPython.rlineimpl as readline
2406
2414
2407 if not readline.have_readline and sys.platform == "win32":
2415 if not readline.have_readline and sys.platform == "win32":
2408 msg = """\
2416 msg = """\
2409 Proper color support under MS Windows requires the pyreadline library.
2417 Proper color support under MS Windows requires the pyreadline library.
2410 You can find it at:
2418 You can find it at:
2411 http://ipython.scipy.org/moin/PyReadline/Intro
2419 http://ipython.scipy.org/moin/PyReadline/Intro
2412 Gary's readline needs the ctypes module, from:
2420 Gary's readline needs the ctypes module, from:
2413 http://starship.python.net/crew/theller/ctypes
2421 http://starship.python.net/crew/theller/ctypes
2414 (Note that ctypes is already part of Python versions 2.5 and newer).
2422 (Note that ctypes is already part of Python versions 2.5 and newer).
2415
2423
2416 Defaulting color scheme to 'NoColor'"""
2424 Defaulting color scheme to 'NoColor'"""
2417 new_scheme = 'NoColor'
2425 new_scheme = 'NoColor'
2418 warn(msg)
2426 warn(msg)
2419
2427
2420 # readline option is 0
2428 # readline option is 0
2421 if not shell.has_readline:
2429 if not shell.has_readline:
2422 new_scheme = 'NoColor'
2430 new_scheme = 'NoColor'
2423
2431
2424 # Set prompt colors
2432 # Set prompt colors
2425 try:
2433 try:
2426 shell.outputcache.set_colors(new_scheme)
2434 shell.outputcache.set_colors(new_scheme)
2427 except:
2435 except:
2428 color_switch_err('prompt')
2436 color_switch_err('prompt')
2429 else:
2437 else:
2430 shell.rc.colors = \
2438 shell.rc.colors = \
2431 shell.outputcache.color_table.active_scheme_name
2439 shell.outputcache.color_table.active_scheme_name
2432 # Set exception colors
2440 # Set exception colors
2433 try:
2441 try:
2434 shell.InteractiveTB.set_colors(scheme = new_scheme)
2442 shell.InteractiveTB.set_colors(scheme = new_scheme)
2435 shell.SyntaxTB.set_colors(scheme = new_scheme)
2443 shell.SyntaxTB.set_colors(scheme = new_scheme)
2436 except:
2444 except:
2437 color_switch_err('exception')
2445 color_switch_err('exception')
2438
2446
2439 # threaded shells use a verbose traceback in sys.excepthook
2447 # threaded shells use a verbose traceback in sys.excepthook
2440 if shell.isthreaded:
2448 if shell.isthreaded:
2441 try:
2449 try:
2442 shell.sys_excepthook.set_colors(scheme=new_scheme)
2450 shell.sys_excepthook.set_colors(scheme=new_scheme)
2443 except:
2451 except:
2444 color_switch_err('system exception handler')
2452 color_switch_err('system exception handler')
2445
2453
2446 # Set info (for 'object?') colors
2454 # Set info (for 'object?') colors
2447 if shell.rc.color_info:
2455 if shell.rc.color_info:
2448 try:
2456 try:
2449 shell.inspector.set_active_scheme(new_scheme)
2457 shell.inspector.set_active_scheme(new_scheme)
2450 except:
2458 except:
2451 color_switch_err('object inspector')
2459 color_switch_err('object inspector')
2452 else:
2460 else:
2453 shell.inspector.set_active_scheme('NoColor')
2461 shell.inspector.set_active_scheme('NoColor')
2454
2462
2455 def magic_color_info(self,parameter_s = ''):
2463 def magic_color_info(self,parameter_s = ''):
2456 """Toggle color_info.
2464 """Toggle color_info.
2457
2465
2458 The color_info configuration parameter controls whether colors are
2466 The color_info configuration parameter controls whether colors are
2459 used for displaying object details (by things like %psource, %pfile or
2467 used for displaying object details (by things like %psource, %pfile or
2460 the '?' system). This function toggles this value with each call.
2468 the '?' system). This function toggles this value with each call.
2461
2469
2462 Note that unless you have a fairly recent pager (less works better
2470 Note that unless you have a fairly recent pager (less works better
2463 than more) in your system, using colored object information displays
2471 than more) in your system, using colored object information displays
2464 will not work properly. Test it and see."""
2472 will not work properly. Test it and see."""
2465
2473
2466 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2474 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2467 self.magic_colors(self.shell.rc.colors)
2475 self.magic_colors(self.shell.rc.colors)
2468 print 'Object introspection functions have now coloring:',
2476 print 'Object introspection functions have now coloring:',
2469 print ['OFF','ON'][self.shell.rc.color_info]
2477 print ['OFF','ON'][self.shell.rc.color_info]
2470
2478
2471 def magic_Pprint(self, parameter_s=''):
2479 def magic_Pprint(self, parameter_s=''):
2472 """Toggle pretty printing on/off."""
2480 """Toggle pretty printing on/off."""
2473
2481
2474 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2482 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2475 print 'Pretty printing has been turned', \
2483 print 'Pretty printing has been turned', \
2476 ['OFF','ON'][self.shell.rc.pprint]
2484 ['OFF','ON'][self.shell.rc.pprint]
2477
2485
2478 def magic_exit(self, parameter_s=''):
2486 def magic_exit(self, parameter_s=''):
2479 """Exit IPython, confirming if configured to do so.
2487 """Exit IPython, confirming if configured to do so.
2480
2488
2481 You can configure whether IPython asks for confirmation upon exit by
2489 You can configure whether IPython asks for confirmation upon exit by
2482 setting the confirm_exit flag in the ipythonrc file."""
2490 setting the confirm_exit flag in the ipythonrc file."""
2483
2491
2484 self.shell.exit()
2492 self.shell.exit()
2485
2493
2486 def magic_quit(self, parameter_s=''):
2494 def magic_quit(self, parameter_s=''):
2487 """Exit IPython, confirming if configured to do so (like %exit)"""
2495 """Exit IPython, confirming if configured to do so (like %exit)"""
2488
2496
2489 self.shell.exit()
2497 self.shell.exit()
2490
2498
2491 def magic_Exit(self, parameter_s=''):
2499 def magic_Exit(self, parameter_s=''):
2492 """Exit IPython without confirmation."""
2500 """Exit IPython without confirmation."""
2493
2501
2494 self.shell.ask_exit()
2502 self.shell.ask_exit()
2495
2503
2496 #......................................................................
2504 #......................................................................
2497 # Functions to implement unix shell-type things
2505 # Functions to implement unix shell-type things
2498
2506
2499 @testdec.skip_doctest
2507 @testdec.skip_doctest
2500 def magic_alias(self, parameter_s = ''):
2508 def magic_alias(self, parameter_s = ''):
2501 """Define an alias for a system command.
2509 """Define an alias for a system command.
2502
2510
2503 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2511 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2504
2512
2505 Then, typing 'alias_name params' will execute the system command 'cmd
2513 Then, typing 'alias_name params' will execute the system command 'cmd
2506 params' (from your underlying operating system).
2514 params' (from your underlying operating system).
2507
2515
2508 Aliases have lower precedence than magic functions and Python normal
2516 Aliases have lower precedence than magic functions and Python normal
2509 variables, so if 'foo' is both a Python variable and an alias, the
2517 variables, so if 'foo' is both a Python variable and an alias, the
2510 alias can not be executed until 'del foo' removes the Python variable.
2518 alias can not be executed until 'del foo' removes the Python variable.
2511
2519
2512 You can use the %l specifier in an alias definition to represent the
2520 You can use the %l specifier in an alias definition to represent the
2513 whole line when the alias is called. For example:
2521 whole line when the alias is called. For example:
2514
2522
2515 In [2]: alias all echo "Input in brackets: <%l>"
2523 In [2]: alias all echo "Input in brackets: <%l>"
2516 In [3]: all hello world
2524 In [3]: all hello world
2517 Input in brackets: <hello world>
2525 Input in brackets: <hello world>
2518
2526
2519 You can also define aliases with parameters using %s specifiers (one
2527 You can also define aliases with parameters using %s specifiers (one
2520 per parameter):
2528 per parameter):
2521
2529
2522 In [1]: alias parts echo first %s second %s
2530 In [1]: alias parts echo first %s second %s
2523 In [2]: %parts A B
2531 In [2]: %parts A B
2524 first A second B
2532 first A second B
2525 In [3]: %parts A
2533 In [3]: %parts A
2526 Incorrect number of arguments: 2 expected.
2534 Incorrect number of arguments: 2 expected.
2527 parts is an alias to: 'echo first %s second %s'
2535 parts is an alias to: 'echo first %s second %s'
2528
2536
2529 Note that %l and %s are mutually exclusive. You can only use one or
2537 Note that %l and %s are mutually exclusive. You can only use one or
2530 the other in your aliases.
2538 the other in your aliases.
2531
2539
2532 Aliases expand Python variables just like system calls using ! or !!
2540 Aliases expand Python variables just like system calls using ! or !!
2533 do: all expressions prefixed with '$' get expanded. For details of
2541 do: all expressions prefixed with '$' get expanded. For details of
2534 the semantic rules, see PEP-215:
2542 the semantic rules, see PEP-215:
2535 http://www.python.org/peps/pep-0215.html. This is the library used by
2543 http://www.python.org/peps/pep-0215.html. This is the library used by
2536 IPython for variable expansion. If you want to access a true shell
2544 IPython for variable expansion. If you want to access a true shell
2537 variable, an extra $ is necessary to prevent its expansion by IPython:
2545 variable, an extra $ is necessary to prevent its expansion by IPython:
2538
2546
2539 In [6]: alias show echo
2547 In [6]: alias show echo
2540 In [7]: PATH='A Python string'
2548 In [7]: PATH='A Python string'
2541 In [8]: show $PATH
2549 In [8]: show $PATH
2542 A Python string
2550 A Python string
2543 In [9]: show $$PATH
2551 In [9]: show $$PATH
2544 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2552 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2545
2553
2546 You can use the alias facility to acess all of $PATH. See the %rehash
2554 You can use the alias facility to acess all of $PATH. See the %rehash
2547 and %rehashx functions, which automatically create aliases for the
2555 and %rehashx functions, which automatically create aliases for the
2548 contents of your $PATH.
2556 contents of your $PATH.
2549
2557
2550 If called with no parameters, %alias prints the current alias table."""
2558 If called with no parameters, %alias prints the current alias table."""
2551
2559
2552 par = parameter_s.strip()
2560 par = parameter_s.strip()
2553 if not par:
2561 if not par:
2554 stored = self.db.get('stored_aliases', {} )
2562 stored = self.db.get('stored_aliases', {} )
2555 atab = self.shell.alias_table
2563 atab = self.shell.alias_table
2556 aliases = atab.keys()
2564 aliases = atab.keys()
2557 aliases.sort()
2565 aliases.sort()
2558 res = []
2566 res = []
2559 showlast = []
2567 showlast = []
2560 for alias in aliases:
2568 for alias in aliases:
2561 special = False
2569 special = False
2562 try:
2570 try:
2563 tgt = atab[alias][1]
2571 tgt = atab[alias][1]
2564 except (TypeError, AttributeError):
2572 except (TypeError, AttributeError):
2565 # unsubscriptable? probably a callable
2573 # unsubscriptable? probably a callable
2566 tgt = atab[alias]
2574 tgt = atab[alias]
2567 special = True
2575 special = True
2568 # 'interesting' aliases
2576 # 'interesting' aliases
2569 if (alias in stored or
2577 if (alias in stored or
2570 special or
2578 special or
2571 alias.lower() != os.path.splitext(tgt)[0].lower() or
2579 alias.lower() != os.path.splitext(tgt)[0].lower() or
2572 ' ' in tgt):
2580 ' ' in tgt):
2573 showlast.append((alias, tgt))
2581 showlast.append((alias, tgt))
2574 else:
2582 else:
2575 res.append((alias, tgt ))
2583 res.append((alias, tgt ))
2576
2584
2577 # show most interesting aliases last
2585 # show most interesting aliases last
2578 res.extend(showlast)
2586 res.extend(showlast)
2579 print "Total number of aliases:",len(aliases)
2587 print "Total number of aliases:",len(aliases)
2580 return res
2588 return res
2581 try:
2589 try:
2582 alias,cmd = par.split(None,1)
2590 alias,cmd = par.split(None,1)
2583 except:
2591 except:
2584 print OInspect.getdoc(self.magic_alias)
2592 print OInspect.getdoc(self.magic_alias)
2585 else:
2593 else:
2586 nargs = cmd.count('%s')
2594 nargs = cmd.count('%s')
2587 if nargs>0 and cmd.find('%l')>=0:
2595 if nargs>0 and cmd.find('%l')>=0:
2588 error('The %s and %l specifiers are mutually exclusive '
2596 error('The %s and %l specifiers are mutually exclusive '
2589 'in alias definitions.')
2597 'in alias definitions.')
2590 else: # all looks OK
2598 else: # all looks OK
2591 self.shell.alias_table[alias] = (nargs,cmd)
2599 self.shell.alias_table[alias] = (nargs,cmd)
2592 self.shell.alias_table_validate(verbose=0)
2600 self.shell.alias_table_validate(verbose=0)
2593 # end magic_alias
2601 # end magic_alias
2594
2602
2595 def magic_unalias(self, parameter_s = ''):
2603 def magic_unalias(self, parameter_s = ''):
2596 """Remove an alias"""
2604 """Remove an alias"""
2597
2605
2598 aname = parameter_s.strip()
2606 aname = parameter_s.strip()
2599 if aname in self.shell.alias_table:
2607 if aname in self.shell.alias_table:
2600 del self.shell.alias_table[aname]
2608 del self.shell.alias_table[aname]
2601 stored = self.db.get('stored_aliases', {} )
2609 stored = self.db.get('stored_aliases', {} )
2602 if aname in stored:
2610 if aname in stored:
2603 print "Removing %stored alias",aname
2611 print "Removing %stored alias",aname
2604 del stored[aname]
2612 del stored[aname]
2605 self.db['stored_aliases'] = stored
2613 self.db['stored_aliases'] = stored
2606
2614
2607
2615
2608 def magic_rehashx(self, parameter_s = ''):
2616 def magic_rehashx(self, parameter_s = ''):
2609 """Update the alias table with all executable files in $PATH.
2617 """Update the alias table with all executable files in $PATH.
2610
2618
2611 This version explicitly checks that every entry in $PATH is a file
2619 This version explicitly checks that every entry in $PATH is a file
2612 with execute access (os.X_OK), so it is much slower than %rehash.
2620 with execute access (os.X_OK), so it is much slower than %rehash.
2613
2621
2614 Under Windows, it checks executability as a match agains a
2622 Under Windows, it checks executability as a match agains a
2615 '|'-separated string of extensions, stored in the IPython config
2623 '|'-separated string of extensions, stored in the IPython config
2616 variable win_exec_ext. This defaults to 'exe|com|bat'.
2624 variable win_exec_ext. This defaults to 'exe|com|bat'.
2617
2625
2618 This function also resets the root module cache of module completer,
2626 This function also resets the root module cache of module completer,
2619 used on slow filesystems.
2627 used on slow filesystems.
2620 """
2628 """
2621
2629
2622
2630
2623 ip = self.api
2631 ip = self.api
2624
2632
2625 # for the benefit of module completer in ipy_completers.py
2633 # for the benefit of module completer in ipy_completers.py
2626 del ip.db['rootmodules']
2634 del ip.db['rootmodules']
2627
2635
2628 path = [os.path.abspath(os.path.expanduser(p)) for p in
2636 path = [os.path.abspath(os.path.expanduser(p)) for p in
2629 os.environ.get('PATH','').split(os.pathsep)]
2637 os.environ.get('PATH','').split(os.pathsep)]
2630 path = filter(os.path.isdir,path)
2638 path = filter(os.path.isdir,path)
2631
2639
2632 alias_table = self.shell.alias_table
2640 alias_table = self.shell.alias_table
2633 syscmdlist = []
2641 syscmdlist = []
2634 if os.name == 'posix':
2642 if os.name == 'posix':
2635 isexec = lambda fname:os.path.isfile(fname) and \
2643 isexec = lambda fname:os.path.isfile(fname) and \
2636 os.access(fname,os.X_OK)
2644 os.access(fname,os.X_OK)
2637 else:
2645 else:
2638
2646
2639 try:
2647 try:
2640 winext = os.environ['pathext'].replace(';','|').replace('.','')
2648 winext = os.environ['pathext'].replace(';','|').replace('.','')
2641 except KeyError:
2649 except KeyError:
2642 winext = 'exe|com|bat|py'
2650 winext = 'exe|com|bat|py'
2643 if 'py' not in winext:
2651 if 'py' not in winext:
2644 winext += '|py'
2652 winext += '|py'
2645 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2653 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2646 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2654 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2647 savedir = os.getcwd()
2655 savedir = os.getcwd()
2648 try:
2656 try:
2649 # write the whole loop for posix/Windows so we don't have an if in
2657 # write the whole loop for posix/Windows so we don't have an if in
2650 # the innermost part
2658 # the innermost part
2651 if os.name == 'posix':
2659 if os.name == 'posix':
2652 for pdir in path:
2660 for pdir in path:
2653 os.chdir(pdir)
2661 os.chdir(pdir)
2654 for ff in os.listdir(pdir):
2662 for ff in os.listdir(pdir):
2655 if isexec(ff) and ff not in self.shell.no_alias:
2663 if isexec(ff) and ff not in self.shell.no_alias:
2656 # each entry in the alias table must be (N,name),
2664 # each entry in the alias table must be (N,name),
2657 # where N is the number of positional arguments of the
2665 # where N is the number of positional arguments of the
2658 # alias.
2666 # alias.
2659 # Dots will be removed from alias names, since ipython
2667 # Dots will be removed from alias names, since ipython
2660 # assumes names with dots to be python code
2668 # assumes names with dots to be python code
2661 alias_table[ff.replace('.','')] = (0,ff)
2669 alias_table[ff.replace('.','')] = (0,ff)
2662 syscmdlist.append(ff)
2670 syscmdlist.append(ff)
2663 else:
2671 else:
2664 for pdir in path:
2672 for pdir in path:
2665 os.chdir(pdir)
2673 os.chdir(pdir)
2666 for ff in os.listdir(pdir):
2674 for ff in os.listdir(pdir):
2667 base, ext = os.path.splitext(ff)
2675 base, ext = os.path.splitext(ff)
2668 if isexec(ff) and base.lower() not in self.shell.no_alias:
2676 if isexec(ff) and base.lower() not in self.shell.no_alias:
2669 if ext.lower() == '.exe':
2677 if ext.lower() == '.exe':
2670 ff = base
2678 ff = base
2671 alias_table[base.lower().replace('.','')] = (0,ff)
2679 alias_table[base.lower().replace('.','')] = (0,ff)
2672 syscmdlist.append(ff)
2680 syscmdlist.append(ff)
2673 # Make sure the alias table doesn't contain keywords or builtins
2681 # Make sure the alias table doesn't contain keywords or builtins
2674 self.shell.alias_table_validate()
2682 self.shell.alias_table_validate()
2675 # Call again init_auto_alias() so we get 'rm -i' and other
2683 # Call again init_auto_alias() so we get 'rm -i' and other
2676 # modified aliases since %rehashx will probably clobber them
2684 # modified aliases since %rehashx will probably clobber them
2677
2685
2678 # no, we don't want them. if %rehashx clobbers them, good,
2686 # no, we don't want them. if %rehashx clobbers them, good,
2679 # we'll probably get better versions
2687 # we'll probably get better versions
2680 # self.shell.init_auto_alias()
2688 # self.shell.init_auto_alias()
2681 db = ip.db
2689 db = ip.db
2682 db['syscmdlist'] = syscmdlist
2690 db['syscmdlist'] = syscmdlist
2683 finally:
2691 finally:
2684 os.chdir(savedir)
2692 os.chdir(savedir)
2685
2693
2686 def magic_pwd(self, parameter_s = ''):
2694 def magic_pwd(self, parameter_s = ''):
2687 """Return the current working directory path."""
2695 """Return the current working directory path."""
2688 return os.getcwd()
2696 return os.getcwd()
2689
2697
2690 def magic_cd(self, parameter_s=''):
2698 def magic_cd(self, parameter_s=''):
2691 """Change the current working directory.
2699 """Change the current working directory.
2692
2700
2693 This command automatically maintains an internal list of directories
2701 This command automatically maintains an internal list of directories
2694 you visit during your IPython session, in the variable _dh. The
2702 you visit during your IPython session, in the variable _dh. The
2695 command %dhist shows this history nicely formatted. You can also
2703 command %dhist shows this history nicely formatted. You can also
2696 do 'cd -<tab>' to see directory history conveniently.
2704 do 'cd -<tab>' to see directory history conveniently.
2697
2705
2698 Usage:
2706 Usage:
2699
2707
2700 cd 'dir': changes to directory 'dir'.
2708 cd 'dir': changes to directory 'dir'.
2701
2709
2702 cd -: changes to the last visited directory.
2710 cd -: changes to the last visited directory.
2703
2711
2704 cd -<n>: changes to the n-th directory in the directory history.
2712 cd -<n>: changes to the n-th directory in the directory history.
2705
2713
2706 cd --foo: change to directory that matches 'foo' in history
2714 cd --foo: change to directory that matches 'foo' in history
2707
2715
2708 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2716 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2709 (note: cd <bookmark_name> is enough if there is no
2717 (note: cd <bookmark_name> is enough if there is no
2710 directory <bookmark_name>, but a bookmark with the name exists.)
2718 directory <bookmark_name>, but a bookmark with the name exists.)
2711 'cd -b <tab>' allows you to tab-complete bookmark names.
2719 'cd -b <tab>' allows you to tab-complete bookmark names.
2712
2720
2713 Options:
2721 Options:
2714
2722
2715 -q: quiet. Do not print the working directory after the cd command is
2723 -q: quiet. Do not print the working directory after the cd command is
2716 executed. By default IPython's cd command does print this directory,
2724 executed. By default IPython's cd command does print this directory,
2717 since the default prompts do not display path information.
2725 since the default prompts do not display path information.
2718
2726
2719 Note that !cd doesn't work for this purpose because the shell where
2727 Note that !cd doesn't work for this purpose because the shell where
2720 !command runs is immediately discarded after executing 'command'."""
2728 !command runs is immediately discarded after executing 'command'."""
2721
2729
2722 parameter_s = parameter_s.strip()
2730 parameter_s = parameter_s.strip()
2723 #bkms = self.shell.persist.get("bookmarks",{})
2731 #bkms = self.shell.persist.get("bookmarks",{})
2724
2732
2725 oldcwd = os.getcwd()
2733 oldcwd = os.getcwd()
2726 numcd = re.match(r'(-)(\d+)$',parameter_s)
2734 numcd = re.match(r'(-)(\d+)$',parameter_s)
2727 # jump in directory history by number
2735 # jump in directory history by number
2728 if numcd:
2736 if numcd:
2729 nn = int(numcd.group(2))
2737 nn = int(numcd.group(2))
2730 try:
2738 try:
2731 ps = self.shell.user_ns['_dh'][nn]
2739 ps = self.shell.user_ns['_dh'][nn]
2732 except IndexError:
2740 except IndexError:
2733 print 'The requested directory does not exist in history.'
2741 print 'The requested directory does not exist in history.'
2734 return
2742 return
2735 else:
2743 else:
2736 opts = {}
2744 opts = {}
2737 elif parameter_s.startswith('--'):
2745 elif parameter_s.startswith('--'):
2738 ps = None
2746 ps = None
2739 fallback = None
2747 fallback = None
2740 pat = parameter_s[2:]
2748 pat = parameter_s[2:]
2741 dh = self.shell.user_ns['_dh']
2749 dh = self.shell.user_ns['_dh']
2742 # first search only by basename (last component)
2750 # first search only by basename (last component)
2743 for ent in reversed(dh):
2751 for ent in reversed(dh):
2744 if pat in os.path.basename(ent) and os.path.isdir(ent):
2752 if pat in os.path.basename(ent) and os.path.isdir(ent):
2745 ps = ent
2753 ps = ent
2746 break
2754 break
2747
2755
2748 if fallback is None and pat in ent and os.path.isdir(ent):
2756 if fallback is None and pat in ent and os.path.isdir(ent):
2749 fallback = ent
2757 fallback = ent
2750
2758
2751 # if we have no last part match, pick the first full path match
2759 # if we have no last part match, pick the first full path match
2752 if ps is None:
2760 if ps is None:
2753 ps = fallback
2761 ps = fallback
2754
2762
2755 if ps is None:
2763 if ps is None:
2756 print "No matching entry in directory history"
2764 print "No matching entry in directory history"
2757 return
2765 return
2758 else:
2766 else:
2759 opts = {}
2767 opts = {}
2760
2768
2761
2769
2762 else:
2770 else:
2763 #turn all non-space-escaping backslashes to slashes,
2771 #turn all non-space-escaping backslashes to slashes,
2764 # for c:\windows\directory\names\
2772 # for c:\windows\directory\names\
2765 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2773 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2766 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2774 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2767 # jump to previous
2775 # jump to previous
2768 if ps == '-':
2776 if ps == '-':
2769 try:
2777 try:
2770 ps = self.shell.user_ns['_dh'][-2]
2778 ps = self.shell.user_ns['_dh'][-2]
2771 except IndexError:
2779 except IndexError:
2772 raise UsageError('%cd -: No previous directory to change to.')
2780 raise UsageError('%cd -: No previous directory to change to.')
2773 # jump to bookmark if needed
2781 # jump to bookmark if needed
2774 else:
2782 else:
2775 if not os.path.isdir(ps) or opts.has_key('b'):
2783 if not os.path.isdir(ps) or opts.has_key('b'):
2776 bkms = self.db.get('bookmarks', {})
2784 bkms = self.db.get('bookmarks', {})
2777
2785
2778 if bkms.has_key(ps):
2786 if bkms.has_key(ps):
2779 target = bkms[ps]
2787 target = bkms[ps]
2780 print '(bookmark:%s) -> %s' % (ps,target)
2788 print '(bookmark:%s) -> %s' % (ps,target)
2781 ps = target
2789 ps = target
2782 else:
2790 else:
2783 if opts.has_key('b'):
2791 if opts.has_key('b'):
2784 raise UsageError("Bookmark '%s' not found. "
2792 raise UsageError("Bookmark '%s' not found. "
2785 "Use '%%bookmark -l' to see your bookmarks." % ps)
2793 "Use '%%bookmark -l' to see your bookmarks." % ps)
2786
2794
2787 # at this point ps should point to the target dir
2795 # at this point ps should point to the target dir
2788 if ps:
2796 if ps:
2789 try:
2797 try:
2790 os.chdir(os.path.expanduser(ps))
2798 os.chdir(os.path.expanduser(ps))
2791 if self.shell.rc.term_title:
2799 if self.shell.rc.term_title:
2792 #print 'set term title:',self.shell.rc.term_title # dbg
2800 #print 'set term title:',self.shell.rc.term_title # dbg
2793 platutils.set_term_title('IPy ' + abbrev_cwd())
2801 platutils.set_term_title('IPy ' + abbrev_cwd())
2794 except OSError:
2802 except OSError:
2795 print sys.exc_info()[1]
2803 print sys.exc_info()[1]
2796 else:
2804 else:
2797 cwd = os.getcwd()
2805 cwd = os.getcwd()
2798 dhist = self.shell.user_ns['_dh']
2806 dhist = self.shell.user_ns['_dh']
2799 if oldcwd != cwd:
2807 if oldcwd != cwd:
2800 dhist.append(cwd)
2808 dhist.append(cwd)
2801 self.db['dhist'] = compress_dhist(dhist)[-100:]
2809 self.db['dhist'] = compress_dhist(dhist)[-100:]
2802
2810
2803 else:
2811 else:
2804 os.chdir(self.shell.home_dir)
2812 os.chdir(self.shell.home_dir)
2805 if self.shell.rc.term_title:
2813 if self.shell.rc.term_title:
2806 platutils.set_term_title("IPy ~")
2814 platutils.set_term_title("IPy ~")
2807 cwd = os.getcwd()
2815 cwd = os.getcwd()
2808 dhist = self.shell.user_ns['_dh']
2816 dhist = self.shell.user_ns['_dh']
2809
2817
2810 if oldcwd != cwd:
2818 if oldcwd != cwd:
2811 dhist.append(cwd)
2819 dhist.append(cwd)
2812 self.db['dhist'] = compress_dhist(dhist)[-100:]
2820 self.db['dhist'] = compress_dhist(dhist)[-100:]
2813 if not 'q' in opts and self.shell.user_ns['_dh']:
2821 if not 'q' in opts and self.shell.user_ns['_dh']:
2814 print self.shell.user_ns['_dh'][-1]
2822 print self.shell.user_ns['_dh'][-1]
2815
2823
2816
2824
2817 def magic_env(self, parameter_s=''):
2825 def magic_env(self, parameter_s=''):
2818 """List environment variables."""
2826 """List environment variables."""
2819
2827
2820 return os.environ.data
2828 return os.environ.data
2821
2829
2822 def magic_pushd(self, parameter_s=''):
2830 def magic_pushd(self, parameter_s=''):
2823 """Place the current dir on stack and change directory.
2831 """Place the current dir on stack and change directory.
2824
2832
2825 Usage:\\
2833 Usage:\\
2826 %pushd ['dirname']
2834 %pushd ['dirname']
2827 """
2835 """
2828
2836
2829 dir_s = self.shell.dir_stack
2837 dir_s = self.shell.dir_stack
2830 tgt = os.path.expanduser(parameter_s)
2838 tgt = os.path.expanduser(parameter_s)
2831 cwd = os.getcwd().replace(self.home_dir,'~')
2839 cwd = os.getcwd().replace(self.home_dir,'~')
2832 if tgt:
2840 if tgt:
2833 self.magic_cd(parameter_s)
2841 self.magic_cd(parameter_s)
2834 dir_s.insert(0,cwd)
2842 dir_s.insert(0,cwd)
2835 return self.magic_dirs()
2843 return self.magic_dirs()
2836
2844
2837 def magic_popd(self, parameter_s=''):
2845 def magic_popd(self, parameter_s=''):
2838 """Change to directory popped off the top of the stack.
2846 """Change to directory popped off the top of the stack.
2839 """
2847 """
2840 if not self.shell.dir_stack:
2848 if not self.shell.dir_stack:
2841 raise UsageError("%popd on empty stack")
2849 raise UsageError("%popd on empty stack")
2842 top = self.shell.dir_stack.pop(0)
2850 top = self.shell.dir_stack.pop(0)
2843 self.magic_cd(top)
2851 self.magic_cd(top)
2844 print "popd ->",top
2852 print "popd ->",top
2845
2853
2846 def magic_dirs(self, parameter_s=''):
2854 def magic_dirs(self, parameter_s=''):
2847 """Return the current directory stack."""
2855 """Return the current directory stack."""
2848
2856
2849 return self.shell.dir_stack
2857 return self.shell.dir_stack
2850
2858
2851 def magic_dhist(self, parameter_s=''):
2859 def magic_dhist(self, parameter_s=''):
2852 """Print your history of visited directories.
2860 """Print your history of visited directories.
2853
2861
2854 %dhist -> print full history\\
2862 %dhist -> print full history\\
2855 %dhist n -> print last n entries only\\
2863 %dhist n -> print last n entries only\\
2856 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2864 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2857
2865
2858 This history is automatically maintained by the %cd command, and
2866 This history is automatically maintained by the %cd command, and
2859 always available as the global list variable _dh. You can use %cd -<n>
2867 always available as the global list variable _dh. You can use %cd -<n>
2860 to go to directory number <n>.
2868 to go to directory number <n>.
2861
2869
2862 Note that most of time, you should view directory history by entering
2870 Note that most of time, you should view directory history by entering
2863 cd -<TAB>.
2871 cd -<TAB>.
2864
2872
2865 """
2873 """
2866
2874
2867 dh = self.shell.user_ns['_dh']
2875 dh = self.shell.user_ns['_dh']
2868 if parameter_s:
2876 if parameter_s:
2869 try:
2877 try:
2870 args = map(int,parameter_s.split())
2878 args = map(int,parameter_s.split())
2871 except:
2879 except:
2872 self.arg_err(Magic.magic_dhist)
2880 self.arg_err(Magic.magic_dhist)
2873 return
2881 return
2874 if len(args) == 1:
2882 if len(args) == 1:
2875 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2883 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2876 elif len(args) == 2:
2884 elif len(args) == 2:
2877 ini,fin = args
2885 ini,fin = args
2878 else:
2886 else:
2879 self.arg_err(Magic.magic_dhist)
2887 self.arg_err(Magic.magic_dhist)
2880 return
2888 return
2881 else:
2889 else:
2882 ini,fin = 0,len(dh)
2890 ini,fin = 0,len(dh)
2883 nlprint(dh,
2891 nlprint(dh,
2884 header = 'Directory history (kept in _dh)',
2892 header = 'Directory history (kept in _dh)',
2885 start=ini,stop=fin)
2893 start=ini,stop=fin)
2886
2894
2887 @testdec.skip_doctest
2895 @testdec.skip_doctest
2888 def magic_sc(self, parameter_s=''):
2896 def magic_sc(self, parameter_s=''):
2889 """Shell capture - execute a shell command and capture its output.
2897 """Shell capture - execute a shell command and capture its output.
2890
2898
2891 DEPRECATED. Suboptimal, retained for backwards compatibility.
2899 DEPRECATED. Suboptimal, retained for backwards compatibility.
2892
2900
2893 You should use the form 'var = !command' instead. Example:
2901 You should use the form 'var = !command' instead. Example:
2894
2902
2895 "%sc -l myfiles = ls ~" should now be written as
2903 "%sc -l myfiles = ls ~" should now be written as
2896
2904
2897 "myfiles = !ls ~"
2905 "myfiles = !ls ~"
2898
2906
2899 myfiles.s, myfiles.l and myfiles.n still apply as documented
2907 myfiles.s, myfiles.l and myfiles.n still apply as documented
2900 below.
2908 below.
2901
2909
2902 --
2910 --
2903 %sc [options] varname=command
2911 %sc [options] varname=command
2904
2912
2905 IPython will run the given command using commands.getoutput(), and
2913 IPython will run the given command using commands.getoutput(), and
2906 will then update the user's interactive namespace with a variable
2914 will then update the user's interactive namespace with a variable
2907 called varname, containing the value of the call. Your command can
2915 called varname, containing the value of the call. Your command can
2908 contain shell wildcards, pipes, etc.
2916 contain shell wildcards, pipes, etc.
2909
2917
2910 The '=' sign in the syntax is mandatory, and the variable name you
2918 The '=' sign in the syntax is mandatory, and the variable name you
2911 supply must follow Python's standard conventions for valid names.
2919 supply must follow Python's standard conventions for valid names.
2912
2920
2913 (A special format without variable name exists for internal use)
2921 (A special format without variable name exists for internal use)
2914
2922
2915 Options:
2923 Options:
2916
2924
2917 -l: list output. Split the output on newlines into a list before
2925 -l: list output. Split the output on newlines into a list before
2918 assigning it to the given variable. By default the output is stored
2926 assigning it to the given variable. By default the output is stored
2919 as a single string.
2927 as a single string.
2920
2928
2921 -v: verbose. Print the contents of the variable.
2929 -v: verbose. Print the contents of the variable.
2922
2930
2923 In most cases you should not need to split as a list, because the
2931 In most cases you should not need to split as a list, because the
2924 returned value is a special type of string which can automatically
2932 returned value is a special type of string which can automatically
2925 provide its contents either as a list (split on newlines) or as a
2933 provide its contents either as a list (split on newlines) or as a
2926 space-separated string. These are convenient, respectively, either
2934 space-separated string. These are convenient, respectively, either
2927 for sequential processing or to be passed to a shell command.
2935 for sequential processing or to be passed to a shell command.
2928
2936
2929 For example:
2937 For example:
2930
2938
2931 # all-random
2939 # all-random
2932
2940
2933 # Capture into variable a
2941 # Capture into variable a
2934 In [1]: sc a=ls *py
2942 In [1]: sc a=ls *py
2935
2943
2936 # a is a string with embedded newlines
2944 # a is a string with embedded newlines
2937 In [2]: a
2945 In [2]: a
2938 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2946 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2939
2947
2940 # which can be seen as a list:
2948 # which can be seen as a list:
2941 In [3]: a.l
2949 In [3]: a.l
2942 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2950 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2943
2951
2944 # or as a whitespace-separated string:
2952 # or as a whitespace-separated string:
2945 In [4]: a.s
2953 In [4]: a.s
2946 Out[4]: 'setup.py win32_manual_post_install.py'
2954 Out[4]: 'setup.py win32_manual_post_install.py'
2947
2955
2948 # a.s is useful to pass as a single command line:
2956 # a.s is useful to pass as a single command line:
2949 In [5]: !wc -l $a.s
2957 In [5]: !wc -l $a.s
2950 146 setup.py
2958 146 setup.py
2951 130 win32_manual_post_install.py
2959 130 win32_manual_post_install.py
2952 276 total
2960 276 total
2953
2961
2954 # while the list form is useful to loop over:
2962 # while the list form is useful to loop over:
2955 In [6]: for f in a.l:
2963 In [6]: for f in a.l:
2956 ...: !wc -l $f
2964 ...: !wc -l $f
2957 ...:
2965 ...:
2958 146 setup.py
2966 146 setup.py
2959 130 win32_manual_post_install.py
2967 130 win32_manual_post_install.py
2960
2968
2961 Similiarly, the lists returned by the -l option are also special, in
2969 Similiarly, the lists returned by the -l option are also special, in
2962 the sense that you can equally invoke the .s attribute on them to
2970 the sense that you can equally invoke the .s attribute on them to
2963 automatically get a whitespace-separated string from their contents:
2971 automatically get a whitespace-separated string from their contents:
2964
2972
2965 In [7]: sc -l b=ls *py
2973 In [7]: sc -l b=ls *py
2966
2974
2967 In [8]: b
2975 In [8]: b
2968 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2976 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2969
2977
2970 In [9]: b.s
2978 In [9]: b.s
2971 Out[9]: 'setup.py win32_manual_post_install.py'
2979 Out[9]: 'setup.py win32_manual_post_install.py'
2972
2980
2973 In summary, both the lists and strings used for ouptut capture have
2981 In summary, both the lists and strings used for ouptut capture have
2974 the following special attributes:
2982 the following special attributes:
2975
2983
2976 .l (or .list) : value as list.
2984 .l (or .list) : value as list.
2977 .n (or .nlstr): value as newline-separated string.
2985 .n (or .nlstr): value as newline-separated string.
2978 .s (or .spstr): value as space-separated string.
2986 .s (or .spstr): value as space-separated string.
2979 """
2987 """
2980
2988
2981 opts,args = self.parse_options(parameter_s,'lv')
2989 opts,args = self.parse_options(parameter_s,'lv')
2982 # Try to get a variable name and command to run
2990 # Try to get a variable name and command to run
2983 try:
2991 try:
2984 # the variable name must be obtained from the parse_options
2992 # the variable name must be obtained from the parse_options
2985 # output, which uses shlex.split to strip options out.
2993 # output, which uses shlex.split to strip options out.
2986 var,_ = args.split('=',1)
2994 var,_ = args.split('=',1)
2987 var = var.strip()
2995 var = var.strip()
2988 # But the the command has to be extracted from the original input
2996 # But the the command has to be extracted from the original input
2989 # parameter_s, not on what parse_options returns, to avoid the
2997 # parameter_s, not on what parse_options returns, to avoid the
2990 # quote stripping which shlex.split performs on it.
2998 # quote stripping which shlex.split performs on it.
2991 _,cmd = parameter_s.split('=',1)
2999 _,cmd = parameter_s.split('=',1)
2992 except ValueError:
3000 except ValueError:
2993 var,cmd = '',''
3001 var,cmd = '',''
2994 # If all looks ok, proceed
3002 # If all looks ok, proceed
2995 out,err = self.shell.getoutputerror(cmd)
3003 out,err = self.shell.getoutputerror(cmd)
2996 if err:
3004 if err:
2997 print >> Term.cerr,err
3005 print >> Term.cerr,err
2998 if opts.has_key('l'):
3006 if opts.has_key('l'):
2999 out = SList(out.split('\n'))
3007 out = SList(out.split('\n'))
3000 else:
3008 else:
3001 out = LSString(out)
3009 out = LSString(out)
3002 if opts.has_key('v'):
3010 if opts.has_key('v'):
3003 print '%s ==\n%s' % (var,pformat(out))
3011 print '%s ==\n%s' % (var,pformat(out))
3004 if var:
3012 if var:
3005 self.shell.user_ns.update({var:out})
3013 self.shell.user_ns.update({var:out})
3006 else:
3014 else:
3007 return out
3015 return out
3008
3016
3009 def magic_sx(self, parameter_s=''):
3017 def magic_sx(self, parameter_s=''):
3010 """Shell execute - run a shell command and capture its output.
3018 """Shell execute - run a shell command and capture its output.
3011
3019
3012 %sx command
3020 %sx command
3013
3021
3014 IPython will run the given command using commands.getoutput(), and
3022 IPython will run the given command using commands.getoutput(), and
3015 return the result formatted as a list (split on '\\n'). Since the
3023 return the result formatted as a list (split on '\\n'). Since the
3016 output is _returned_, it will be stored in ipython's regular output
3024 output is _returned_, it will be stored in ipython's regular output
3017 cache Out[N] and in the '_N' automatic variables.
3025 cache Out[N] and in the '_N' automatic variables.
3018
3026
3019 Notes:
3027 Notes:
3020
3028
3021 1) If an input line begins with '!!', then %sx is automatically
3029 1) If an input line begins with '!!', then %sx is automatically
3022 invoked. That is, while:
3030 invoked. That is, while:
3023 !ls
3031 !ls
3024 causes ipython to simply issue system('ls'), typing
3032 causes ipython to simply issue system('ls'), typing
3025 !!ls
3033 !!ls
3026 is a shorthand equivalent to:
3034 is a shorthand equivalent to:
3027 %sx ls
3035 %sx ls
3028
3036
3029 2) %sx differs from %sc in that %sx automatically splits into a list,
3037 2) %sx differs from %sc in that %sx automatically splits into a list,
3030 like '%sc -l'. The reason for this is to make it as easy as possible
3038 like '%sc -l'. The reason for this is to make it as easy as possible
3031 to process line-oriented shell output via further python commands.
3039 to process line-oriented shell output via further python commands.
3032 %sc is meant to provide much finer control, but requires more
3040 %sc is meant to provide much finer control, but requires more
3033 typing.
3041 typing.
3034
3042
3035 3) Just like %sc -l, this is a list with special attributes:
3043 3) Just like %sc -l, this is a list with special attributes:
3036
3044
3037 .l (or .list) : value as list.
3045 .l (or .list) : value as list.
3038 .n (or .nlstr): value as newline-separated string.
3046 .n (or .nlstr): value as newline-separated string.
3039 .s (or .spstr): value as whitespace-separated string.
3047 .s (or .spstr): value as whitespace-separated string.
3040
3048
3041 This is very useful when trying to use such lists as arguments to
3049 This is very useful when trying to use such lists as arguments to
3042 system commands."""
3050 system commands."""
3043
3051
3044 if parameter_s:
3052 if parameter_s:
3045 out,err = self.shell.getoutputerror(parameter_s)
3053 out,err = self.shell.getoutputerror(parameter_s)
3046 if err:
3054 if err:
3047 print >> Term.cerr,err
3055 print >> Term.cerr,err
3048 return SList(out.split('\n'))
3056 return SList(out.split('\n'))
3049
3057
3050 def magic_bg(self, parameter_s=''):
3058 def magic_bg(self, parameter_s=''):
3051 """Run a job in the background, in a separate thread.
3059 """Run a job in the background, in a separate thread.
3052
3060
3053 For example,
3061 For example,
3054
3062
3055 %bg myfunc(x,y,z=1)
3063 %bg myfunc(x,y,z=1)
3056
3064
3057 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3065 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3058 execution starts, a message will be printed indicating the job
3066 execution starts, a message will be printed indicating the job
3059 number. If your job number is 5, you can use
3067 number. If your job number is 5, you can use
3060
3068
3061 myvar = jobs.result(5) or myvar = jobs[5].result
3069 myvar = jobs.result(5) or myvar = jobs[5].result
3062
3070
3063 to assign this result to variable 'myvar'.
3071 to assign this result to variable 'myvar'.
3064
3072
3065 IPython has a job manager, accessible via the 'jobs' object. You can
3073 IPython has a job manager, accessible via the 'jobs' object. You can
3066 type jobs? to get more information about it, and use jobs.<TAB> to see
3074 type jobs? to get more information about it, and use jobs.<TAB> to see
3067 its attributes. All attributes not starting with an underscore are
3075 its attributes. All attributes not starting with an underscore are
3068 meant for public use.
3076 meant for public use.
3069
3077
3070 In particular, look at the jobs.new() method, which is used to create
3078 In particular, look at the jobs.new() method, which is used to create
3071 new jobs. This magic %bg function is just a convenience wrapper
3079 new jobs. This magic %bg function is just a convenience wrapper
3072 around jobs.new(), for expression-based jobs. If you want to create a
3080 around jobs.new(), for expression-based jobs. If you want to create a
3073 new job with an explicit function object and arguments, you must call
3081 new job with an explicit function object and arguments, you must call
3074 jobs.new() directly.
3082 jobs.new() directly.
3075
3083
3076 The jobs.new docstring also describes in detail several important
3084 The jobs.new docstring also describes in detail several important
3077 caveats associated with a thread-based model for background job
3085 caveats associated with a thread-based model for background job
3078 execution. Type jobs.new? for details.
3086 execution. Type jobs.new? for details.
3079
3087
3080 You can check the status of all jobs with jobs.status().
3088 You can check the status of all jobs with jobs.status().
3081
3089
3082 The jobs variable is set by IPython into the Python builtin namespace.
3090 The jobs variable is set by IPython into the Python builtin namespace.
3083 If you ever declare a variable named 'jobs', you will shadow this
3091 If you ever declare a variable named 'jobs', you will shadow this
3084 name. You can either delete your global jobs variable to regain
3092 name. You can either delete your global jobs variable to regain
3085 access to the job manager, or make a new name and assign it manually
3093 access to the job manager, or make a new name and assign it manually
3086 to the manager (stored in IPython's namespace). For example, to
3094 to the manager (stored in IPython's namespace). For example, to
3087 assign the job manager to the Jobs name, use:
3095 assign the job manager to the Jobs name, use:
3088
3096
3089 Jobs = __builtins__.jobs"""
3097 Jobs = __builtins__.jobs"""
3090
3098
3091 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3099 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3092
3100
3093 def magic_r(self, parameter_s=''):
3101 def magic_r(self, parameter_s=''):
3094 """Repeat previous input.
3102 """Repeat previous input.
3095
3103
3096 Note: Consider using the more powerfull %rep instead!
3104 Note: Consider using the more powerfull %rep instead!
3097
3105
3098 If given an argument, repeats the previous command which starts with
3106 If given an argument, repeats the previous command which starts with
3099 the same string, otherwise it just repeats the previous input.
3107 the same string, otherwise it just repeats the previous input.
3100
3108
3101 Shell escaped commands (with ! as first character) are not recognized
3109 Shell escaped commands (with ! as first character) are not recognized
3102 by this system, only pure python code and magic commands.
3110 by this system, only pure python code and magic commands.
3103 """
3111 """
3104
3112
3105 start = parameter_s.strip()
3113 start = parameter_s.strip()
3106 esc_magic = self.shell.ESC_MAGIC
3114 esc_magic = self.shell.ESC_MAGIC
3107 # Identify magic commands even if automagic is on (which means
3115 # Identify magic commands even if automagic is on (which means
3108 # the in-memory version is different from that typed by the user).
3116 # the in-memory version is different from that typed by the user).
3109 if self.shell.rc.automagic:
3117 if self.shell.rc.automagic:
3110 start_magic = esc_magic+start
3118 start_magic = esc_magic+start
3111 else:
3119 else:
3112 start_magic = start
3120 start_magic = start
3113 # Look through the input history in reverse
3121 # Look through the input history in reverse
3114 for n in range(len(self.shell.input_hist)-2,0,-1):
3122 for n in range(len(self.shell.input_hist)-2,0,-1):
3115 input = self.shell.input_hist[n]
3123 input = self.shell.input_hist[n]
3116 # skip plain 'r' lines so we don't recurse to infinity
3124 # skip plain 'r' lines so we don't recurse to infinity
3117 if input != '_ip.magic("r")\n' and \
3125 if input != '_ip.magic("r")\n' and \
3118 (input.startswith(start) or input.startswith(start_magic)):
3126 (input.startswith(start) or input.startswith(start_magic)):
3119 #print 'match',`input` # dbg
3127 #print 'match',`input` # dbg
3120 print 'Executing:',input,
3128 print 'Executing:',input,
3121 self.shell.runlines(input)
3129 self.shell.runlines(input)
3122 return
3130 return
3123 print 'No previous input matching `%s` found.' % start
3131 print 'No previous input matching `%s` found.' % start
3124
3132
3125
3133
3126 def magic_bookmark(self, parameter_s=''):
3134 def magic_bookmark(self, parameter_s=''):
3127 """Manage IPython's bookmark system.
3135 """Manage IPython's bookmark system.
3128
3136
3129 %bookmark <name> - set bookmark to current dir
3137 %bookmark <name> - set bookmark to current dir
3130 %bookmark <name> <dir> - set bookmark to <dir>
3138 %bookmark <name> <dir> - set bookmark to <dir>
3131 %bookmark -l - list all bookmarks
3139 %bookmark -l - list all bookmarks
3132 %bookmark -d <name> - remove bookmark
3140 %bookmark -d <name> - remove bookmark
3133 %bookmark -r - remove all bookmarks
3141 %bookmark -r - remove all bookmarks
3134
3142
3135 You can later on access a bookmarked folder with:
3143 You can later on access a bookmarked folder with:
3136 %cd -b <name>
3144 %cd -b <name>
3137 or simply '%cd <name>' if there is no directory called <name> AND
3145 or simply '%cd <name>' if there is no directory called <name> AND
3138 there is such a bookmark defined.
3146 there is such a bookmark defined.
3139
3147
3140 Your bookmarks persist through IPython sessions, but they are
3148 Your bookmarks persist through IPython sessions, but they are
3141 associated with each profile."""
3149 associated with each profile."""
3142
3150
3143 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3151 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3144 if len(args) > 2:
3152 if len(args) > 2:
3145 raise UsageError("%bookmark: too many arguments")
3153 raise UsageError("%bookmark: too many arguments")
3146
3154
3147 bkms = self.db.get('bookmarks',{})
3155 bkms = self.db.get('bookmarks',{})
3148
3156
3149 if opts.has_key('d'):
3157 if opts.has_key('d'):
3150 try:
3158 try:
3151 todel = args[0]
3159 todel = args[0]
3152 except IndexError:
3160 except IndexError:
3153 raise UsageError(
3161 raise UsageError(
3154 "%bookmark -d: must provide a bookmark to delete")
3162 "%bookmark -d: must provide a bookmark to delete")
3155 else:
3163 else:
3156 try:
3164 try:
3157 del bkms[todel]
3165 del bkms[todel]
3158 except KeyError:
3166 except KeyError:
3159 raise UsageError(
3167 raise UsageError(
3160 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3168 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3161
3169
3162 elif opts.has_key('r'):
3170 elif opts.has_key('r'):
3163 bkms = {}
3171 bkms = {}
3164 elif opts.has_key('l'):
3172 elif opts.has_key('l'):
3165 bks = bkms.keys()
3173 bks = bkms.keys()
3166 bks.sort()
3174 bks.sort()
3167 if bks:
3175 if bks:
3168 size = max(map(len,bks))
3176 size = max(map(len,bks))
3169 else:
3177 else:
3170 size = 0
3178 size = 0
3171 fmt = '%-'+str(size)+'s -> %s'
3179 fmt = '%-'+str(size)+'s -> %s'
3172 print 'Current bookmarks:'
3180 print 'Current bookmarks:'
3173 for bk in bks:
3181 for bk in bks:
3174 print fmt % (bk,bkms[bk])
3182 print fmt % (bk,bkms[bk])
3175 else:
3183 else:
3176 if not args:
3184 if not args:
3177 raise UsageError("%bookmark: You must specify the bookmark name")
3185 raise UsageError("%bookmark: You must specify the bookmark name")
3178 elif len(args)==1:
3186 elif len(args)==1:
3179 bkms[args[0]] = os.getcwd()
3187 bkms[args[0]] = os.getcwd()
3180 elif len(args)==2:
3188 elif len(args)==2:
3181 bkms[args[0]] = args[1]
3189 bkms[args[0]] = args[1]
3182 self.db['bookmarks'] = bkms
3190 self.db['bookmarks'] = bkms
3183
3191
3184 def magic_pycat(self, parameter_s=''):
3192 def magic_pycat(self, parameter_s=''):
3185 """Show a syntax-highlighted file through a pager.
3193 """Show a syntax-highlighted file through a pager.
3186
3194
3187 This magic is similar to the cat utility, but it will assume the file
3195 This magic is similar to the cat utility, but it will assume the file
3188 to be Python source and will show it with syntax highlighting. """
3196 to be Python source and will show it with syntax highlighting. """
3189
3197
3190 try:
3198 try:
3191 filename = get_py_filename(parameter_s)
3199 filename = get_py_filename(parameter_s)
3192 cont = file_read(filename)
3200 cont = file_read(filename)
3193 except IOError:
3201 except IOError:
3194 try:
3202 try:
3195 cont = eval(parameter_s,self.user_ns)
3203 cont = eval(parameter_s,self.user_ns)
3196 except NameError:
3204 except NameError:
3197 cont = None
3205 cont = None
3198 if cont is None:
3206 if cont is None:
3199 print "Error: no such file or variable"
3207 print "Error: no such file or variable"
3200 return
3208 return
3201
3209
3202 page(self.shell.pycolorize(cont),
3210 page(self.shell.pycolorize(cont),
3203 screen_lines=self.shell.rc.screen_length)
3211 screen_lines=self.shell.rc.screen_length)
3204
3212
3205 def magic_cpaste(self, parameter_s=''):
3213 def magic_cpaste(self, parameter_s=''):
3206 """Allows you to paste & execute a pre-formatted code block from clipboard.
3214 """Allows you to paste & execute a pre-formatted code block from clipboard.
3207
3215
3208 You must terminate the block with '--' (two minus-signs) alone on the
3216 You must terminate the block with '--' (two minus-signs) alone on the
3209 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3217 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3210 is the new sentinel for this operation)
3218 is the new sentinel for this operation)
3211
3219
3212 The block is dedented prior to execution to enable execution of method
3220 The block is dedented prior to execution to enable execution of method
3213 definitions. '>' and '+' characters at the beginning of a line are
3221 definitions. '>' and '+' characters at the beginning of a line are
3214 ignored, to allow pasting directly from e-mails, diff files and
3222 ignored, to allow pasting directly from e-mails, diff files and
3215 doctests (the '...' continuation prompt is also stripped). The
3223 doctests (the '...' continuation prompt is also stripped). The
3216 executed block is also assigned to variable named 'pasted_block' for
3224 executed block is also assigned to variable named 'pasted_block' for
3217 later editing with '%edit pasted_block'.
3225 later editing with '%edit pasted_block'.
3218
3226
3219 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3227 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3220 This assigns the pasted block to variable 'foo' as string, without
3228 This assigns the pasted block to variable 'foo' as string, without
3221 dedenting or executing it (preceding >>> and + is still stripped)
3229 dedenting or executing it (preceding >>> and + is still stripped)
3222
3230
3223 '%cpaste -r' re-executes the block previously entered by cpaste.
3231 '%cpaste -r' re-executes the block previously entered by cpaste.
3224
3232
3225 Do not be alarmed by garbled output on Windows (it's a readline bug).
3233 Do not be alarmed by garbled output on Windows (it's a readline bug).
3226 Just press enter and type -- (and press enter again) and the block
3234 Just press enter and type -- (and press enter again) and the block
3227 will be what was just pasted.
3235 will be what was just pasted.
3228
3236
3229 IPython statements (magics, shell escapes) are not supported (yet).
3237 IPython statements (magics, shell escapes) are not supported (yet).
3230 """
3238 """
3231 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3239 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3232 par = args.strip()
3240 par = args.strip()
3233 if opts.has_key('r'):
3241 if opts.has_key('r'):
3234 b = self.user_ns.get('pasted_block', None)
3242 b = self.user_ns.get('pasted_block', None)
3235 if b is None:
3243 if b is None:
3236 raise UsageError('No previous pasted block available')
3244 raise UsageError('No previous pasted block available')
3237 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3245 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3238 exec b in self.user_ns
3246 exec b in self.user_ns
3239 return
3247 return
3240
3248
3241 sentinel = opts.get('s','--')
3249 sentinel = opts.get('s','--')
3242
3250
3243 # Regular expressions that declare text we strip from the input:
3251 # Regular expressions that declare text we strip from the input:
3244 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3252 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3245 r'^\s*(\s?>)+', # Python input prompt
3253 r'^\s*(\s?>)+', # Python input prompt
3246 r'^\s*\.{3,}', # Continuation prompts
3254 r'^\s*\.{3,}', # Continuation prompts
3247 r'^\++',
3255 r'^\++',
3248 ]
3256 ]
3249
3257
3250 strip_from_start = map(re.compile,strip_re)
3258 strip_from_start = map(re.compile,strip_re)
3251
3259
3252 from IPython import iplib
3260 from IPython import iplib
3253 lines = []
3261 lines = []
3254 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3262 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3255 while 1:
3263 while 1:
3256 l = iplib.raw_input_original(':')
3264 l = iplib.raw_input_original(':')
3257 if l ==sentinel:
3265 if l ==sentinel:
3258 break
3266 break
3259
3267
3260 for pat in strip_from_start:
3268 for pat in strip_from_start:
3261 l = pat.sub('',l)
3269 l = pat.sub('',l)
3262 lines.append(l)
3270 lines.append(l)
3263
3271
3264 block = "\n".join(lines) + '\n'
3272 block = "\n".join(lines) + '\n'
3265 #print "block:\n",block
3273 #print "block:\n",block
3266 if not par:
3274 if not par:
3267 b = textwrap.dedent(block)
3275 b = textwrap.dedent(block)
3268 self.user_ns['pasted_block'] = b
3276 self.user_ns['pasted_block'] = b
3269 exec b in self.user_ns
3277 exec b in self.user_ns
3270 else:
3278 else:
3271 self.user_ns[par] = SList(block.splitlines())
3279 self.user_ns[par] = SList(block.splitlines())
3272 print "Block assigned to '%s'" % par
3280 print "Block assigned to '%s'" % par
3273
3281
3274 def magic_quickref(self,arg):
3282 def magic_quickref(self,arg):
3275 """ Show a quick reference sheet """
3283 """ Show a quick reference sheet """
3276 import IPython.usage
3284 import IPython.usage
3277 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3285 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3278
3286
3279 page(qr)
3287 page(qr)
3280
3288
3281 def magic_upgrade(self,arg):
3289 def magic_upgrade(self,arg):
3282 """ Upgrade your IPython installation
3290 """ Upgrade your IPython installation
3283
3291
3284 This will copy the config files that don't yet exist in your
3292 This will copy the config files that don't yet exist in your
3285 ipython dir from the system config dir. Use this after upgrading
3293 ipython dir from the system config dir. Use this after upgrading
3286 IPython if you don't wish to delete your .ipython dir.
3294 IPython if you don't wish to delete your .ipython dir.
3287
3295
3288 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3296 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3289 new users)
3297 new users)
3290
3298
3291 """
3299 """
3292 ip = self.getapi()
3300 ip = self.getapi()
3293 ipinstallation = path(IPython.__file__).dirname()
3301 ipinstallation = path(IPython.__file__).dirname()
3294 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3302 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3295 src_config = ipinstallation / 'UserConfig'
3303 src_config = ipinstallation / 'UserConfig'
3296 userdir = path(ip.options.ipythondir)
3304 userdir = path(ip.options.ipythondir)
3297 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3305 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3298 print ">",cmd
3306 print ">",cmd
3299 shell(cmd)
3307 shell(cmd)
3300 if arg == '-nolegacy':
3308 if arg == '-nolegacy':
3301 legacy = userdir.files('ipythonrc*')
3309 legacy = userdir.files('ipythonrc*')
3302 print "Nuking legacy files:",legacy
3310 print "Nuking legacy files:",legacy
3303
3311
3304 [p.remove() for p in legacy]
3312 [p.remove() for p in legacy]
3305 suffix = (sys.platform == 'win32' and '.ini' or '')
3313 suffix = (sys.platform == 'win32' and '.ini' or '')
3306 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3314 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3307
3315
3308
3316
3309 def magic_doctest_mode(self,parameter_s=''):
3317 def magic_doctest_mode(self,parameter_s=''):
3310 """Toggle doctest mode on and off.
3318 """Toggle doctest mode on and off.
3311
3319
3312 This mode allows you to toggle the prompt behavior between normal
3320 This mode allows you to toggle the prompt behavior between normal
3313 IPython prompts and ones that are as similar to the default IPython
3321 IPython prompts and ones that are as similar to the default IPython
3314 interpreter as possible.
3322 interpreter as possible.
3315
3323
3316 It also supports the pasting of code snippets that have leading '>>>'
3324 It also supports the pasting of code snippets that have leading '>>>'
3317 and '...' prompts in them. This means that you can paste doctests from
3325 and '...' prompts in them. This means that you can paste doctests from
3318 files or docstrings (even if they have leading whitespace), and the
3326 files or docstrings (even if they have leading whitespace), and the
3319 code will execute correctly. You can then use '%history -tn' to see
3327 code will execute correctly. You can then use '%history -tn' to see
3320 the translated history without line numbers; this will give you the
3328 the translated history without line numbers; this will give you the
3321 input after removal of all the leading prompts and whitespace, which
3329 input after removal of all the leading prompts and whitespace, which
3322 can be pasted back into an editor.
3330 can be pasted back into an editor.
3323
3331
3324 With these features, you can switch into this mode easily whenever you
3332 With these features, you can switch into this mode easily whenever you
3325 need to do testing and changes to doctests, without having to leave
3333 need to do testing and changes to doctests, without having to leave
3326 your existing IPython session.
3334 your existing IPython session.
3327 """
3335 """
3328
3336
3329 # XXX - Fix this to have cleaner activate/deactivate calls.
3337 # XXX - Fix this to have cleaner activate/deactivate calls.
3330 from IPython.Extensions import InterpreterPasteInput as ipaste
3338 from IPython.Extensions import InterpreterPasteInput as ipaste
3331 from IPython.ipstruct import Struct
3339 from IPython.ipstruct import Struct
3332
3340
3333 # Shorthands
3341 # Shorthands
3334 shell = self.shell
3342 shell = self.shell
3335 oc = shell.outputcache
3343 oc = shell.outputcache
3336 rc = shell.rc
3344 rc = shell.rc
3337 meta = shell.meta
3345 meta = shell.meta
3338 # dstore is a data store kept in the instance metadata bag to track any
3346 # dstore is a data store kept in the instance metadata bag to track any
3339 # changes we make, so we can undo them later.
3347 # changes we make, so we can undo them later.
3340 dstore = meta.setdefault('doctest_mode',Struct())
3348 dstore = meta.setdefault('doctest_mode',Struct())
3341 save_dstore = dstore.setdefault
3349 save_dstore = dstore.setdefault
3342
3350
3343 # save a few values we'll need to recover later
3351 # save a few values we'll need to recover later
3344 mode = save_dstore('mode',False)
3352 mode = save_dstore('mode',False)
3345 save_dstore('rc_pprint',rc.pprint)
3353 save_dstore('rc_pprint',rc.pprint)
3346 save_dstore('xmode',shell.InteractiveTB.mode)
3354 save_dstore('xmode',shell.InteractiveTB.mode)
3347 save_dstore('rc_separate_out',rc.separate_out)
3355 save_dstore('rc_separate_out',rc.separate_out)
3348 save_dstore('rc_separate_out2',rc.separate_out2)
3356 save_dstore('rc_separate_out2',rc.separate_out2)
3349 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3357 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3350 save_dstore('rc_separate_in',rc.separate_in)
3358 save_dstore('rc_separate_in',rc.separate_in)
3351
3359
3352 if mode == False:
3360 if mode == False:
3353 # turn on
3361 # turn on
3354 ipaste.activate_prefilter()
3362 ipaste.activate_prefilter()
3355
3363
3356 oc.prompt1.p_template = '>>> '
3364 oc.prompt1.p_template = '>>> '
3357 oc.prompt2.p_template = '... '
3365 oc.prompt2.p_template = '... '
3358 oc.prompt_out.p_template = ''
3366 oc.prompt_out.p_template = ''
3359
3367
3360 # Prompt separators like plain python
3368 # Prompt separators like plain python
3361 oc.input_sep = oc.prompt1.sep = ''
3369 oc.input_sep = oc.prompt1.sep = ''
3362 oc.output_sep = ''
3370 oc.output_sep = ''
3363 oc.output_sep2 = ''
3371 oc.output_sep2 = ''
3364
3372
3365 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3373 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3366 oc.prompt_out.pad_left = False
3374 oc.prompt_out.pad_left = False
3367
3375
3368 rc.pprint = False
3376 rc.pprint = False
3369
3377
3370 shell.magic_xmode('Plain')
3378 shell.magic_xmode('Plain')
3371
3379
3372 else:
3380 else:
3373 # turn off
3381 # turn off
3374 ipaste.deactivate_prefilter()
3382 ipaste.deactivate_prefilter()
3375
3383
3376 oc.prompt1.p_template = rc.prompt_in1
3384 oc.prompt1.p_template = rc.prompt_in1
3377 oc.prompt2.p_template = rc.prompt_in2
3385 oc.prompt2.p_template = rc.prompt_in2
3378 oc.prompt_out.p_template = rc.prompt_out
3386 oc.prompt_out.p_template = rc.prompt_out
3379
3387
3380 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3388 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3381
3389
3382 oc.output_sep = dstore.rc_separate_out
3390 oc.output_sep = dstore.rc_separate_out
3383 oc.output_sep2 = dstore.rc_separate_out2
3391 oc.output_sep2 = dstore.rc_separate_out2
3384
3392
3385 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3393 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3386 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3394 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3387
3395
3388 rc.pprint = dstore.rc_pprint
3396 rc.pprint = dstore.rc_pprint
3389
3397
3390 shell.magic_xmode(dstore.xmode)
3398 shell.magic_xmode(dstore.xmode)
3391
3399
3392 # Store new mode and inform
3400 # Store new mode and inform
3393 dstore.mode = bool(1-int(mode))
3401 dstore.mode = bool(1-int(mode))
3394 print 'Doctest mode is:',
3402 print 'Doctest mode is:',
3395 print ['OFF','ON'][dstore.mode]
3403 print ['OFF','ON'][dstore.mode]
3396
3404
3397 # end Magic
3405 # end Magic
@@ -1,1238 +1,1249 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
2 """IPython Shell classes.
3
3
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $"""
7 $Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 # Stdlib imports
21 # Stdlib imports
22 import __builtin__
22 import __builtin__
23 import __main__
23 import __main__
24 import Queue
24 import Queue
25 import inspect
25 import inspect
26 import os
26 import os
27 import sys
27 import sys
28 import thread
28 import thread
29 import threading
29 import threading
30 import time
30 import time
31
31
32 from signal import signal, SIGINT
32 from signal import signal, SIGINT
33
33
34 try:
34 try:
35 import ctypes
35 import ctypes
36 HAS_CTYPES = True
36 HAS_CTYPES = True
37 except ImportError:
37 except ImportError:
38 HAS_CTYPES = False
38 HAS_CTYPES = False
39
39
40 # IPython imports
40 # IPython imports
41 import IPython
41 import IPython
42 from IPython import ultraTB, ipapi
42 from IPython import ultraTB, ipapi
43 from IPython.Magic import Magic
43 from IPython.Magic import Magic
44 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
44 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
45 from IPython.iplib import InteractiveShell
45 from IPython.iplib import InteractiveShell
46 from IPython.ipmaker import make_IPython
46 from IPython.ipmaker import make_IPython
47 from IPython.ipstruct import Struct
47 from IPython.ipstruct import Struct
48 from IPython.testing import decorators as testdec
48 from IPython.testing import decorators as testdec
49
49
50 # Globals
50 # Globals
51 # global flag to pass around information about Ctrl-C without exceptions
51 # global flag to pass around information about Ctrl-C without exceptions
52 KBINT = False
52 KBINT = False
53
53
54 # global flag to turn on/off Tk support.
54 # global flag to turn on/off Tk support.
55 USE_TK = False
55 USE_TK = False
56
56
57 # ID for the main thread, used for cross-thread exceptions
57 # ID for the main thread, used for cross-thread exceptions
58 MAIN_THREAD_ID = thread.get_ident()
58 MAIN_THREAD_ID = thread.get_ident()
59
59
60 # Tag when runcode() is active, for exception handling
60 # Tag when runcode() is active, for exception handling
61 CODE_RUN = None
61 CODE_RUN = None
62
62
63 # Default timeout for waiting for multithreaded shells (in seconds)
63 # Default timeout for waiting for multithreaded shells (in seconds)
64 GUI_TIMEOUT = 10
64 GUI_TIMEOUT = 10
65
65
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67 # This class is trivial now, but I want to have it in to publish a clean
67 # This class is trivial now, but I want to have it in to publish a clean
68 # interface. Later when the internals are reorganized, code that uses this
68 # interface. Later when the internals are reorganized, code that uses this
69 # shouldn't have to change.
69 # shouldn't have to change.
70
70
71 class IPShell:
71 class IPShell:
72 """Create an IPython instance."""
72 """Create an IPython instance."""
73
73
74 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
74 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
75 debug=1,shell_class=InteractiveShell):
75 debug=1,shell_class=InteractiveShell):
76 self.IP = make_IPython(argv,user_ns=user_ns,
76 self.IP = make_IPython(argv,user_ns=user_ns,
77 user_global_ns=user_global_ns,
77 user_global_ns=user_global_ns,
78 debug=debug,shell_class=shell_class)
78 debug=debug,shell_class=shell_class)
79
79
80 def mainloop(self,sys_exit=0,banner=None):
80 def mainloop(self,sys_exit=0,banner=None):
81 self.IP.mainloop(banner)
81 self.IP.mainloop(banner)
82 if sys_exit:
82 if sys_exit:
83 sys.exit()
83 sys.exit()
84
84
85 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
86 def kill_embedded(self,parameter_s=''):
86 def kill_embedded(self,parameter_s=''):
87 """%kill_embedded : deactivate for good the current embedded IPython.
87 """%kill_embedded : deactivate for good the current embedded IPython.
88
88
89 This function (after asking for confirmation) sets an internal flag so that
89 This function (after asking for confirmation) sets an internal flag so that
90 an embedded IPython will never activate again. This is useful to
90 an embedded IPython will never activate again. This is useful to
91 permanently disable a shell that is being called inside a loop: once you've
91 permanently disable a shell that is being called inside a loop: once you've
92 figured out what you needed from it, you may then kill it and the program
92 figured out what you needed from it, you may then kill it and the program
93 will then continue to run without the interactive shell interfering again.
93 will then continue to run without the interactive shell interfering again.
94 """
94 """
95
95
96 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
96 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
97 "(y/n)? [y/N] ",'n')
97 "(y/n)? [y/N] ",'n')
98 if kill:
98 if kill:
99 self.shell.embedded_active = False
99 self.shell.embedded_active = False
100 print "This embedded IPython will not reactivate anymore once you exit."
100 print "This embedded IPython will not reactivate anymore once you exit."
101
101
102 class IPShellEmbed:
102 class IPShellEmbed:
103 """Allow embedding an IPython shell into a running program.
103 """Allow embedding an IPython shell into a running program.
104
104
105 Instances of this class are callable, with the __call__ method being an
105 Instances of this class are callable, with the __call__ method being an
106 alias to the embed() method of an InteractiveShell instance.
106 alias to the embed() method of an InteractiveShell instance.
107
107
108 Usage (see also the example-embed.py file for a running example):
108 Usage (see also the example-embed.py file for a running example):
109
109
110 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
110 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
111
111
112 - argv: list containing valid command-line options for IPython, as they
112 - argv: list containing valid command-line options for IPython, as they
113 would appear in sys.argv[1:].
113 would appear in sys.argv[1:].
114
114
115 For example, the following command-line options:
115 For example, the following command-line options:
116
116
117 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
117 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
118
118
119 would be passed in the argv list as:
119 would be passed in the argv list as:
120
120
121 ['-prompt_in1','Input <\\#>','-colors','LightBG']
121 ['-prompt_in1','Input <\\#>','-colors','LightBG']
122
122
123 - banner: string which gets printed every time the interpreter starts.
123 - banner: string which gets printed every time the interpreter starts.
124
124
125 - exit_msg: string which gets printed every time the interpreter exits.
125 - exit_msg: string which gets printed every time the interpreter exits.
126
126
127 - rc_override: a dict or Struct of configuration options such as those
127 - rc_override: a dict or Struct of configuration options such as those
128 used by IPython. These options are read from your ~/.ipython/ipythonrc
128 used by IPython. These options are read from your ~/.ipython/ipythonrc
129 file when the Shell object is created. Passing an explicit rc_override
129 file when the Shell object is created. Passing an explicit rc_override
130 dict with any options you want allows you to override those values at
130 dict with any options you want allows you to override those values at
131 creation time without having to modify the file. This way you can create
131 creation time without having to modify the file. This way you can create
132 embeddable instances configured in any way you want without editing any
132 embeddable instances configured in any way you want without editing any
133 global files (thus keeping your interactive IPython configuration
133 global files (thus keeping your interactive IPython configuration
134 unchanged).
134 unchanged).
135
135
136 Then the ipshell instance can be called anywhere inside your code:
136 Then the ipshell instance can be called anywhere inside your code:
137
137
138 ipshell(header='') -> Opens up an IPython shell.
138 ipshell(header='') -> Opens up an IPython shell.
139
139
140 - header: string printed by the IPython shell upon startup. This can let
140 - header: string printed by the IPython shell upon startup. This can let
141 you know where in your code you are when dropping into the shell. Note
141 you know where in your code you are when dropping into the shell. Note
142 that 'banner' gets prepended to all calls, so header is used for
142 that 'banner' gets prepended to all calls, so header is used for
143 location-specific information.
143 location-specific information.
144
144
145 For more details, see the __call__ method below.
145 For more details, see the __call__ method below.
146
146
147 When the IPython shell is exited with Ctrl-D, normal program execution
147 When the IPython shell is exited with Ctrl-D, normal program execution
148 resumes.
148 resumes.
149
149
150 This functionality was inspired by a posting on comp.lang.python by cmkl
150 This functionality was inspired by a posting on comp.lang.python by cmkl
151 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
151 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
152 by the IDL stop/continue commands."""
152 by the IDL stop/continue commands."""
153
153
154 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
154 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
155 user_ns=None):
155 user_ns=None):
156 """Note that argv here is a string, NOT a list."""
156 """Note that argv here is a string, NOT a list."""
157 self.set_banner(banner)
157 self.set_banner(banner)
158 self.set_exit_msg(exit_msg)
158 self.set_exit_msg(exit_msg)
159 self.set_dummy_mode(0)
159 self.set_dummy_mode(0)
160
160
161 # sys.displayhook is a global, we need to save the user's original
161 # sys.displayhook is a global, we need to save the user's original
162 # Don't rely on __displayhook__, as the user may have changed that.
162 # Don't rely on __displayhook__, as the user may have changed that.
163 self.sys_displayhook_ori = sys.displayhook
163 self.sys_displayhook_ori = sys.displayhook
164
164
165 # save readline completer status
165 # save readline completer status
166 try:
166 try:
167 #print 'Save completer',sys.ipcompleter # dbg
167 #print 'Save completer',sys.ipcompleter # dbg
168 self.sys_ipcompleter_ori = sys.ipcompleter
168 self.sys_ipcompleter_ori = sys.ipcompleter
169 except:
169 except:
170 pass # not nested with IPython
170 pass # not nested with IPython
171
171
172 self.IP = make_IPython(argv,rc_override=rc_override,
172 self.IP = make_IPython(argv,rc_override=rc_override,
173 embedded=True,
173 embedded=True,
174 user_ns=user_ns)
174 user_ns=user_ns)
175
175
176 ip = ipapi.IPApi(self.IP)
176 ip = ipapi.IPApi(self.IP)
177 ip.expose_magic("kill_embedded",kill_embedded)
177 ip.expose_magic("kill_embedded",kill_embedded)
178
178
179 # copy our own displayhook also
179 # copy our own displayhook also
180 self.sys_displayhook_embed = sys.displayhook
180 self.sys_displayhook_embed = sys.displayhook
181 # and leave the system's display hook clean
181 # and leave the system's display hook clean
182 sys.displayhook = self.sys_displayhook_ori
182 sys.displayhook = self.sys_displayhook_ori
183 # don't use the ipython crash handler so that user exceptions aren't
183 # don't use the ipython crash handler so that user exceptions aren't
184 # trapped
184 # trapped
185 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
185 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
186 mode = self.IP.rc.xmode,
186 mode = self.IP.rc.xmode,
187 call_pdb = self.IP.rc.pdb)
187 call_pdb = self.IP.rc.pdb)
188 self.restore_system_completer()
188 self.restore_system_completer()
189
189
190 def restore_system_completer(self):
190 def restore_system_completer(self):
191 """Restores the readline completer which was in place.
191 """Restores the readline completer which was in place.
192
192
193 This allows embedded IPython within IPython not to disrupt the
193 This allows embedded IPython within IPython not to disrupt the
194 parent's completion.
194 parent's completion.
195 """
195 """
196
196
197 try:
197 try:
198 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
198 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
199 sys.ipcompleter = self.sys_ipcompleter_ori
199 sys.ipcompleter = self.sys_ipcompleter_ori
200 except:
200 except:
201 pass
201 pass
202
202
203 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
203 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
204 """Activate the interactive interpreter.
204 """Activate the interactive interpreter.
205
205
206 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
206 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
207 the interpreter shell with the given local and global namespaces, and
207 the interpreter shell with the given local and global namespaces, and
208 optionally print a header string at startup.
208 optionally print a header string at startup.
209
209
210 The shell can be globally activated/deactivated using the
210 The shell can be globally activated/deactivated using the
211 set/get_dummy_mode methods. This allows you to turn off a shell used
211 set/get_dummy_mode methods. This allows you to turn off a shell used
212 for debugging globally.
212 for debugging globally.
213
213
214 However, *each* time you call the shell you can override the current
214 However, *each* time you call the shell you can override the current
215 state of dummy_mode with the optional keyword parameter 'dummy'. For
215 state of dummy_mode with the optional keyword parameter 'dummy'. For
216 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
216 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
217 can still have a specific call work by making it as IPShell(dummy=0).
217 can still have a specific call work by making it as IPShell(dummy=0).
218
218
219 The optional keyword parameter dummy controls whether the call
219 The optional keyword parameter dummy controls whether the call
220 actually does anything. """
220 actually does anything. """
221
221
222 # If the user has turned it off, go away
222 # If the user has turned it off, go away
223 if not self.IP.embedded_active:
223 if not self.IP.embedded_active:
224 return
224 return
225
225
226 # Normal exits from interactive mode set this flag, so the shell can't
226 # Normal exits from interactive mode set this flag, so the shell can't
227 # re-enter (it checks this variable at the start of interactive mode).
227 # re-enter (it checks this variable at the start of interactive mode).
228 self.IP.exit_now = False
228 self.IP.exit_now = False
229
229
230 # Allow the dummy parameter to override the global __dummy_mode
230 # Allow the dummy parameter to override the global __dummy_mode
231 if dummy or (dummy != 0 and self.__dummy_mode):
231 if dummy or (dummy != 0 and self.__dummy_mode):
232 return
232 return
233
233
234 # Set global subsystems (display,completions) to our values
234 # Set global subsystems (display,completions) to our values
235 sys.displayhook = self.sys_displayhook_embed
235 sys.displayhook = self.sys_displayhook_embed
236 if self.IP.has_readline:
236 if self.IP.has_readline:
237 self.IP.set_completer()
237 self.IP.set_completer()
238
238
239 if self.banner and header:
239 if self.banner and header:
240 format = '%s\n%s\n'
240 format = '%s\n%s\n'
241 else:
241 else:
242 format = '%s%s\n'
242 format = '%s%s\n'
243 banner = format % (self.banner,header)
243 banner = format % (self.banner,header)
244
244
245 # Call the embedding code with a stack depth of 1 so it can skip over
245 # Call the embedding code with a stack depth of 1 so it can skip over
246 # our call and get the original caller's namespaces.
246 # our call and get the original caller's namespaces.
247 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
247 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
248
248
249 if self.exit_msg:
249 if self.exit_msg:
250 print self.exit_msg
250 print self.exit_msg
251
251
252 # Restore global systems (display, completion)
252 # Restore global systems (display, completion)
253 sys.displayhook = self.sys_displayhook_ori
253 sys.displayhook = self.sys_displayhook_ori
254 self.restore_system_completer()
254 self.restore_system_completer()
255
255
256 def set_dummy_mode(self,dummy):
256 def set_dummy_mode(self,dummy):
257 """Sets the embeddable shell's dummy mode parameter.
257 """Sets the embeddable shell's dummy mode parameter.
258
258
259 set_dummy_mode(dummy): dummy = 0 or 1.
259 set_dummy_mode(dummy): dummy = 0 or 1.
260
260
261 This parameter is persistent and makes calls to the embeddable shell
261 This parameter is persistent and makes calls to the embeddable shell
262 silently return without performing any action. This allows you to
262 silently return without performing any action. This allows you to
263 globally activate or deactivate a shell you're using with a single call.
263 globally activate or deactivate a shell you're using with a single call.
264
264
265 If you need to manually"""
265 If you need to manually"""
266
266
267 if dummy not in [0,1,False,True]:
267 if dummy not in [0,1,False,True]:
268 raise ValueError,'dummy parameter must be boolean'
268 raise ValueError,'dummy parameter must be boolean'
269 self.__dummy_mode = dummy
269 self.__dummy_mode = dummy
270
270
271 def get_dummy_mode(self):
271 def get_dummy_mode(self):
272 """Return the current value of the dummy mode parameter.
272 """Return the current value of the dummy mode parameter.
273 """
273 """
274 return self.__dummy_mode
274 return self.__dummy_mode
275
275
276 def set_banner(self,banner):
276 def set_banner(self,banner):
277 """Sets the global banner.
277 """Sets the global banner.
278
278
279 This banner gets prepended to every header printed when the shell
279 This banner gets prepended to every header printed when the shell
280 instance is called."""
280 instance is called."""
281
281
282 self.banner = banner
282 self.banner = banner
283
283
284 def set_exit_msg(self,exit_msg):
284 def set_exit_msg(self,exit_msg):
285 """Sets the global exit_msg.
285 """Sets the global exit_msg.
286
286
287 This exit message gets printed upon exiting every time the embedded
287 This exit message gets printed upon exiting every time the embedded
288 shell is called. It is None by default. """
288 shell is called. It is None by default. """
289
289
290 self.exit_msg = exit_msg
290 self.exit_msg = exit_msg
291
291
292 #-----------------------------------------------------------------------------
292 #-----------------------------------------------------------------------------
293 if HAS_CTYPES:
293 if HAS_CTYPES:
294 # Add async exception support. Trick taken from:
294 # Add async exception support. Trick taken from:
295 # http://sebulba.wikispaces.com/recipe+thread2
295 # http://sebulba.wikispaces.com/recipe+thread2
296 def _async_raise(tid, exctype):
296 def _async_raise(tid, exctype):
297 """raises the exception, performs cleanup if needed"""
297 """raises the exception, performs cleanup if needed"""
298 if not inspect.isclass(exctype):
298 if not inspect.isclass(exctype):
299 raise TypeError("Only types can be raised (not instances)")
299 raise TypeError("Only types can be raised (not instances)")
300 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
300 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
301 ctypes.py_object(exctype))
301 ctypes.py_object(exctype))
302 if res == 0:
302 if res == 0:
303 raise ValueError("invalid thread id")
303 raise ValueError("invalid thread id")
304 elif res != 1:
304 elif res != 1:
305 # """if it returns a number greater than one, you're in trouble,
305 # """if it returns a number greater than one, you're in trouble,
306 # and you should call it again with exc=NULL to revert the effect"""
306 # and you should call it again with exc=NULL to revert the effect"""
307 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
307 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
308 raise SystemError("PyThreadState_SetAsyncExc failed")
308 raise SystemError("PyThreadState_SetAsyncExc failed")
309
309
310 def sigint_handler (signum,stack_frame):
310 def sigint_handler (signum,stack_frame):
311 """Sigint handler for threaded apps.
311 """Sigint handler for threaded apps.
312
312
313 This is a horrible hack to pass information about SIGINT _without_
313 This is a horrible hack to pass information about SIGINT _without_
314 using exceptions, since I haven't been able to properly manage
314 using exceptions, since I haven't been able to properly manage
315 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
315 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
316 done (or at least that's my understanding from a c.l.py thread where
316 done (or at least that's my understanding from a c.l.py thread where
317 this was discussed)."""
317 this was discussed)."""
318
318
319 global KBINT
319 global KBINT
320
320
321 if CODE_RUN:
321 if CODE_RUN:
322 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
322 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
323 else:
323 else:
324 KBINT = True
324 KBINT = True
325 print '\nKeyboardInterrupt - Press <Enter> to continue.',
325 print '\nKeyboardInterrupt - Press <Enter> to continue.',
326 Term.cout.flush()
326 Term.cout.flush()
327
327
328 else:
328 else:
329 def sigint_handler (signum,stack_frame):
329 def sigint_handler (signum,stack_frame):
330 """Sigint handler for threaded apps.
330 """Sigint handler for threaded apps.
331
331
332 This is a horrible hack to pass information about SIGINT _without_
332 This is a horrible hack to pass information about SIGINT _without_
333 using exceptions, since I haven't been able to properly manage
333 using exceptions, since I haven't been able to properly manage
334 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
334 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
335 done (or at least that's my understanding from a c.l.py thread where
335 done (or at least that's my understanding from a c.l.py thread where
336 this was discussed)."""
336 this was discussed)."""
337
337
338 global KBINT
338 global KBINT
339
339
340 print '\nKeyboardInterrupt - Press <Enter> to continue.',
340 print '\nKeyboardInterrupt - Press <Enter> to continue.',
341 Term.cout.flush()
341 Term.cout.flush()
342 # Set global flag so that runsource can know that Ctrl-C was hit
342 # Set global flag so that runsource can know that Ctrl-C was hit
343 KBINT = True
343 KBINT = True
344
344
345
345
346 class MTInteractiveShell(InteractiveShell):
346 class MTInteractiveShell(InteractiveShell):
347 """Simple multi-threaded shell."""
347 """Simple multi-threaded shell."""
348
348
349 # Threading strategy taken from:
349 # Threading strategy taken from:
350 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
350 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
351 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
351 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
352 # from the pygtk mailing list, to avoid lockups with system calls.
352 # from the pygtk mailing list, to avoid lockups with system calls.
353
353
354 # class attribute to indicate whether the class supports threads or not.
354 # class attribute to indicate whether the class supports threads or not.
355 # Subclasses with thread support should override this as needed.
355 # Subclasses with thread support should override this as needed.
356 isthreaded = True
356 isthreaded = True
357
357
358 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
358 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
359 user_ns=None,user_global_ns=None,banner2='',
359 user_ns=None,user_global_ns=None,banner2='',
360 gui_timeout=GUI_TIMEOUT,**kw):
360 gui_timeout=GUI_TIMEOUT,**kw):
361 """Similar to the normal InteractiveShell, but with threading control"""
361 """Similar to the normal InteractiveShell, but with threading control"""
362
362
363 InteractiveShell.__init__(self,name,usage,rc,user_ns,
363 InteractiveShell.__init__(self,name,usage,rc,user_ns,
364 user_global_ns,banner2)
364 user_global_ns,banner2)
365
365
366 # Timeout we wait for GUI thread
366 # Timeout we wait for GUI thread
367 self.gui_timeout = gui_timeout
367 self.gui_timeout = gui_timeout
368
368
369 # A queue to hold the code to be executed.
369 # A queue to hold the code to be executed.
370 self.code_queue = Queue.Queue()
370 self.code_queue = Queue.Queue()
371
371
372 # Stuff to do at closing time
372 # Stuff to do at closing time
373 self._kill = None
373 self._kill = None
374 on_kill = kw.get('on_kill', [])
374 on_kill = kw.get('on_kill', [])
375 # Check that all things to kill are callable:
375 # Check that all things to kill are callable:
376 for t in on_kill:
376 for t in on_kill:
377 if not callable(t):
377 if not callable(t):
378 raise TypeError,'on_kill must be a list of callables'
378 raise TypeError,'on_kill must be a list of callables'
379 self.on_kill = on_kill
379 self.on_kill = on_kill
380 # thread identity of the "worker thread" (that may execute code directly)
380 # thread identity of the "worker thread" (that may execute code directly)
381 self.worker_ident = None
381 self.worker_ident = None
382
382
383 def runsource(self, source, filename="<input>", symbol="single"):
383 def runsource(self, source, filename="<input>", symbol="single"):
384 """Compile and run some source in the interpreter.
384 """Compile and run some source in the interpreter.
385
385
386 Modified version of code.py's runsource(), to handle threading issues.
386 Modified version of code.py's runsource(), to handle threading issues.
387 See the original for full docstring details."""
387 See the original for full docstring details."""
388
388
389 global KBINT
389 global KBINT
390
390
391 # If Ctrl-C was typed, we reset the flag and return right away
391 # If Ctrl-C was typed, we reset the flag and return right away
392 if KBINT:
392 if KBINT:
393 KBINT = False
393 KBINT = False
394 return False
394 return False
395
395
396 if self._kill:
396 if self._kill:
397 # can't queue new code if we are being killed
397 # can't queue new code if we are being killed
398 return True
398 return True
399
399
400 try:
400 try:
401 code = self.compile(source, filename, symbol)
401 code = self.compile(source, filename, symbol)
402 except (OverflowError, SyntaxError, ValueError):
402 except (OverflowError, SyntaxError, ValueError):
403 # Case 1
403 # Case 1
404 self.showsyntaxerror(filename)
404 self.showsyntaxerror(filename)
405 return False
405 return False
406
406
407 if code is None:
407 if code is None:
408 # Case 2
408 # Case 2
409 return True
409 return True
410
410
411 # shortcut - if we are in worker thread, or the worker thread is not
411 # shortcut - if we are in worker thread, or the worker thread is not
412 # running, execute directly (to allow recursion and prevent deadlock if
412 # running, execute directly (to allow recursion and prevent deadlock if
413 # code is run early in IPython construction)
413 # code is run early in IPython construction)
414
414
415 if (self.worker_ident is None
415 if (self.worker_ident is None
416 or self.worker_ident == thread.get_ident() ):
416 or self.worker_ident == thread.get_ident() ):
417 InteractiveShell.runcode(self,code)
417 InteractiveShell.runcode(self,code)
418 return
418 return False
419
419
420 # Case 3
420 # Case 3
421 # Store code in queue, so the execution thread can handle it.
421 # Store code in queue, so the execution thread can handle it.
422
422
423 completed_ev, received_ev = threading.Event(), threading.Event()
423 completed_ev, received_ev = threading.Event(), threading.Event()
424
424
425 self.code_queue.put((code,completed_ev, received_ev))
425 self.code_queue.put((code,completed_ev, received_ev))
426 # first make sure the message was received, with timeout
426 # first make sure the message was received, with timeout
427 received_ev.wait(self.gui_timeout)
427 received_ev.wait(self.gui_timeout)
428 if not received_ev.isSet():
428 if not received_ev.isSet():
429 # the mainloop is dead, start executing code directly
429 # the mainloop is dead, start executing code directly
430 print "Warning: Timeout for mainloop thread exceeded"
430 print "Warning: Timeout for mainloop thread exceeded"
431 print "switching to nonthreaded mode (until mainloop wakes up again)"
431 print "switching to nonthreaded mode (until mainloop wakes up again)"
432 self.worker_ident = None
432 self.worker_ident = None
433 else:
433 else:
434 completed_ev.wait()
434 completed_ev.wait()
435 return False
435 return False
436
436
437 def runcode(self):
437 def runcode(self):
438 """Execute a code object.
438 """Execute a code object.
439
439
440 Multithreaded wrapper around IPython's runcode()."""
440 Multithreaded wrapper around IPython's runcode()."""
441
441
442 global CODE_RUN
442 global CODE_RUN
443
443
444 # we are in worker thread, stash out the id for runsource()
444 # we are in worker thread, stash out the id for runsource()
445 self.worker_ident = thread.get_ident()
445 self.worker_ident = thread.get_ident()
446
446
447 if self._kill:
447 if self._kill:
448 print >>Term.cout, 'Closing threads...',
448 print >>Term.cout, 'Closing threads...',
449 Term.cout.flush()
449 Term.cout.flush()
450 for tokill in self.on_kill:
450 for tokill in self.on_kill:
451 tokill()
451 tokill()
452 print >>Term.cout, 'Done.'
452 print >>Term.cout, 'Done.'
453 # allow kill() to return
453 # allow kill() to return
454 self._kill.set()
454 self._kill.set()
455 return True
455 return True
456
456
457 # Install sigint handler. We do it every time to ensure that if user
457 # Install sigint handler. We do it every time to ensure that if user
458 # code modifies it, we restore our own handling.
458 # code modifies it, we restore our own handling.
459 try:
459 try:
460 signal(SIGINT,sigint_handler)
460 signal(SIGINT,sigint_handler)
461 except SystemError:
461 except SystemError:
462 # This happens under Windows, which seems to have all sorts
462 # This happens under Windows, which seems to have all sorts
463 # of problems with signal handling. Oh well...
463 # of problems with signal handling. Oh well...
464 pass
464 pass
465
465
466 # Flush queue of pending code by calling the run methood of the parent
466 # Flush queue of pending code by calling the run methood of the parent
467 # class with all items which may be in the queue.
467 # class with all items which may be in the queue.
468 code_to_run = None
468 code_to_run = None
469 while 1:
469 while 1:
470 try:
470 try:
471 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
471 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
472 except Queue.Empty:
472 except Queue.Empty:
473 break
473 break
474 received_ev.set()
474 received_ev.set()
475
475
476 # Exceptions need to be raised differently depending on which
476 # Exceptions need to be raised differently depending on which
477 # thread is active. This convoluted try/except is only there to
477 # thread is active. This convoluted try/except is only there to
478 # protect against asynchronous exceptions, to ensure that a KBINT
478 # protect against asynchronous exceptions, to ensure that a KBINT
479 # at the wrong time doesn't deadlock everything. The global
479 # at the wrong time doesn't deadlock everything. The global
480 # CODE_TO_RUN is set to true/false as close as possible to the
480 # CODE_TO_RUN is set to true/false as close as possible to the
481 # runcode() call, so that the KBINT handler is correctly informed.
481 # runcode() call, so that the KBINT handler is correctly informed.
482 try:
482 try:
483 try:
483 try:
484 CODE_RUN = True
484 CODE_RUN = True
485 InteractiveShell.runcode(self,code_to_run)
485 InteractiveShell.runcode(self,code_to_run)
486 except KeyboardInterrupt:
486 except KeyboardInterrupt:
487 print "Keyboard interrupted in mainloop"
487 print "Keyboard interrupted in mainloop"
488 while not self.code_queue.empty():
488 while not self.code_queue.empty():
489 code, ev1,ev2 = self.code_queue.get_nowait()
489 code, ev1,ev2 = self.code_queue.get_nowait()
490 ev1.set()
490 ev1.set()
491 ev2.set()
491 ev2.set()
492 break
492 break
493 finally:
493 finally:
494 CODE_RUN = False
494 CODE_RUN = False
495 # allow runsource() return from wait
495 # allow runsource() return from wait
496 completed_ev.set()
496 completed_ev.set()
497
497
498
498
499 # This MUST return true for gtk threading to work
499 # This MUST return true for gtk threading to work
500 return True
500 return True
501
501
502 def kill(self):
502 def kill(self):
503 """Kill the thread, returning when it has been shut down."""
503 """Kill the thread, returning when it has been shut down."""
504 self._kill = threading.Event()
504 self._kill = threading.Event()
505 self._kill.wait()
505 self._kill.wait()
506
506
507 class MatplotlibShellBase:
507 class MatplotlibShellBase:
508 """Mixin class to provide the necessary modifications to regular IPython
508 """Mixin class to provide the necessary modifications to regular IPython
509 shell classes for matplotlib support.
509 shell classes for matplotlib support.
510
510
511 Given Python's MRO, this should be used as the FIRST class in the
511 Given Python's MRO, this should be used as the FIRST class in the
512 inheritance hierarchy, so that it overrides the relevant methods."""
512 inheritance hierarchy, so that it overrides the relevant methods."""
513
513
514 def _matplotlib_config(self,name,user_ns,user_global_ns=None):
514 def _matplotlib_config(self,name,user_ns,user_global_ns=None):
515 """Return items needed to setup the user's shell with matplotlib"""
515 """Return items needed to setup the user's shell with matplotlib"""
516
516
517 # Initialize matplotlib to interactive mode always
517 # Initialize matplotlib to interactive mode always
518 import matplotlib
518 import matplotlib
519 from matplotlib import backends
519 from matplotlib import backends
520 matplotlib.interactive(True)
520 matplotlib.interactive(True)
521
521
522 def use(arg):
522 def use(arg):
523 """IPython wrapper for matplotlib's backend switcher.
523 """IPython wrapper for matplotlib's backend switcher.
524
524
525 In interactive use, we can not allow switching to a different
525 In interactive use, we can not allow switching to a different
526 interactive backend, since thread conflicts will most likely crash
526 interactive backend, since thread conflicts will most likely crash
527 the python interpreter. This routine does a safety check first,
527 the python interpreter. This routine does a safety check first,
528 and refuses to perform a dangerous switch. It still allows
528 and refuses to perform a dangerous switch. It still allows
529 switching to non-interactive backends."""
529 switching to non-interactive backends."""
530
530
531 if arg in backends.interactive_bk and arg != self.mpl_backend:
531 if arg in backends.interactive_bk and arg != self.mpl_backend:
532 m=('invalid matplotlib backend switch.\n'
532 m=('invalid matplotlib backend switch.\n'
533 'This script attempted to switch to the interactive '
533 'This script attempted to switch to the interactive '
534 'backend: `%s`\n'
534 'backend: `%s`\n'
535 'Your current choice of interactive backend is: `%s`\n\n'
535 'Your current choice of interactive backend is: `%s`\n\n'
536 'Switching interactive matplotlib backends at runtime\n'
536 'Switching interactive matplotlib backends at runtime\n'
537 'would crash the python interpreter, '
537 'would crash the python interpreter, '
538 'and IPython has blocked it.\n\n'
538 'and IPython has blocked it.\n\n'
539 'You need to either change your choice of matplotlib backend\n'
539 'You need to either change your choice of matplotlib backend\n'
540 'by editing your .matplotlibrc file, or run this script as a \n'
540 'by editing your .matplotlibrc file, or run this script as a \n'
541 'standalone file from the command line, not using IPython.\n' %
541 'standalone file from the command line, not using IPython.\n' %
542 (arg,self.mpl_backend) )
542 (arg,self.mpl_backend) )
543 raise RuntimeError, m
543 raise RuntimeError, m
544 else:
544 else:
545 self.mpl_use(arg)
545 self.mpl_use(arg)
546 self.mpl_use._called = True
546 self.mpl_use._called = True
547
547
548 self.matplotlib = matplotlib
548 self.matplotlib = matplotlib
549 self.mpl_backend = matplotlib.rcParams['backend']
549 self.mpl_backend = matplotlib.rcParams['backend']
550
550
551 # we also need to block switching of interactive backends by use()
551 # we also need to block switching of interactive backends by use()
552 self.mpl_use = matplotlib.use
552 self.mpl_use = matplotlib.use
553 self.mpl_use._called = False
553 self.mpl_use._called = False
554 # overwrite the original matplotlib.use with our wrapper
554 # overwrite the original matplotlib.use with our wrapper
555 matplotlib.use = use
555 matplotlib.use = use
556
556
557 # This must be imported last in the matplotlib series, after
557 # This must be imported last in the matplotlib series, after
558 # backend/interactivity choices have been made
558 # backend/interactivity choices have been made
559 import matplotlib.pylab as pylab
559 import matplotlib.pylab as pylab
560 self.pylab = pylab
560 self.pylab = pylab
561
561
562 self.pylab.show._needmain = False
562 self.pylab.show._needmain = False
563 # We need to detect at runtime whether show() is called by the user.
563 # We need to detect at runtime whether show() is called by the user.
564 # For this, we wrap it into a decorator which adds a 'called' flag.
564 # For this, we wrap it into a decorator which adds a 'called' flag.
565 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
565 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
566
566
567 # Build a user namespace initialized with matplotlib/matlab features.
567 # Build a user namespace initialized with matplotlib/matlab features.
568 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
568 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
569 user_global_ns)
569 user_global_ns)
570
570
571 # Import numpy as np/pyplot as plt are conventions we're trying to
571 # Import numpy as np/pyplot as plt are conventions we're trying to
572 # somewhat standardize on. Making them available to users by default
572 # somewhat standardize on. Making them available to users by default
573 # will greatly help this.
573 # will greatly help this.
574 exec ("import numpy\n"
574 exec ("import numpy\n"
575 "import numpy as np\n"
575 "import numpy as np\n"
576 "import matplotlib\n"
576 "import matplotlib\n"
577 "import matplotlib.pylab as pylab\n"
577 "import matplotlib.pylab as pylab\n"
578 "try:\n"
578 "try:\n"
579 " import matplotlib.pyplot as plt\n"
579 " import matplotlib.pyplot as plt\n"
580 "except ImportError:\n"
580 "except ImportError:\n"
581 " pass\n"
581 " pass\n"
582 ) in user_ns
582 ) in user_ns
583
583
584 # Build matplotlib info banner
584 # Build matplotlib info banner
585 b="""
585 b="""
586 Welcome to pylab, a matplotlib-based Python environment.
586 Welcome to pylab, a matplotlib-based Python environment.
587 For more information, type 'help(pylab)'.
587 For more information, type 'help(pylab)'.
588 """
588 """
589 return user_ns,user_global_ns,b
589 return user_ns,user_global_ns,b
590
590
591 def mplot_exec(self,fname,*where,**kw):
591 def mplot_exec(self,fname,*where,**kw):
592 """Execute a matplotlib script.
592 """Execute a matplotlib script.
593
593
594 This is a call to execfile(), but wrapped in safeties to properly
594 This is a call to execfile(), but wrapped in safeties to properly
595 handle interactive rendering and backend switching."""
595 handle interactive rendering and backend switching."""
596
596
597 #print '*** Matplotlib runner ***' # dbg
597 #print '*** Matplotlib runner ***' # dbg
598 # turn off rendering until end of script
598 # turn off rendering until end of script
599 isInteractive = self.matplotlib.rcParams['interactive']
599 isInteractive = self.matplotlib.rcParams['interactive']
600 self.matplotlib.interactive(False)
600 self.matplotlib.interactive(False)
601 self.safe_execfile(fname,*where,**kw)
601 self.safe_execfile(fname,*where,**kw)
602 self.matplotlib.interactive(isInteractive)
602 self.matplotlib.interactive(isInteractive)
603 # make rendering call now, if the user tried to do it
603 # make rendering call now, if the user tried to do it
604 if self.pylab.draw_if_interactive.called:
604 if self.pylab.draw_if_interactive.called:
605 self.pylab.draw()
605 self.pylab.draw()
606 self.pylab.draw_if_interactive.called = False
606 self.pylab.draw_if_interactive.called = False
607
607
608 # if a backend switch was performed, reverse it now
608 # if a backend switch was performed, reverse it now
609 if self.mpl_use._called:
609 if self.mpl_use._called:
610 self.matplotlib.rcParams['backend'] = self.mpl_backend
610 self.matplotlib.rcParams['backend'] = self.mpl_backend
611
611
612 @testdec.skip_doctest
612 @testdec.skip_doctest
613 def magic_run(self,parameter_s=''):
613 def magic_run(self,parameter_s=''):
614 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
614 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
615
615
616 # Fix the docstring so users see the original as well
616 # Fix the docstring so users see the original as well
617 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
617 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
618 "\n *** Modified %run for Matplotlib,"
618 "\n *** Modified %run for Matplotlib,"
619 " with proper interactive handling ***")
619 " with proper interactive handling ***")
620
620
621 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
621 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
622 # and multithreaded. Note that these are meant for internal use, the IPShell*
622 # and multithreaded. Note that these are meant for internal use, the IPShell*
623 # classes below are the ones meant for public consumption.
623 # classes below are the ones meant for public consumption.
624
624
625 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
625 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
626 """Single-threaded shell with matplotlib support."""
626 """Single-threaded shell with matplotlib support."""
627
627
628 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
628 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
629 user_ns=None,user_global_ns=None,**kw):
629 user_ns=None,user_global_ns=None,**kw):
630 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
630 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
631 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
631 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
632 banner2=b2,**kw)
632 banner2=b2,**kw)
633
633
634 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
634 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
635 """Multi-threaded shell with matplotlib support."""
635 """Multi-threaded shell with matplotlib support."""
636
636
637 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
637 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
638 user_ns=None,user_global_ns=None, **kw):
638 user_ns=None,user_global_ns=None, **kw):
639 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
639 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
640 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
640 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
641 banner2=b2,**kw)
641 banner2=b2,**kw)
642
642
643 #-----------------------------------------------------------------------------
643 #-----------------------------------------------------------------------------
644 # Utility functions for the different GUI enabled IPShell* classes.
644 # Utility functions for the different GUI enabled IPShell* classes.
645
645
646 def get_tk():
646 def get_tk():
647 """Tries to import Tkinter and returns a withdrawn Tkinter root
647 """Tries to import Tkinter and returns a withdrawn Tkinter root
648 window. If Tkinter is already imported or not available, this
648 window. If Tkinter is already imported or not available, this
649 returns None. This function calls `hijack_tk` underneath.
649 returns None. This function calls `hijack_tk` underneath.
650 """
650 """
651 if not USE_TK or sys.modules.has_key('Tkinter'):
651 if not USE_TK or sys.modules.has_key('Tkinter'):
652 return None
652 return None
653 else:
653 else:
654 try:
654 try:
655 import Tkinter
655 import Tkinter
656 except ImportError:
656 except ImportError:
657 return None
657 return None
658 else:
658 else:
659 hijack_tk()
659 hijack_tk()
660 r = Tkinter.Tk()
660 r = Tkinter.Tk()
661 r.withdraw()
661 r.withdraw()
662 return r
662 return r
663
663
664 def hijack_tk():
664 def hijack_tk():
665 """Modifies Tkinter's mainloop with a dummy so when a module calls
665 """Modifies Tkinter's mainloop with a dummy so when a module calls
666 mainloop, it does not block.
666 mainloop, it does not block.
667
667
668 """
668 """
669 def misc_mainloop(self, n=0):
669 def misc_mainloop(self, n=0):
670 pass
670 pass
671 def tkinter_mainloop(n=0):
671 def tkinter_mainloop(n=0):
672 pass
672 pass
673
673
674 import Tkinter
674 import Tkinter
675 Tkinter.Misc.mainloop = misc_mainloop
675 Tkinter.Misc.mainloop = misc_mainloop
676 Tkinter.mainloop = tkinter_mainloop
676 Tkinter.mainloop = tkinter_mainloop
677
677
678 def update_tk(tk):
678 def update_tk(tk):
679 """Updates the Tkinter event loop. This is typically called from
679 """Updates the Tkinter event loop. This is typically called from
680 the respective WX or GTK mainloops.
680 the respective WX or GTK mainloops.
681 """
681 """
682 if tk:
682 if tk:
683 tk.update()
683 tk.update()
684
684
685 def hijack_wx():
685 def hijack_wx():
686 """Modifies wxPython's MainLoop with a dummy so user code does not
686 """Modifies wxPython's MainLoop with a dummy so user code does not
687 block IPython. The hijacked mainloop function is returned.
687 block IPython. The hijacked mainloop function is returned.
688 """
688 """
689 def dummy_mainloop(*args, **kw):
689 def dummy_mainloop(*args, **kw):
690 pass
690 pass
691
691
692 try:
692 try:
693 import wx
693 import wx
694 except ImportError:
694 except ImportError:
695 # For very old versions of WX
695 # For very old versions of WX
696 import wxPython as wx
696 import wxPython as wx
697
697
698 ver = wx.__version__
698 ver = wx.__version__
699 orig_mainloop = None
699 orig_mainloop = None
700 if ver[:3] >= '2.5':
700 if ver[:3] >= '2.5':
701 import wx
701 import wx
702 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
702 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
703 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
703 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
704 else: raise AttributeError('Could not find wx core module')
704 else: raise AttributeError('Could not find wx core module')
705 orig_mainloop = core.PyApp_MainLoop
705 orig_mainloop = core.PyApp_MainLoop
706 core.PyApp_MainLoop = dummy_mainloop
706 core.PyApp_MainLoop = dummy_mainloop
707 elif ver[:3] == '2.4':
707 elif ver[:3] == '2.4':
708 orig_mainloop = wx.wxc.wxPyApp_MainLoop
708 orig_mainloop = wx.wxc.wxPyApp_MainLoop
709 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
709 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
710 else:
710 else:
711 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
711 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
712 return orig_mainloop
712 return orig_mainloop
713
713
714 def hijack_gtk():
714 def hijack_gtk():
715 """Modifies pyGTK's mainloop with a dummy so user code does not
715 """Modifies pyGTK's mainloop with a dummy so user code does not
716 block IPython. This function returns the original `gtk.mainloop`
716 block IPython. This function returns the original `gtk.mainloop`
717 function that has been hijacked.
717 function that has been hijacked.
718 """
718 """
719 def dummy_mainloop(*args, **kw):
719 def dummy_mainloop(*args, **kw):
720 pass
720 pass
721 import gtk
721 import gtk
722 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
722 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
723 else: orig_mainloop = gtk.mainloop
723 else: orig_mainloop = gtk.mainloop
724 gtk.mainloop = dummy_mainloop
724 gtk.mainloop = dummy_mainloop
725 gtk.main = dummy_mainloop
725 gtk.main = dummy_mainloop
726 return orig_mainloop
726 return orig_mainloop
727
727
728 def hijack_qt():
728 def hijack_qt():
729 """Modifies PyQt's mainloop with a dummy so user code does not
729 """Modifies PyQt's mainloop with a dummy so user code does not
730 block IPython. This function returns the original
730 block IPython. This function returns the original
731 `qt.qApp.exec_loop` function that has been hijacked.
731 `qt.qApp.exec_loop` function that has been hijacked.
732 """
732 """
733 def dummy_mainloop(*args, **kw):
733 def dummy_mainloop(*args, **kw):
734 pass
734 pass
735 import qt
735 import qt
736 orig_mainloop = qt.qApp.exec_loop
736 orig_mainloop = qt.qApp.exec_loop
737 qt.qApp.exec_loop = dummy_mainloop
737 qt.qApp.exec_loop = dummy_mainloop
738 qt.QApplication.exec_loop = dummy_mainloop
738 qt.QApplication.exec_loop = dummy_mainloop
739 return orig_mainloop
739 return orig_mainloop
740
740
741 def hijack_qt4():
741 def hijack_qt4():
742 """Modifies PyQt4's mainloop with a dummy so user code does not
742 """Modifies PyQt4's mainloop with a dummy so user code does not
743 block IPython. This function returns the original
743 block IPython. This function returns the original
744 `QtGui.qApp.exec_` function that has been hijacked.
744 `QtGui.qApp.exec_` function that has been hijacked.
745 """
745 """
746 def dummy_mainloop(*args, **kw):
746 def dummy_mainloop(*args, **kw):
747 pass
747 pass
748 from PyQt4 import QtGui, QtCore
748 from PyQt4 import QtGui, QtCore
749 orig_mainloop = QtGui.qApp.exec_
749 orig_mainloop = QtGui.qApp.exec_
750 QtGui.qApp.exec_ = dummy_mainloop
750 QtGui.qApp.exec_ = dummy_mainloop
751 QtGui.QApplication.exec_ = dummy_mainloop
751 QtGui.QApplication.exec_ = dummy_mainloop
752 QtCore.QCoreApplication.exec_ = dummy_mainloop
752 QtCore.QCoreApplication.exec_ = dummy_mainloop
753 return orig_mainloop
753 return orig_mainloop
754
754
755 #-----------------------------------------------------------------------------
755 #-----------------------------------------------------------------------------
756 # The IPShell* classes below are the ones meant to be run by external code as
756 # The IPShell* classes below are the ones meant to be run by external code as
757 # IPython instances. Note that unless a specific threading strategy is
757 # IPython instances. Note that unless a specific threading strategy is
758 # desired, the factory function start() below should be used instead (it
758 # desired, the factory function start() below should be used instead (it
759 # selects the proper threaded class).
759 # selects the proper threaded class).
760
760
761 class IPThread(threading.Thread):
761 class IPThread(threading.Thread):
762 def run(self):
762 def run(self):
763 self.IP.mainloop(self._banner)
763 self.IP.mainloop(self._banner)
764 self.IP.kill()
764 self.IP.kill()
765
765
766 class IPShellGTK(IPThread):
766 class IPShellGTK(IPThread):
767 """Run a gtk mainloop() in a separate thread.
767 """Run a gtk mainloop() in a separate thread.
768
768
769 Python commands can be passed to the thread where they will be executed.
769 Python commands can be passed to the thread where they will be executed.
770 This is implemented by periodically checking for passed code using a
770 This is implemented by periodically checking for passed code using a
771 GTK timeout callback."""
771 GTK timeout callback."""
772
772
773 TIMEOUT = 100 # Millisecond interval between timeouts.
773 TIMEOUT = 100 # Millisecond interval between timeouts.
774
774
775 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
775 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
776 debug=1,shell_class=MTInteractiveShell):
776 debug=1,shell_class=MTInteractiveShell):
777
777
778 import gtk
778 import gtk
779 # Check for set_interactive, coming up in new pygtk.
780 # Disable it so that this code works, but notify
781 # the user that he has a better option as well.
782 # XXX TODO better support when set_interactive is released
783 try:
784 gtk.set_interactive(False)
785 print "Your PyGtk has set_interactive(), so you can use the"
786 print "more stable single-threaded Gtk mode."
787 print "See https://bugs.launchpad.net/ipython/+bug/270856"
788 except AttributeError:
789 pass
779
790
780 self.gtk = gtk
791 self.gtk = gtk
781 self.gtk_mainloop = hijack_gtk()
792 self.gtk_mainloop = hijack_gtk()
782
793
783 # Allows us to use both Tk and GTK.
794 # Allows us to use both Tk and GTK.
784 self.tk = get_tk()
795 self.tk = get_tk()
785
796
786 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
797 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
787 else: mainquit = self.gtk.mainquit
798 else: mainquit = self.gtk.mainquit
788
799
789 self.IP = make_IPython(argv,user_ns=user_ns,
800 self.IP = make_IPython(argv,user_ns=user_ns,
790 user_global_ns=user_global_ns,
801 user_global_ns=user_global_ns,
791 debug=debug,
802 debug=debug,
792 shell_class=shell_class,
803 shell_class=shell_class,
793 on_kill=[mainquit])
804 on_kill=[mainquit])
794
805
795 # HACK: slot for banner in self; it will be passed to the mainloop
806 # HACK: slot for banner in self; it will be passed to the mainloop
796 # method only and .run() needs it. The actual value will be set by
807 # method only and .run() needs it. The actual value will be set by
797 # .mainloop().
808 # .mainloop().
798 self._banner = None
809 self._banner = None
799
810
800 threading.Thread.__init__(self)
811 threading.Thread.__init__(self)
801
812
802 def mainloop(self,sys_exit=0,banner=None):
813 def mainloop(self,sys_exit=0,banner=None):
803
814
804 self._banner = banner
815 self._banner = banner
805
816
806 if self.gtk.pygtk_version >= (2,4,0):
817 if self.gtk.pygtk_version >= (2,4,0):
807 import gobject
818 import gobject
808 gobject.idle_add(self.on_timer)
819 gobject.idle_add(self.on_timer)
809 else:
820 else:
810 self.gtk.idle_add(self.on_timer)
821 self.gtk.idle_add(self.on_timer)
811
822
812 if sys.platform != 'win32':
823 if sys.platform != 'win32':
813 try:
824 try:
814 if self.gtk.gtk_version[0] >= 2:
825 if self.gtk.gtk_version[0] >= 2:
815 self.gtk.gdk.threads_init()
826 self.gtk.gdk.threads_init()
816 except AttributeError:
827 except AttributeError:
817 pass
828 pass
818 except RuntimeError:
829 except RuntimeError:
819 error('Your pyGTK likely has not been compiled with '
830 error('Your pyGTK likely has not been compiled with '
820 'threading support.\n'
831 'threading support.\n'
821 'The exception printout is below.\n'
832 'The exception printout is below.\n'
822 'You can either rebuild pyGTK with threads, or '
833 'You can either rebuild pyGTK with threads, or '
823 'try using \n'
834 'try using \n'
824 'matplotlib with a different backend (like Tk or WX).\n'
835 'matplotlib with a different backend (like Tk or WX).\n'
825 'Note that matplotlib will most likely not work in its '
836 'Note that matplotlib will most likely not work in its '
826 'current state!')
837 'current state!')
827 self.IP.InteractiveTB()
838 self.IP.InteractiveTB()
828
839
829 self.start()
840 self.start()
830 self.gtk.gdk.threads_enter()
841 self.gtk.gdk.threads_enter()
831 self.gtk_mainloop()
842 self.gtk_mainloop()
832 self.gtk.gdk.threads_leave()
843 self.gtk.gdk.threads_leave()
833 self.join()
844 self.join()
834
845
835 def on_timer(self):
846 def on_timer(self):
836 """Called when GTK is idle.
847 """Called when GTK is idle.
837
848
838 Must return True always, otherwise GTK stops calling it"""
849 Must return True always, otherwise GTK stops calling it"""
839
850
840 update_tk(self.tk)
851 update_tk(self.tk)
841 self.IP.runcode()
852 self.IP.runcode()
842 time.sleep(0.01)
853 time.sleep(0.01)
843 return True
854 return True
844
855
845
856
846 class IPShellWX(IPThread):
857 class IPShellWX(IPThread):
847 """Run a wx mainloop() in a separate thread.
858 """Run a wx mainloop() in a separate thread.
848
859
849 Python commands can be passed to the thread where they will be executed.
860 Python commands can be passed to the thread where they will be executed.
850 This is implemented by periodically checking for passed code using a
861 This is implemented by periodically checking for passed code using a
851 GTK timeout callback."""
862 GTK timeout callback."""
852
863
853 TIMEOUT = 100 # Millisecond interval between timeouts.
864 TIMEOUT = 100 # Millisecond interval between timeouts.
854
865
855 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
866 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
856 debug=1,shell_class=MTInteractiveShell):
867 debug=1,shell_class=MTInteractiveShell):
857
868
858 self.IP = make_IPython(argv,user_ns=user_ns,
869 self.IP = make_IPython(argv,user_ns=user_ns,
859 user_global_ns=user_global_ns,
870 user_global_ns=user_global_ns,
860 debug=debug,
871 debug=debug,
861 shell_class=shell_class,
872 shell_class=shell_class,
862 on_kill=[self.wxexit])
873 on_kill=[self.wxexit])
863
874
864 wantedwxversion=self.IP.rc.wxversion
875 wantedwxversion=self.IP.rc.wxversion
865 if wantedwxversion!="0":
876 if wantedwxversion!="0":
866 try:
877 try:
867 import wxversion
878 import wxversion
868 except ImportError:
879 except ImportError:
869 error('The wxversion module is needed for WX version selection')
880 error('The wxversion module is needed for WX version selection')
870 else:
881 else:
871 try:
882 try:
872 wxversion.select(wantedwxversion)
883 wxversion.select(wantedwxversion)
873 except:
884 except:
874 self.IP.InteractiveTB()
885 self.IP.InteractiveTB()
875 error('Requested wxPython version %s could not be loaded' %
886 error('Requested wxPython version %s could not be loaded' %
876 wantedwxversion)
887 wantedwxversion)
877
888
878 import wx
889 import wx
879
890
880 threading.Thread.__init__(self)
891 threading.Thread.__init__(self)
881 self.wx = wx
892 self.wx = wx
882 self.wx_mainloop = hijack_wx()
893 self.wx_mainloop = hijack_wx()
883
894
884 # Allows us to use both Tk and GTK.
895 # Allows us to use both Tk and GTK.
885 self.tk = get_tk()
896 self.tk = get_tk()
886
897
887 # HACK: slot for banner in self; it will be passed to the mainloop
898 # HACK: slot for banner in self; it will be passed to the mainloop
888 # method only and .run() needs it. The actual value will be set by
899 # method only and .run() needs it. The actual value will be set by
889 # .mainloop().
900 # .mainloop().
890 self._banner = None
901 self._banner = None
891
902
892 self.app = None
903 self.app = None
893
904
894 def wxexit(self, *args):
905 def wxexit(self, *args):
895 if self.app is not None:
906 if self.app is not None:
896 self.app.agent.timer.Stop()
907 self.app.agent.timer.Stop()
897 self.app.ExitMainLoop()
908 self.app.ExitMainLoop()
898
909
899 def mainloop(self,sys_exit=0,banner=None):
910 def mainloop(self,sys_exit=0,banner=None):
900
911
901 self._banner = banner
912 self._banner = banner
902
913
903 self.start()
914 self.start()
904
915
905 class TimerAgent(self.wx.MiniFrame):
916 class TimerAgent(self.wx.MiniFrame):
906 wx = self.wx
917 wx = self.wx
907 IP = self.IP
918 IP = self.IP
908 tk = self.tk
919 tk = self.tk
909 def __init__(self, parent, interval):
920 def __init__(self, parent, interval):
910 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
921 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
911 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
922 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
912 size=(100, 100),style=style)
923 size=(100, 100),style=style)
913 self.Show(False)
924 self.Show(False)
914 self.interval = interval
925 self.interval = interval
915 self.timerId = self.wx.NewId()
926 self.timerId = self.wx.NewId()
916
927
917 def StartWork(self):
928 def StartWork(self):
918 self.timer = self.wx.Timer(self, self.timerId)
929 self.timer = self.wx.Timer(self, self.timerId)
919 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
930 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
920 self.timer.Start(self.interval)
931 self.timer.Start(self.interval)
921
932
922 def OnTimer(self, event):
933 def OnTimer(self, event):
923 update_tk(self.tk)
934 update_tk(self.tk)
924 self.IP.runcode()
935 self.IP.runcode()
925
936
926 class App(self.wx.App):
937 class App(self.wx.App):
927 wx = self.wx
938 wx = self.wx
928 TIMEOUT = self.TIMEOUT
939 TIMEOUT = self.TIMEOUT
929 def OnInit(self):
940 def OnInit(self):
930 'Create the main window and insert the custom frame'
941 'Create the main window and insert the custom frame'
931 self.agent = TimerAgent(None, self.TIMEOUT)
942 self.agent = TimerAgent(None, self.TIMEOUT)
932 self.agent.Show(False)
943 self.agent.Show(False)
933 self.agent.StartWork()
944 self.agent.StartWork()
934 return True
945 return True
935
946
936 self.app = App(redirect=False)
947 self.app = App(redirect=False)
937 self.wx_mainloop(self.app)
948 self.wx_mainloop(self.app)
938 self.join()
949 self.join()
939
950
940
951
941 class IPShellQt(IPThread):
952 class IPShellQt(IPThread):
942 """Run a Qt event loop in a separate thread.
953 """Run a Qt event loop in a separate thread.
943
954
944 Python commands can be passed to the thread where they will be executed.
955 Python commands can be passed to the thread where they will be executed.
945 This is implemented by periodically checking for passed code using a
956 This is implemented by periodically checking for passed code using a
946 Qt timer / slot."""
957 Qt timer / slot."""
947
958
948 TIMEOUT = 100 # Millisecond interval between timeouts.
959 TIMEOUT = 100 # Millisecond interval between timeouts.
949
960
950 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
961 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
951 debug=0, shell_class=MTInteractiveShell):
962 debug=0, shell_class=MTInteractiveShell):
952
963
953 import qt
964 import qt
954
965
955 self.exec_loop = hijack_qt()
966 self.exec_loop = hijack_qt()
956
967
957 # Allows us to use both Tk and QT.
968 # Allows us to use both Tk and QT.
958 self.tk = get_tk()
969 self.tk = get_tk()
959
970
960 self.IP = make_IPython(argv,
971 self.IP = make_IPython(argv,
961 user_ns=user_ns,
972 user_ns=user_ns,
962 user_global_ns=user_global_ns,
973 user_global_ns=user_global_ns,
963 debug=debug,
974 debug=debug,
964 shell_class=shell_class,
975 shell_class=shell_class,
965 on_kill=[qt.qApp.exit])
976 on_kill=[qt.qApp.exit])
966
977
967 # HACK: slot for banner in self; it will be passed to the mainloop
978 # HACK: slot for banner in self; it will be passed to the mainloop
968 # method only and .run() needs it. The actual value will be set by
979 # method only and .run() needs it. The actual value will be set by
969 # .mainloop().
980 # .mainloop().
970 self._banner = None
981 self._banner = None
971
982
972 threading.Thread.__init__(self)
983 threading.Thread.__init__(self)
973
984
974 def mainloop(self, sys_exit=0, banner=None):
985 def mainloop(self, sys_exit=0, banner=None):
975
986
976 import qt
987 import qt
977
988
978 self._banner = banner
989 self._banner = banner
979
990
980 if qt.QApplication.startingUp():
991 if qt.QApplication.startingUp():
981 a = qt.QApplication(sys.argv)
992 a = qt.QApplication(sys.argv)
982
993
983 self.timer = qt.QTimer()
994 self.timer = qt.QTimer()
984 qt.QObject.connect(self.timer,
995 qt.QObject.connect(self.timer,
985 qt.SIGNAL('timeout()'),
996 qt.SIGNAL('timeout()'),
986 self.on_timer)
997 self.on_timer)
987
998
988 self.start()
999 self.start()
989 self.timer.start(self.TIMEOUT, True)
1000 self.timer.start(self.TIMEOUT, True)
990 while True:
1001 while True:
991 if self.IP._kill: break
1002 if self.IP._kill: break
992 self.exec_loop()
1003 self.exec_loop()
993 self.join()
1004 self.join()
994
1005
995 def on_timer(self):
1006 def on_timer(self):
996 update_tk(self.tk)
1007 update_tk(self.tk)
997 result = self.IP.runcode()
1008 result = self.IP.runcode()
998 self.timer.start(self.TIMEOUT, True)
1009 self.timer.start(self.TIMEOUT, True)
999 return result
1010 return result
1000
1011
1001
1012
1002 class IPShellQt4(IPThread):
1013 class IPShellQt4(IPThread):
1003 """Run a Qt event loop in a separate thread.
1014 """Run a Qt event loop in a separate thread.
1004
1015
1005 Python commands can be passed to the thread where they will be executed.
1016 Python commands can be passed to the thread where they will be executed.
1006 This is implemented by periodically checking for passed code using a
1017 This is implemented by periodically checking for passed code using a
1007 Qt timer / slot."""
1018 Qt timer / slot."""
1008
1019
1009 TIMEOUT = 100 # Millisecond interval between timeouts.
1020 TIMEOUT = 100 # Millisecond interval between timeouts.
1010
1021
1011 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1022 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1012 debug=0, shell_class=MTInteractiveShell):
1023 debug=0, shell_class=MTInteractiveShell):
1013
1024
1014 from PyQt4 import QtCore, QtGui
1025 from PyQt4 import QtCore, QtGui
1015
1026
1016 try:
1027 try:
1017 # present in PyQt4-4.2.1 or later
1028 # present in PyQt4-4.2.1 or later
1018 QtCore.pyqtRemoveInputHook()
1029 QtCore.pyqtRemoveInputHook()
1019 except AttributeError:
1030 except AttributeError:
1020 pass
1031 pass
1021
1032
1022 if QtCore.PYQT_VERSION_STR == '4.3':
1033 if QtCore.PYQT_VERSION_STR == '4.3':
1023 warn('''PyQt4 version 4.3 detected.
1034 warn('''PyQt4 version 4.3 detected.
1024 If you experience repeated threading warnings, please update PyQt4.
1035 If you experience repeated threading warnings, please update PyQt4.
1025 ''')
1036 ''')
1026
1037
1027 self.exec_ = hijack_qt4()
1038 self.exec_ = hijack_qt4()
1028
1039
1029 # Allows us to use both Tk and QT.
1040 # Allows us to use both Tk and QT.
1030 self.tk = get_tk()
1041 self.tk = get_tk()
1031
1042
1032 self.IP = make_IPython(argv,
1043 self.IP = make_IPython(argv,
1033 user_ns=user_ns,
1044 user_ns=user_ns,
1034 user_global_ns=user_global_ns,
1045 user_global_ns=user_global_ns,
1035 debug=debug,
1046 debug=debug,
1036 shell_class=shell_class,
1047 shell_class=shell_class,
1037 on_kill=[QtGui.qApp.exit])
1048 on_kill=[QtGui.qApp.exit])
1038
1049
1039 # HACK: slot for banner in self; it will be passed to the mainloop
1050 # HACK: slot for banner in self; it will be passed to the mainloop
1040 # method only and .run() needs it. The actual value will be set by
1051 # method only and .run() needs it. The actual value will be set by
1041 # .mainloop().
1052 # .mainloop().
1042 self._banner = None
1053 self._banner = None
1043
1054
1044 threading.Thread.__init__(self)
1055 threading.Thread.__init__(self)
1045
1056
1046 def mainloop(self, sys_exit=0, banner=None):
1057 def mainloop(self, sys_exit=0, banner=None):
1047
1058
1048 from PyQt4 import QtCore, QtGui
1059 from PyQt4 import QtCore, QtGui
1049
1060
1050 self._banner = banner
1061 self._banner = banner
1051
1062
1052 if QtGui.QApplication.startingUp():
1063 if QtGui.QApplication.startingUp():
1053 a = QtGui.QApplication(sys.argv)
1064 a = QtGui.QApplication(sys.argv)
1054
1065
1055 self.timer = QtCore.QTimer()
1066 self.timer = QtCore.QTimer()
1056 QtCore.QObject.connect(self.timer,
1067 QtCore.QObject.connect(self.timer,
1057 QtCore.SIGNAL('timeout()'),
1068 QtCore.SIGNAL('timeout()'),
1058 self.on_timer)
1069 self.on_timer)
1059
1070
1060 self.start()
1071 self.start()
1061 self.timer.start(self.TIMEOUT)
1072 self.timer.start(self.TIMEOUT)
1062 while True:
1073 while True:
1063 if self.IP._kill: break
1074 if self.IP._kill: break
1064 self.exec_()
1075 self.exec_()
1065 self.join()
1076 self.join()
1066
1077
1067 def on_timer(self):
1078 def on_timer(self):
1068 update_tk(self.tk)
1079 update_tk(self.tk)
1069 result = self.IP.runcode()
1080 result = self.IP.runcode()
1070 self.timer.start(self.TIMEOUT)
1081 self.timer.start(self.TIMEOUT)
1071 return result
1082 return result
1072
1083
1073
1084
1074 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1085 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1075 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1086 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1076 def _load_pylab(user_ns):
1087 def _load_pylab(user_ns):
1077 """Allow users to disable pulling all of pylab into the top-level
1088 """Allow users to disable pulling all of pylab into the top-level
1078 namespace.
1089 namespace.
1079
1090
1080 This little utility must be called AFTER the actual ipython instance is
1091 This little utility must be called AFTER the actual ipython instance is
1081 running, since only then will the options file have been fully parsed."""
1092 running, since only then will the options file have been fully parsed."""
1082
1093
1083 ip = IPython.ipapi.get()
1094 ip = IPython.ipapi.get()
1084 if ip.options.pylab_import_all:
1095 if ip.options.pylab_import_all:
1085 ip.ex("from matplotlib.pylab import *")
1096 ip.ex("from matplotlib.pylab import *")
1086 ip.IP.user_config_ns.update(ip.user_ns)
1097 ip.IP.user_config_ns.update(ip.user_ns)
1087
1098
1088
1099
1089 class IPShellMatplotlib(IPShell):
1100 class IPShellMatplotlib(IPShell):
1090 """Subclass IPShell with MatplotlibShell as the internal shell.
1101 """Subclass IPShell with MatplotlibShell as the internal shell.
1091
1102
1092 Single-threaded class, meant for the Tk* and FLTK* backends.
1103 Single-threaded class, meant for the Tk* and FLTK* backends.
1093
1104
1094 Having this on a separate class simplifies the external driver code."""
1105 Having this on a separate class simplifies the external driver code."""
1095
1106
1096 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1107 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1097 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1108 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1098 shell_class=MatplotlibShell)
1109 shell_class=MatplotlibShell)
1099 _load_pylab(self.IP.user_ns)
1110 _load_pylab(self.IP.user_ns)
1100
1111
1101 class IPShellMatplotlibGTK(IPShellGTK):
1112 class IPShellMatplotlibGTK(IPShellGTK):
1102 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1113 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1103
1114
1104 Multi-threaded class, meant for the GTK* backends."""
1115 Multi-threaded class, meant for the GTK* backends."""
1105
1116
1106 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1117 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1107 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1118 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1108 shell_class=MatplotlibMTShell)
1119 shell_class=MatplotlibMTShell)
1109 _load_pylab(self.IP.user_ns)
1120 _load_pylab(self.IP.user_ns)
1110
1121
1111 class IPShellMatplotlibWX(IPShellWX):
1122 class IPShellMatplotlibWX(IPShellWX):
1112 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1123 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1113
1124
1114 Multi-threaded class, meant for the WX* backends."""
1125 Multi-threaded class, meant for the WX* backends."""
1115
1126
1116 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1127 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1117 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1128 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1118 shell_class=MatplotlibMTShell)
1129 shell_class=MatplotlibMTShell)
1119 _load_pylab(self.IP.user_ns)
1130 _load_pylab(self.IP.user_ns)
1120
1131
1121 class IPShellMatplotlibQt(IPShellQt):
1132 class IPShellMatplotlibQt(IPShellQt):
1122 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1133 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1123
1134
1124 Multi-threaded class, meant for the Qt* backends."""
1135 Multi-threaded class, meant for the Qt* backends."""
1125
1136
1126 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1137 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1127 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1138 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1128 shell_class=MatplotlibMTShell)
1139 shell_class=MatplotlibMTShell)
1129 _load_pylab(self.IP.user_ns)
1140 _load_pylab(self.IP.user_ns)
1130
1141
1131 class IPShellMatplotlibQt4(IPShellQt4):
1142 class IPShellMatplotlibQt4(IPShellQt4):
1132 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1143 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1133
1144
1134 Multi-threaded class, meant for the Qt4* backends."""
1145 Multi-threaded class, meant for the Qt4* backends."""
1135
1146
1136 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1147 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1137 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1148 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1138 shell_class=MatplotlibMTShell)
1149 shell_class=MatplotlibMTShell)
1139 _load_pylab(self.IP.user_ns)
1150 _load_pylab(self.IP.user_ns)
1140
1151
1141 #-----------------------------------------------------------------------------
1152 #-----------------------------------------------------------------------------
1142 # Factory functions to actually start the proper thread-aware shell
1153 # Factory functions to actually start the proper thread-aware shell
1143
1154
1144 def _select_shell(argv):
1155 def _select_shell(argv):
1145 """Select a shell from the given argv vector.
1156 """Select a shell from the given argv vector.
1146
1157
1147 This function implements the threading selection policy, allowing runtime
1158 This function implements the threading selection policy, allowing runtime
1148 control of the threading mode, both for general users and for matplotlib.
1159 control of the threading mode, both for general users and for matplotlib.
1149
1160
1150 Return:
1161 Return:
1151 Shell class to be instantiated for runtime operation.
1162 Shell class to be instantiated for runtime operation.
1152 """
1163 """
1153
1164
1154 global USE_TK
1165 global USE_TK
1155
1166
1156 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1167 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1157 'wthread' : IPShellMatplotlibWX,
1168 'wthread' : IPShellMatplotlibWX,
1158 'qthread' : IPShellMatplotlibQt,
1169 'qthread' : IPShellMatplotlibQt,
1159 'q4thread' : IPShellMatplotlibQt4,
1170 'q4thread' : IPShellMatplotlibQt4,
1160 'tkthread' : IPShellMatplotlib, # Tk is built-in
1171 'tkthread' : IPShellMatplotlib, # Tk is built-in
1161 }
1172 }
1162
1173
1163 th_shell = {'gthread' : IPShellGTK,
1174 th_shell = {'gthread' : IPShellGTK,
1164 'wthread' : IPShellWX,
1175 'wthread' : IPShellWX,
1165 'qthread' : IPShellQt,
1176 'qthread' : IPShellQt,
1166 'q4thread' : IPShellQt4,
1177 'q4thread' : IPShellQt4,
1167 'tkthread' : IPShell, # Tk is built-in
1178 'tkthread' : IPShell, # Tk is built-in
1168 }
1179 }
1169
1180
1170 backends = {'gthread' : 'GTKAgg',
1181 backends = {'gthread' : 'GTKAgg',
1171 'wthread' : 'WXAgg',
1182 'wthread' : 'WXAgg',
1172 'qthread' : 'QtAgg',
1183 'qthread' : 'QtAgg',
1173 'q4thread' :'Qt4Agg',
1184 'q4thread' :'Qt4Agg',
1174 'tkthread' :'TkAgg',
1185 'tkthread' :'TkAgg',
1175 }
1186 }
1176
1187
1177 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1188 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1178 'tkthread'])
1189 'tkthread'])
1179 user_opts = set([s.replace('-','') for s in argv[:3]])
1190 user_opts = set([s.replace('-','') for s in argv[:3]])
1180 special_opts = user_opts & all_opts
1191 special_opts = user_opts & all_opts
1181
1192
1182 if 'tk' in special_opts:
1193 if 'tk' in special_opts:
1183 USE_TK = True
1194 USE_TK = True
1184 special_opts.remove('tk')
1195 special_opts.remove('tk')
1185
1196
1186 if 'pylab' in special_opts:
1197 if 'pylab' in special_opts:
1187
1198
1188 try:
1199 try:
1189 import matplotlib
1200 import matplotlib
1190 except ImportError:
1201 except ImportError:
1191 error('matplotlib could NOT be imported! Starting normal IPython.')
1202 error('matplotlib could NOT be imported! Starting normal IPython.')
1192 return IPShell
1203 return IPShell
1193
1204
1194 special_opts.remove('pylab')
1205 special_opts.remove('pylab')
1195 # If there's any option left, it means the user wants to force the
1206 # If there's any option left, it means the user wants to force the
1196 # threading backend, else it's auto-selected from the rc file
1207 # threading backend, else it's auto-selected from the rc file
1197 if special_opts:
1208 if special_opts:
1198 th_mode = special_opts.pop()
1209 th_mode = special_opts.pop()
1199 matplotlib.rcParams['backend'] = backends[th_mode]
1210 matplotlib.rcParams['backend'] = backends[th_mode]
1200 else:
1211 else:
1201 backend = matplotlib.rcParams['backend']
1212 backend = matplotlib.rcParams['backend']
1202 if backend.startswith('GTK'):
1213 if backend.startswith('GTK'):
1203 th_mode = 'gthread'
1214 th_mode = 'gthread'
1204 elif backend.startswith('WX'):
1215 elif backend.startswith('WX'):
1205 th_mode = 'wthread'
1216 th_mode = 'wthread'
1206 elif backend.startswith('Qt4'):
1217 elif backend.startswith('Qt4'):
1207 th_mode = 'q4thread'
1218 th_mode = 'q4thread'
1208 elif backend.startswith('Qt'):
1219 elif backend.startswith('Qt'):
1209 th_mode = 'qthread'
1220 th_mode = 'qthread'
1210 else:
1221 else:
1211 # Any other backend, use plain Tk
1222 # Any other backend, use plain Tk
1212 th_mode = 'tkthread'
1223 th_mode = 'tkthread'
1213
1224
1214 return mpl_shell[th_mode]
1225 return mpl_shell[th_mode]
1215 else:
1226 else:
1216 # No pylab requested, just plain threads
1227 # No pylab requested, just plain threads
1217 try:
1228 try:
1218 th_mode = special_opts.pop()
1229 th_mode = special_opts.pop()
1219 except KeyError:
1230 except KeyError:
1220 th_mode = 'tkthread'
1231 th_mode = 'tkthread'
1221 return th_shell[th_mode]
1232 return th_shell[th_mode]
1222
1233
1223
1234
1224 # This is the one which should be called by external code.
1235 # This is the one which should be called by external code.
1225 def start(user_ns = None):
1236 def start(user_ns = None):
1226 """Return a running shell instance, dealing with threading options.
1237 """Return a running shell instance, dealing with threading options.
1227
1238
1228 This is a factory function which will instantiate the proper IPython shell
1239 This is a factory function which will instantiate the proper IPython shell
1229 based on the user's threading choice. Such a selector is needed because
1240 based on the user's threading choice. Such a selector is needed because
1230 different GUI toolkits require different thread handling details."""
1241 different GUI toolkits require different thread handling details."""
1231
1242
1232 shell = _select_shell(sys.argv)
1243 shell = _select_shell(sys.argv)
1233 return shell(user_ns = user_ns)
1244 return shell(user_ns = user_ns)
1234
1245
1235 # Some aliases for backwards compatibility
1246 # Some aliases for backwards compatibility
1236 IPythonShell = IPShell
1247 IPythonShell = IPShell
1237 IPythonShellEmbed = IPShellEmbed
1248 IPythonShellEmbed = IPShellEmbed
1238 #************************ End of file <Shell.py> ***************************
1249 #************************ End of file <Shell.py> ***************************
@@ -1,526 +1,526 b''
1 """Module for interactive demos using IPython.
1 """Module for interactive demos using IPython.
2
2
3 This module implements a few classes for running Python scripts interactively
3 This module implements a few classes for running Python scripts interactively
4 in IPython for demonstrations. With very simple markup (a few tags in
4 in IPython for demonstrations. With very simple markup (a few tags in
5 comments), you can control points where the script stops executing and returns
5 comments), you can control points where the script stops executing and returns
6 control to IPython.
6 control to IPython.
7
7
8
8
9 Provided classes
9 Provided classes
10 ================
10 ================
11
11
12 The classes are (see their docstrings for further details):
12 The classes are (see their docstrings for further details):
13
13
14 - Demo: pure python demos
14 - Demo: pure python demos
15
15
16 - IPythonDemo: demos with input to be processed by IPython as if it had been
16 - IPythonDemo: demos with input to be processed by IPython as if it had been
17 typed interactively (so magics work, as well as any other special syntax you
17 typed interactively (so magics work, as well as any other special syntax you
18 may have added via input prefilters).
18 may have added via input prefilters).
19
19
20 - LineDemo: single-line version of the Demo class. These demos are executed
20 - LineDemo: single-line version of the Demo class. These demos are executed
21 one line at a time, and require no markup.
21 one line at a time, and require no markup.
22
22
23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
24 executed a line at a time, but processed via IPython).
24 executed a line at a time, but processed via IPython).
25
25
26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
27 declares an empty marquee and a pre_cmd that clears the screen before each
27 declares an empty marquee and a pre_cmd that clears the screen before each
28 block (see Subclassing below).
28 block (see Subclassing below).
29
29
30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
31 classes.
31 classes.
32
32
33
33
34 Subclassing
34 Subclassing
35 ===========
35 ===========
36
36
37 The classes here all include a few methods meant to make customization by
37 The classes here all include a few methods meant to make customization by
38 subclassing more convenient. Their docstrings below have some more details:
38 subclassing more convenient. Their docstrings below have some more details:
39
39
40 - marquee(): generates a marquee to provide visible on-screen markers at each
40 - marquee(): generates a marquee to provide visible on-screen markers at each
41 block start and end.
41 block start and end.
42
42
43 - pre_cmd(): run right before the execution of each block.
43 - pre_cmd(): run right before the execution of each block.
44
44
45 - post_cmd(): run right after the execution of each block. If the block
45 - post_cmd(): run right after the execution of each block. If the block
46 raises an exception, this is NOT called.
46 raises an exception, this is NOT called.
47
47
48
48
49 Operation
49 Operation
50 =========
50 =========
51
51
52 The file is run in its own empty namespace (though you can pass it a string of
52 The file is run in its own empty namespace (though you can pass it a string of
53 arguments as if in a command line environment, and it will see those as
53 arguments as if in a command line environment, and it will see those as
54 sys.argv). But at each stop, the global IPython namespace is updated with the
54 sys.argv). But at each stop, the global IPython namespace is updated with the
55 current internal demo namespace, so you can work interactively with the data
55 current internal demo namespace, so you can work interactively with the data
56 accumulated so far.
56 accumulated so far.
57
57
58 By default, each block of code is printed (with syntax highlighting) before
58 By default, each block of code is printed (with syntax highlighting) before
59 executing it and you have to confirm execution. This is intended to show the
59 executing it and you have to confirm execution. This is intended to show the
60 code to an audience first so you can discuss it, and only proceed with
60 code to an audience first so you can discuss it, and only proceed with
61 execution once you agree. There are a few tags which allow you to modify this
61 execution once you agree. There are a few tags which allow you to modify this
62 behavior.
62 behavior.
63
63
64 The supported tags are:
64 The supported tags are:
65
65
66 # <demo> stop
66 # <demo> stop
67
67
68 Defines block boundaries, the points where IPython stops execution of the
68 Defines block boundaries, the points where IPython stops execution of the
69 file and returns to the interactive prompt.
69 file and returns to the interactive prompt.
70
70
71 You can optionally mark the stop tag with extra dashes before and after the
71 You can optionally mark the stop tag with extra dashes before and after the
72 word 'stop', to help visually distinguish the blocks in a text editor:
72 word 'stop', to help visually distinguish the blocks in a text editor:
73
73
74 # <demo> --- stop ---
74 # <demo> --- stop ---
75
75
76
76
77 # <demo> silent
77 # <demo> silent
78
78
79 Make a block execute silently (and hence automatically). Typically used in
79 Make a block execute silently (and hence automatically). Typically used in
80 cases where you have some boilerplate or initialization code which you need
80 cases where you have some boilerplate or initialization code which you need
81 executed but do not want to be seen in the demo.
81 executed but do not want to be seen in the demo.
82
82
83 # <demo> auto
83 # <demo> auto
84
84
85 Make a block execute automatically, but still being printed. Useful for
85 Make a block execute automatically, but still being printed. Useful for
86 simple code which does not warrant discussion, since it avoids the extra
86 simple code which does not warrant discussion, since it avoids the extra
87 manual confirmation.
87 manual confirmation.
88
88
89 # <demo> auto_all
89 # <demo> auto_all
90
90
91 This tag can _only_ be in the first block, and if given it overrides the
91 This tag can _only_ be in the first block, and if given it overrides the
92 individual auto tags to make the whole demo fully automatic (no block asks
92 individual auto tags to make the whole demo fully automatic (no block asks
93 for confirmation). It can also be given at creation time (or the attribute
93 for confirmation). It can also be given at creation time (or the attribute
94 set later) to override what's in the file.
94 set later) to override what's in the file.
95
95
96 While _any_ python file can be run as a Demo instance, if there are no stop
96 While _any_ python file can be run as a Demo instance, if there are no stop
97 tags the whole file will run in a single block (no different that calling
97 tags the whole file will run in a single block (no different that calling
98 first %pycat and then %run). The minimal markup to make this useful is to
98 first %pycat and then %run). The minimal markup to make this useful is to
99 place a set of stop tags; the other tags are only there to let you fine-tune
99 place a set of stop tags; the other tags are only there to let you fine-tune
100 the execution.
100 the execution.
101
101
102 This is probably best explained with the simple example file below. You can
102 This is probably best explained with the simple example file below. You can
103 copy this into a file named ex_demo.py, and try running it via:
103 copy this into a file named ex_demo.py, and try running it via:
104
104
105 from IPython.demo import Demo
105 from IPython.demo import Demo
106 d = Demo('ex_demo.py')
106 d = Demo('ex_demo.py')
107 d() <--- Call the d object (omit the parens if you have autocall set to 2).
107 d() <--- Call the d object (omit the parens if you have autocall set to 2).
108
108
109 Each time you call the demo object, it runs the next block. The demo object
109 Each time you call the demo object, it runs the next block. The demo object
110 has a few useful methods for navigation, like again(), edit(), jump(), seek()
110 has a few useful methods for navigation, like again(), edit(), jump(), seek()
111 and back(). It can be reset for a new run via reset() or reloaded from disk
111 and back(). It can be reset for a new run via reset() or reloaded from disk
112 (in case you've edited the source) via reload(). See their docstrings below.
112 (in case you've edited the source) via reload(). See their docstrings below.
113
113
114
114
115 Example
115 Example
116 =======
116 =======
117
117
118 The following is a very simple example of a valid demo file.
118 The following is a very simple example of a valid demo file.
119
119
120 #################### EXAMPLE DEMO <ex_demo.py> ###############################
120 #################### EXAMPLE DEMO <ex_demo.py> ###############################
121 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
121 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
122
122
123 print 'Hello, welcome to an interactive IPython demo.'
123 print 'Hello, welcome to an interactive IPython demo.'
124
124
125 # The mark below defines a block boundary, which is a point where IPython will
125 # The mark below defines a block boundary, which is a point where IPython will
126 # stop execution and return to the interactive prompt. The dashes are actually
126 # stop execution and return to the interactive prompt. The dashes are actually
127 # optional and used only as a visual aid to clearly separate blocks while
127 # optional and used only as a visual aid to clearly separate blocks while
128 editing the demo code.
128 editing the demo code.
129 # <demo> stop
129 # <demo> stop
130
130
131 x = 1
131 x = 1
132 y = 2
132 y = 2
133
133
134 # <demo> stop
134 # <demo> stop
135
135
136 # the mark below makes this block as silent
136 # the mark below makes this block as silent
137 # <demo> silent
137 # <demo> silent
138
138
139 print 'This is a silent block, which gets executed but not printed.'
139 print 'This is a silent block, which gets executed but not printed.'
140
140
141 # <demo> stop
141 # <demo> stop
142 # <demo> auto
142 # <demo> auto
143 print 'This is an automatic block.'
143 print 'This is an automatic block.'
144 print 'It is executed without asking for confirmation, but printed.'
144 print 'It is executed without asking for confirmation, but printed.'
145 z = x+y
145 z = x+y
146
146
147 print 'z=',x
147 print 'z=',x
148
148
149 # <demo> stop
149 # <demo> stop
150 # This is just another normal block.
150 # This is just another normal block.
151 print 'z is now:', z
151 print 'z is now:', z
152
152
153 print 'bye!'
153 print 'bye!'
154 ################### END EXAMPLE DEMO <ex_demo.py> ############################
154 ################### END EXAMPLE DEMO <ex_demo.py> ############################
155 """
155 """
156
156
157 #*****************************************************************************
157 #*****************************************************************************
158 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
158 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
159 #
159 #
160 # Distributed under the terms of the BSD License. The full license is in
160 # Distributed under the terms of the BSD License. The full license is in
161 # the file COPYING, distributed as part of this software.
161 # the file COPYING, distributed as part of this software.
162 #
162 #
163 #*****************************************************************************
163 #*****************************************************************************
164
164
165 import exceptions
165 import exceptions
166 import os
166 import os
167 import re
167 import re
168 import shlex
168 import shlex
169 import sys
169 import sys
170
170
171 from IPython.PyColorize import Parser
171 from IPython.PyColorize import Parser
172 from IPython.genutils import marquee, file_read, file_readlines
172 from IPython.genutils import marquee, file_read, file_readlines
173
173
174 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
174 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
175
175
176 class DemoError(exceptions.Exception): pass
176 class DemoError(exceptions.Exception): pass
177
177
178 def re_mark(mark):
178 def re_mark(mark):
179 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
179 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
180
180
181 class Demo(object):
181 class Demo(object):
182
182
183 re_stop = re_mark('-?\s?stop\s?-?')
183 re_stop = re_mark('-*\s?stop\s?-*')
184 re_silent = re_mark('silent')
184 re_silent = re_mark('silent')
185 re_auto = re_mark('auto')
185 re_auto = re_mark('auto')
186 re_auto_all = re_mark('auto_all')
186 re_auto_all = re_mark('auto_all')
187
187
188 def __init__(self,fname,arg_str='',auto_all=None):
188 def __init__(self,fname,arg_str='',auto_all=None):
189 """Make a new demo object. To run the demo, simply call the object.
189 """Make a new demo object. To run the demo, simply call the object.
190
190
191 See the module docstring for full details and an example (you can use
191 See the module docstring for full details and an example (you can use
192 IPython.Demo? in IPython to see it).
192 IPython.Demo? in IPython to see it).
193
193
194 Inputs:
194 Inputs:
195
195
196 - fname = filename.
196 - fname = filename.
197
197
198 Optional inputs:
198 Optional inputs:
199
199
200 - arg_str(''): a string of arguments, internally converted to a list
200 - arg_str(''): a string of arguments, internally converted to a list
201 just like sys.argv, so the demo script can see a similar
201 just like sys.argv, so the demo script can see a similar
202 environment.
202 environment.
203
203
204 - auto_all(None): global flag to run all blocks automatically without
204 - auto_all(None): global flag to run all blocks automatically without
205 confirmation. This attribute overrides the block-level tags and
205 confirmation. This attribute overrides the block-level tags and
206 applies to the whole demo. It is an attribute of the object, and
206 applies to the whole demo. It is an attribute of the object, and
207 can be changed at runtime simply by reassigning it to a boolean
207 can be changed at runtime simply by reassigning it to a boolean
208 value.
208 value.
209 """
209 """
210
210
211 self.fname = fname
211 self.fname = fname
212 self.sys_argv = [fname] + shlex.split(arg_str)
212 self.sys_argv = [fname] + shlex.split(arg_str)
213 self.auto_all = auto_all
213 self.auto_all = auto_all
214
214
215 # get a few things from ipython. While it's a bit ugly design-wise,
215 # get a few things from ipython. While it's a bit ugly design-wise,
216 # it ensures that things like color scheme and the like are always in
216 # it ensures that things like color scheme and the like are always in
217 # sync with the ipython mode being used. This class is only meant to
217 # sync with the ipython mode being used. This class is only meant to
218 # be used inside ipython anyways, so it's OK.
218 # be used inside ipython anyways, so it's OK.
219 self.ip_ns = __IPYTHON__.user_ns
219 self.ip_ns = __IPYTHON__.user_ns
220 self.ip_colorize = __IPYTHON__.pycolorize
220 self.ip_colorize = __IPYTHON__.pycolorize
221 self.ip_showtb = __IPYTHON__.showtraceback
221 self.ip_showtb = __IPYTHON__.showtraceback
222 self.ip_runlines = __IPYTHON__.runlines
222 self.ip_runlines = __IPYTHON__.runlines
223 self.shell = __IPYTHON__
223 self.shell = __IPYTHON__
224
224
225 # load user data and initialize data structures
225 # load user data and initialize data structures
226 self.reload()
226 self.reload()
227
227
228 def reload(self):
228 def reload(self):
229 """Reload source from disk and initialize state."""
229 """Reload source from disk and initialize state."""
230 # read data and parse into blocks
230 # read data and parse into blocks
231 self.src = file_read(self.fname)
231 self.src = file_read(self.fname)
232 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
232 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
233 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
233 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
234 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
234 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
235
235
236 # if auto_all is not given (def. None), we read it from the file
236 # if auto_all is not given (def. None), we read it from the file
237 if self.auto_all is None:
237 if self.auto_all is None:
238 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
238 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
239 else:
239 else:
240 self.auto_all = bool(self.auto_all)
240 self.auto_all = bool(self.auto_all)
241
241
242 # Clean the sources from all markup so it doesn't get displayed when
242 # Clean the sources from all markup so it doesn't get displayed when
243 # running the demo
243 # running the demo
244 src_blocks = []
244 src_blocks = []
245 auto_strip = lambda s: self.re_auto.sub('',s)
245 auto_strip = lambda s: self.re_auto.sub('',s)
246 for i,b in enumerate(src_b):
246 for i,b in enumerate(src_b):
247 if self._auto[i]:
247 if self._auto[i]:
248 src_blocks.append(auto_strip(b))
248 src_blocks.append(auto_strip(b))
249 else:
249 else:
250 src_blocks.append(b)
250 src_blocks.append(b)
251 # remove the auto_all marker
251 # remove the auto_all marker
252 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
252 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
253
253
254 self.nblocks = len(src_blocks)
254 self.nblocks = len(src_blocks)
255 self.src_blocks = src_blocks
255 self.src_blocks = src_blocks
256
256
257 # also build syntax-highlighted source
257 # also build syntax-highlighted source
258 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
258 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
259
259
260 # ensure clean namespace and seek offset
260 # ensure clean namespace and seek offset
261 self.reset()
261 self.reset()
262
262
263 def reset(self):
263 def reset(self):
264 """Reset the namespace and seek pointer to restart the demo"""
264 """Reset the namespace and seek pointer to restart the demo"""
265 self.user_ns = {}
265 self.user_ns = {}
266 self.finished = False
266 self.finished = False
267 self.block_index = 0
267 self.block_index = 0
268
268
269 def _validate_index(self,index):
269 def _validate_index(self,index):
270 if index<0 or index>=self.nblocks:
270 if index<0 or index>=self.nblocks:
271 raise ValueError('invalid block index %s' % index)
271 raise ValueError('invalid block index %s' % index)
272
272
273 def _get_index(self,index):
273 def _get_index(self,index):
274 """Get the current block index, validating and checking status.
274 """Get the current block index, validating and checking status.
275
275
276 Returns None if the demo is finished"""
276 Returns None if the demo is finished"""
277
277
278 if index is None:
278 if index is None:
279 if self.finished:
279 if self.finished:
280 print 'Demo finished. Use reset() if you want to rerun it.'
280 print 'Demo finished. Use reset() if you want to rerun it.'
281 return None
281 return None
282 index = self.block_index
282 index = self.block_index
283 else:
283 else:
284 self._validate_index(index)
284 self._validate_index(index)
285 return index
285 return index
286
286
287 def seek(self,index):
287 def seek(self,index):
288 """Move the current seek pointer to the given block.
288 """Move the current seek pointer to the given block.
289
289
290 You can use negative indices to seek from the end, with identical
290 You can use negative indices to seek from the end, with identical
291 semantics to those of Python lists."""
291 semantics to those of Python lists."""
292 if index<0:
292 if index<0:
293 index = self.nblocks + index
293 index = self.nblocks + index
294 self._validate_index(index)
294 self._validate_index(index)
295 self.block_index = index
295 self.block_index = index
296 self.finished = False
296 self.finished = False
297
297
298 def back(self,num=1):
298 def back(self,num=1):
299 """Move the seek pointer back num blocks (default is 1)."""
299 """Move the seek pointer back num blocks (default is 1)."""
300 self.seek(self.block_index-num)
300 self.seek(self.block_index-num)
301
301
302 def jump(self,num=1):
302 def jump(self,num=1):
303 """Jump a given number of blocks relative to the current one.
303 """Jump a given number of blocks relative to the current one.
304
304
305 The offset can be positive or negative, defaults to 1."""
305 The offset can be positive or negative, defaults to 1."""
306 self.seek(self.block_index+num)
306 self.seek(self.block_index+num)
307
307
308 def again(self):
308 def again(self):
309 """Move the seek pointer back one block and re-execute."""
309 """Move the seek pointer back one block and re-execute."""
310 self.back(1)
310 self.back(1)
311 self()
311 self()
312
312
313 def edit(self,index=None):
313 def edit(self,index=None):
314 """Edit a block.
314 """Edit a block.
315
315
316 If no number is given, use the last block executed.
316 If no number is given, use the last block executed.
317
317
318 This edits the in-memory copy of the demo, it does NOT modify the
318 This edits the in-memory copy of the demo, it does NOT modify the
319 original source file. If you want to do that, simply open the file in
319 original source file. If you want to do that, simply open the file in
320 an editor and use reload() when you make changes to the file. This
320 an editor and use reload() when you make changes to the file. This
321 method is meant to let you change a block during a demonstration for
321 method is meant to let you change a block during a demonstration for
322 explanatory purposes, without damaging your original script."""
322 explanatory purposes, without damaging your original script."""
323
323
324 index = self._get_index(index)
324 index = self._get_index(index)
325 if index is None:
325 if index is None:
326 return
326 return
327 # decrease the index by one (unless we're at the very beginning), so
327 # decrease the index by one (unless we're at the very beginning), so
328 # that the default demo.edit() call opens up the sblock we've last run
328 # that the default demo.edit() call opens up the sblock we've last run
329 if index>0:
329 if index>0:
330 index -= 1
330 index -= 1
331
331
332 filename = self.shell.mktempfile(self.src_blocks[index])
332 filename = self.shell.mktempfile(self.src_blocks[index])
333 self.shell.hooks.editor(filename,1)
333 self.shell.hooks.editor(filename,1)
334 new_block = file_read(filename)
334 new_block = file_read(filename)
335 # update the source and colored block
335 # update the source and colored block
336 self.src_blocks[index] = new_block
336 self.src_blocks[index] = new_block
337 self.src_blocks_colored[index] = self.ip_colorize(new_block)
337 self.src_blocks_colored[index] = self.ip_colorize(new_block)
338 self.block_index = index
338 self.block_index = index
339 # call to run with the newly edited index
339 # call to run with the newly edited index
340 self()
340 self()
341
341
342 def show(self,index=None):
342 def show(self,index=None):
343 """Show a single block on screen"""
343 """Show a single block on screen"""
344
344
345 index = self._get_index(index)
345 index = self._get_index(index)
346 if index is None:
346 if index is None:
347 return
347 return
348
348
349 print self.marquee('<%s> block # %s (%s remaining)' %
349 print self.marquee('<%s> block # %s (%s remaining)' %
350 (self.fname,index,self.nblocks-index-1))
350 (self.fname,index,self.nblocks-index-1))
351 sys.stdout.write(self.src_blocks_colored[index])
351 sys.stdout.write(self.src_blocks_colored[index])
352 sys.stdout.flush()
352 sys.stdout.flush()
353
353
354 def show_all(self):
354 def show_all(self):
355 """Show entire demo on screen, block by block"""
355 """Show entire demo on screen, block by block"""
356
356
357 fname = self.fname
357 fname = self.fname
358 nblocks = self.nblocks
358 nblocks = self.nblocks
359 silent = self._silent
359 silent = self._silent
360 marquee = self.marquee
360 marquee = self.marquee
361 for index,block in enumerate(self.src_blocks_colored):
361 for index,block in enumerate(self.src_blocks_colored):
362 if silent[index]:
362 if silent[index]:
363 print marquee('<%s> SILENT block # %s (%s remaining)' %
363 print marquee('<%s> SILENT block # %s (%s remaining)' %
364 (fname,index,nblocks-index-1))
364 (fname,index,nblocks-index-1))
365 else:
365 else:
366 print marquee('<%s> block # %s (%s remaining)' %
366 print marquee('<%s> block # %s (%s remaining)' %
367 (fname,index,nblocks-index-1))
367 (fname,index,nblocks-index-1))
368 print block,
368 print block,
369 sys.stdout.flush()
369 sys.stdout.flush()
370
370
371 def runlines(self,source):
371 def runlines(self,source):
372 """Execute a string with one or more lines of code"""
372 """Execute a string with one or more lines of code"""
373
373
374 exec source in self.user_ns
374 exec source in self.user_ns
375
375
376 def __call__(self,index=None):
376 def __call__(self,index=None):
377 """run a block of the demo.
377 """run a block of the demo.
378
378
379 If index is given, it should be an integer >=1 and <= nblocks. This
379 If index is given, it should be an integer >=1 and <= nblocks. This
380 means that the calling convention is one off from typical Python
380 means that the calling convention is one off from typical Python
381 lists. The reason for the inconsistency is that the demo always
381 lists. The reason for the inconsistency is that the demo always
382 prints 'Block n/N, and N is the total, so it would be very odd to use
382 prints 'Block n/N, and N is the total, so it would be very odd to use
383 zero-indexing here."""
383 zero-indexing here."""
384
384
385 index = self._get_index(index)
385 index = self._get_index(index)
386 if index is None:
386 if index is None:
387 return
387 return
388 try:
388 try:
389 marquee = self.marquee
389 marquee = self.marquee
390 next_block = self.src_blocks[index]
390 next_block = self.src_blocks[index]
391 self.block_index += 1
391 self.block_index += 1
392 if self._silent[index]:
392 if self._silent[index]:
393 print marquee('Executing silent block # %s (%s remaining)' %
393 print marquee('Executing silent block # %s (%s remaining)' %
394 (index,self.nblocks-index-1))
394 (index,self.nblocks-index-1))
395 else:
395 else:
396 self.pre_cmd()
396 self.pre_cmd()
397 self.show(index)
397 self.show(index)
398 if self.auto_all or self._auto[index]:
398 if self.auto_all or self._auto[index]:
399 print marquee('output:')
399 print marquee('output:')
400 else:
400 else:
401 print marquee('Press <q> to quit, <Enter> to execute...'),
401 print marquee('Press <q> to quit, <Enter> to execute...'),
402 ans = raw_input().strip()
402 ans = raw_input().strip()
403 if ans:
403 if ans:
404 print marquee('Block NOT executed')
404 print marquee('Block NOT executed')
405 return
405 return
406 try:
406 try:
407 save_argv = sys.argv
407 save_argv = sys.argv
408 sys.argv = self.sys_argv
408 sys.argv = self.sys_argv
409 self.runlines(next_block)
409 self.runlines(next_block)
410 self.post_cmd()
410 self.post_cmd()
411 finally:
411 finally:
412 sys.argv = save_argv
412 sys.argv = save_argv
413
413
414 except:
414 except:
415 self.ip_showtb(filename=self.fname)
415 self.ip_showtb(filename=self.fname)
416 else:
416 else:
417 self.ip_ns.update(self.user_ns)
417 self.ip_ns.update(self.user_ns)
418
418
419 if self.block_index == self.nblocks:
419 if self.block_index == self.nblocks:
420 mq1 = self.marquee('END OF DEMO')
420 mq1 = self.marquee('END OF DEMO')
421 if mq1:
421 if mq1:
422 # avoid spurious prints if empty marquees are used
422 # avoid spurious prints if empty marquees are used
423 print
423 print
424 print mq1
424 print mq1
425 print self.marquee('Use reset() if you want to rerun it.')
425 print self.marquee('Use reset() if you want to rerun it.')
426 self.finished = True
426 self.finished = True
427
427
428 # These methods are meant to be overridden by subclasses who may wish to
428 # These methods are meant to be overridden by subclasses who may wish to
429 # customize the behavior of of their demos.
429 # customize the behavior of of their demos.
430 def marquee(self,txt='',width=78,mark='*'):
430 def marquee(self,txt='',width=78,mark='*'):
431 """Return the input string centered in a 'marquee'."""
431 """Return the input string centered in a 'marquee'."""
432 return marquee(txt,width,mark)
432 return marquee(txt,width,mark)
433
433
434 def pre_cmd(self):
434 def pre_cmd(self):
435 """Method called before executing each block."""
435 """Method called before executing each block."""
436 pass
436 pass
437
437
438 def post_cmd(self):
438 def post_cmd(self):
439 """Method called after executing each block."""
439 """Method called after executing each block."""
440 pass
440 pass
441
441
442
442
443 class IPythonDemo(Demo):
443 class IPythonDemo(Demo):
444 """Class for interactive demos with IPython's input processing applied.
444 """Class for interactive demos with IPython's input processing applied.
445
445
446 This subclasses Demo, but instead of executing each block by the Python
446 This subclasses Demo, but instead of executing each block by the Python
447 interpreter (via exec), it actually calls IPython on it, so that any input
447 interpreter (via exec), it actually calls IPython on it, so that any input
448 filters which may be in place are applied to the input block.
448 filters which may be in place are applied to the input block.
449
449
450 If you have an interactive environment which exposes special input
450 If you have an interactive environment which exposes special input
451 processing, you can use this class instead to write demo scripts which
451 processing, you can use this class instead to write demo scripts which
452 operate exactly as if you had typed them interactively. The default Demo
452 operate exactly as if you had typed them interactively. The default Demo
453 class requires the input to be valid, pure Python code.
453 class requires the input to be valid, pure Python code.
454 """
454 """
455
455
456 def runlines(self,source):
456 def runlines(self,source):
457 """Execute a string with one or more lines of code"""
457 """Execute a string with one or more lines of code"""
458
458
459 self.shell.runlines(source)
459 self.shell.runlines(source)
460
460
461 class LineDemo(Demo):
461 class LineDemo(Demo):
462 """Demo where each line is executed as a separate block.
462 """Demo where each line is executed as a separate block.
463
463
464 The input script should be valid Python code.
464 The input script should be valid Python code.
465
465
466 This class doesn't require any markup at all, and it's meant for simple
466 This class doesn't require any markup at all, and it's meant for simple
467 scripts (with no nesting or any kind of indentation) which consist of
467 scripts (with no nesting or any kind of indentation) which consist of
468 multiple lines of input to be executed, one at a time, as if they had been
468 multiple lines of input to be executed, one at a time, as if they had been
469 typed in the interactive prompt."""
469 typed in the interactive prompt."""
470
470
471 def reload(self):
471 def reload(self):
472 """Reload source from disk and initialize state."""
472 """Reload source from disk and initialize state."""
473 # read data and parse into blocks
473 # read data and parse into blocks
474 src_b = [l for l in file_readlines(self.fname) if l.strip()]
474 src_b = [l for l in file_readlines(self.fname) if l.strip()]
475 nblocks = len(src_b)
475 nblocks = len(src_b)
476 self.src = os.linesep.join(file_readlines(self.fname))
476 self.src = os.linesep.join(file_readlines(self.fname))
477 self._silent = [False]*nblocks
477 self._silent = [False]*nblocks
478 self._auto = [True]*nblocks
478 self._auto = [True]*nblocks
479 self.auto_all = True
479 self.auto_all = True
480 self.nblocks = nblocks
480 self.nblocks = nblocks
481 self.src_blocks = src_b
481 self.src_blocks = src_b
482
482
483 # also build syntax-highlighted source
483 # also build syntax-highlighted source
484 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
484 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
485
485
486 # ensure clean namespace and seek offset
486 # ensure clean namespace and seek offset
487 self.reset()
487 self.reset()
488
488
489
489
490 class IPythonLineDemo(IPythonDemo,LineDemo):
490 class IPythonLineDemo(IPythonDemo,LineDemo):
491 """Variant of the LineDemo class whose input is processed by IPython."""
491 """Variant of the LineDemo class whose input is processed by IPython."""
492 pass
492 pass
493
493
494
494
495 class ClearMixin(object):
495 class ClearMixin(object):
496 """Use this mixin to make Demo classes with less visual clutter.
496 """Use this mixin to make Demo classes with less visual clutter.
497
497
498 Demos using this mixin will clear the screen before every block and use
498 Demos using this mixin will clear the screen before every block and use
499 blank marquees.
499 blank marquees.
500
500
501 Note that in order for the methods defined here to actually override those
501 Note that in order for the methods defined here to actually override those
502 of the classes it's mixed with, it must go /first/ in the inheritance
502 of the classes it's mixed with, it must go /first/ in the inheritance
503 tree. For example:
503 tree. For example:
504
504
505 class ClearIPDemo(ClearMixin,IPythonDemo): pass
505 class ClearIPDemo(ClearMixin,IPythonDemo): pass
506
506
507 will provide an IPythonDemo class with the mixin's features.
507 will provide an IPythonDemo class with the mixin's features.
508 """
508 """
509
509
510 def marquee(self,txt='',width=78,mark='*'):
510 def marquee(self,txt='',width=78,mark='*'):
511 """Blank marquee that returns '' no matter what the input."""
511 """Blank marquee that returns '' no matter what the input."""
512 return ''
512 return ''
513
513
514 def pre_cmd(self):
514 def pre_cmd(self):
515 """Method called before executing each block.
515 """Method called before executing each block.
516
516
517 This one simply clears the screen."""
517 This one simply clears the screen."""
518 os.system('clear')
518 os.system('clear')
519
519
520
520
521 class ClearDemo(ClearMixin,Demo):
521 class ClearDemo(ClearMixin,Demo):
522 pass
522 pass
523
523
524
524
525 class ClearIPDemo(ClearMixin,IPythonDemo):
525 class ClearIPDemo(ClearMixin,IPythonDemo):
526 pass
526 pass
@@ -1,249 +1,252 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 import IPython.ipapi
22 import IPython.ipapi
23 ip = IPython.ipapi.get()
23 ip = IPython.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 os.system('jed +%d %s' % (linenum,filename))
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise ipapi.TryNext()
29
30
30 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
31
32
32 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
33 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
34
35
35 $Id: hooks.py 2998 2008-01-31 10:06:04Z vivainio $"""
36 $Id: hooks.py 2998 2008-01-31 10:06:04Z vivainio $"""
36
37
37 #*****************************************************************************
38 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
40 #
40 # Distributed under the terms of the BSD License. The full license is in
41 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
42 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
43 #*****************************************************************************
43
44
44 from IPython import Release
45 from IPython import Release
45 from IPython import ipapi
46 from IPython import ipapi
46 __author__ = '%s <%s>' % Release.authors['Fernando']
47 __author__ = '%s <%s>' % Release.authors['Fernando']
47 __license__ = Release.license
48 __license__ = Release.license
48 __version__ = Release.version
49 __version__ = Release.version
49
50
50 import os,bisect
51 import os,bisect
51 from genutils import Term,shell
52 from genutils import Term,shell
52 from pprint import PrettyPrinter
53 from pprint import PrettyPrinter
53
54
54 # List here all the default hooks. For now it's just the editor functions
55 # List here all the default hooks. For now it's just the editor functions
55 # but over time we'll move here all the public API for user-accessible things.
56 # but over time we'll move here all the public API for user-accessible things.
56 # vds: >>
57 # vds: >>
57 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
58 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
58 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
59 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
59 'generate_prompt', 'generate_output_prompt','shell_hook',
60 'generate_prompt', 'generate_output_prompt','shell_hook',
60 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook']
61 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook']
61 # vds: <<
62 # vds: <<
62
63
63 pformat = PrettyPrinter().pformat
64 pformat = PrettyPrinter().pformat
64
65
65 def editor(self,filename, linenum=None):
66 def editor(self,filename, linenum=None):
66 """Open the default editor at the given filename and linenumber.
67 """Open the default editor at the given filename and linenumber.
67
68
68 This is IPython's default editor hook, you can use it as an example to
69 This is IPython's default editor hook, you can use it as an example to
69 write your own modified one. To set your own editor function as the
70 write your own modified one. To set your own editor function as the
70 new editor hook, call ip.set_hook('editor',yourfunc)."""
71 new editor hook, call ip.set_hook('editor',yourfunc)."""
71
72
72 # IPython configures a default editor at startup by reading $EDITOR from
73 # IPython configures a default editor at startup by reading $EDITOR from
73 # the environment, and falling back on vi (unix) or notepad (win32).
74 # the environment, and falling back on vi (unix) or notepad (win32).
74 editor = self.rc.editor
75 editor = self.rc.editor
75
76
76 # marker for at which line to open the file (for existing objects)
77 # marker for at which line to open the file (for existing objects)
77 if linenum is None or editor=='notepad':
78 if linenum is None or editor=='notepad':
78 linemark = ''
79 linemark = ''
79 else:
80 else:
80 linemark = '+%d' % int(linenum)
81 linemark = '+%d' % int(linenum)
81
82
82 # Enclose in quotes if necessary and legal
83 # Enclose in quotes if necessary and legal
83 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
84 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
84 editor = '"%s"' % editor
85 editor = '"%s"' % editor
85
86
86 # Call the actual editor
87 # Call the actual editor
87 os.system('%s %s %s' % (editor,linemark,filename))
88 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
89 raise ipapi.TryNext()
88
90
89 import tempfile
91 import tempfile
90 def fix_error_editor(self,filename,linenum,column,msg):
92 def fix_error_editor(self,filename,linenum,column,msg):
91 """Open the editor at the given filename, linenumber, column and
93 """Open the editor at the given filename, linenumber, column and
92 show an error message. This is used for correcting syntax errors.
94 show an error message. This is used for correcting syntax errors.
93 The current implementation only has special support for the VIM editor,
95 The current implementation only has special support for the VIM editor,
94 and falls back on the 'editor' hook if VIM is not used.
96 and falls back on the 'editor' hook if VIM is not used.
95
97
96 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
98 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
97 """
99 """
98 def vim_quickfix_file():
100 def vim_quickfix_file():
99 t = tempfile.NamedTemporaryFile()
101 t = tempfile.NamedTemporaryFile()
100 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
102 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
101 t.flush()
103 t.flush()
102 return t
104 return t
103 if os.path.basename(self.rc.editor) != 'vim':
105 if os.path.basename(self.rc.editor) != 'vim':
104 self.hooks.editor(filename,linenum)
106 self.hooks.editor(filename,linenum)
105 return
107 return
106 t = vim_quickfix_file()
108 t = vim_quickfix_file()
107 try:
109 try:
108 os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name)
110 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
111 raise ipapi.TryNext()
109 finally:
112 finally:
110 t.close()
113 t.close()
111
114
112 # vds: >>
115 # vds: >>
113 def synchronize_with_editor(self, filename, linenum, column):
116 def synchronize_with_editor(self, filename, linenum, column):
114 pass
117 pass
115 # vds: <<
118 # vds: <<
116
119
117 class CommandChainDispatcher:
120 class CommandChainDispatcher:
118 """ Dispatch calls to a chain of commands until some func can handle it
121 """ Dispatch calls to a chain of commands until some func can handle it
119
122
120 Usage: instantiate, execute "add" to add commands (with optional
123 Usage: instantiate, execute "add" to add commands (with optional
121 priority), execute normally via f() calling mechanism.
124 priority), execute normally via f() calling mechanism.
122
125
123 """
126 """
124 def __init__(self,commands=None):
127 def __init__(self,commands=None):
125 if commands is None:
128 if commands is None:
126 self.chain = []
129 self.chain = []
127 else:
130 else:
128 self.chain = commands
131 self.chain = commands
129
132
130
133
131 def __call__(self,*args, **kw):
134 def __call__(self,*args, **kw):
132 """ Command chain is called just like normal func.
135 """ Command chain is called just like normal func.
133
136
134 This will call all funcs in chain with the same args as were given to this
137 This will call all funcs in chain with the same args as were given to this
135 function, and return the result of first func that didn't raise
138 function, and return the result of first func that didn't raise
136 TryNext """
139 TryNext """
137
140
138 for prio,cmd in self.chain:
141 for prio,cmd in self.chain:
139 #print "prio",prio,"cmd",cmd #dbg
142 #print "prio",prio,"cmd",cmd #dbg
140 try:
143 try:
141 ret = cmd(*args, **kw)
144 ret = cmd(*args, **kw)
142 return ret
145 return ret
143 except ipapi.TryNext, exc:
146 except ipapi.TryNext, exc:
144 if exc.args or exc.kwargs:
147 if exc.args or exc.kwargs:
145 args = exc.args
148 args = exc.args
146 kw = exc.kwargs
149 kw = exc.kwargs
147 # if no function will accept it, raise TryNext up to the caller
150 # if no function will accept it, raise TryNext up to the caller
148 raise ipapi.TryNext
151 raise ipapi.TryNext
149
152
150 def __str__(self):
153 def __str__(self):
151 return str(self.chain)
154 return str(self.chain)
152
155
153 def add(self, func, priority=0):
156 def add(self, func, priority=0):
154 """ Add a func to the cmd chain with given priority """
157 """ Add a func to the cmd chain with given priority """
155 bisect.insort(self.chain,(priority,func))
158 bisect.insort(self.chain,(priority,func))
156
159
157 def __iter__(self):
160 def __iter__(self):
158 """ Return all objects in chain.
161 """ Return all objects in chain.
159
162
160 Handy if the objects are not callable.
163 Handy if the objects are not callable.
161 """
164 """
162 return iter(self.chain)
165 return iter(self.chain)
163
166
164 def result_display(self,arg):
167 def result_display(self,arg):
165 """ Default display hook.
168 """ Default display hook.
166
169
167 Called for displaying the result to the user.
170 Called for displaying the result to the user.
168 """
171 """
169
172
170 if self.rc.pprint:
173 if self.rc.pprint:
171 out = pformat(arg)
174 out = pformat(arg)
172 if '\n' in out:
175 if '\n' in out:
173 # So that multi-line strings line up with the left column of
176 # So that multi-line strings line up with the left column of
174 # the screen, instead of having the output prompt mess up
177 # the screen, instead of having the output prompt mess up
175 # their first line.
178 # their first line.
176 Term.cout.write('\n')
179 Term.cout.write('\n')
177 print >>Term.cout, out
180 print >>Term.cout, out
178 else:
181 else:
179 # By default, the interactive prompt uses repr() to display results,
182 # By default, the interactive prompt uses repr() to display results,
180 # so we should honor this. Users who'd rather use a different
183 # so we should honor this. Users who'd rather use a different
181 # mechanism can easily override this hook.
184 # mechanism can easily override this hook.
182 print >>Term.cout, repr(arg)
185 print >>Term.cout, repr(arg)
183 # the default display hook doesn't manipulate the value to put in history
186 # the default display hook doesn't manipulate the value to put in history
184 return None
187 return None
185
188
186 def input_prefilter(self,line):
189 def input_prefilter(self,line):
187 """ Default input prefilter
190 """ Default input prefilter
188
191
189 This returns the line as unchanged, so that the interpreter
192 This returns the line as unchanged, so that the interpreter
190 knows that nothing was done and proceeds with "classic" prefiltering
193 knows that nothing was done and proceeds with "classic" prefiltering
191 (%magics, !shell commands etc.).
194 (%magics, !shell commands etc.).
192
195
193 Note that leading whitespace is not passed to this hook. Prefilter
196 Note that leading whitespace is not passed to this hook. Prefilter
194 can't alter indentation.
197 can't alter indentation.
195
198
196 """
199 """
197 #print "attempt to rewrite",line #dbg
200 #print "attempt to rewrite",line #dbg
198 return line
201 return line
199
202
200 def shutdown_hook(self):
203 def shutdown_hook(self):
201 """ default shutdown hook
204 """ default shutdown hook
202
205
203 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
206 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
204 """
207 """
205
208
206 #print "default shutdown hook ok" # dbg
209 #print "default shutdown hook ok" # dbg
207 return
210 return
208
211
209 def late_startup_hook(self):
212 def late_startup_hook(self):
210 """ Executed after ipython has been constructed and configured
213 """ Executed after ipython has been constructed and configured
211
214
212 """
215 """
213 #print "default startup hook ok" # dbg
216 #print "default startup hook ok" # dbg
214
217
215 def generate_prompt(self, is_continuation):
218 def generate_prompt(self, is_continuation):
216 """ calculate and return a string with the prompt to display """
219 """ calculate and return a string with the prompt to display """
217 ip = self.api
220 ip = self.api
218 if is_continuation:
221 if is_continuation:
219 return str(ip.IP.outputcache.prompt2)
222 return str(ip.IP.outputcache.prompt2)
220 return str(ip.IP.outputcache.prompt1)
223 return str(ip.IP.outputcache.prompt1)
221
224
222 def generate_output_prompt(self):
225 def generate_output_prompt(self):
223 ip = self.api
226 ip = self.api
224 return str(ip.IP.outputcache.prompt_out)
227 return str(ip.IP.outputcache.prompt_out)
225
228
226 def shell_hook(self,cmd):
229 def shell_hook(self,cmd):
227 """ Run system/shell command a'la os.system() """
230 """ Run system/shell command a'la os.system() """
228
231
229 shell(cmd, header=self.rc.system_header, verbose=self.rc.system_verbose)
232 shell(cmd, header=self.rc.system_header, verbose=self.rc.system_verbose)
230
233
231 def show_in_pager(self,s):
234 def show_in_pager(self,s):
232 """ Run a string through pager """
235 """ Run a string through pager """
233 # raising TryNext here will use the default paging functionality
236 # raising TryNext here will use the default paging functionality
234 raise ipapi.TryNext
237 raise ipapi.TryNext
235
238
236 def pre_prompt_hook(self):
239 def pre_prompt_hook(self):
237 """ Run before displaying the next prompt
240 """ Run before displaying the next prompt
238
241
239 Use this e.g. to display output from asynchronous operations (in order
242 Use this e.g. to display output from asynchronous operations (in order
240 to not mess up text entry)
243 to not mess up text entry)
241 """
244 """
242
245
243 return None
246 return None
244
247
245 def pre_runcode_hook(self):
248 def pre_runcode_hook(self):
246 """ Executed before running the (prefiltered) code in IPython """
249 """ Executed before running the (prefiltered) code in IPython """
247 return None
250 return None
248
251
249
252
@@ -1,2686 +1,2695 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.3 or newer.
5 Requires Python 2.3 or newer.
6
6
7 This file contains all the classes and helper functions specific to IPython.
7 This file contains all the classes and helper functions specific to IPython.
8
8
9 """
9 """
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #
17 #
18 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Python standard library. Over time, all of that class has been copied
19 # Python standard library. Over time, all of that class has been copied
20 # verbatim here for modifications which could not be accomplished by
20 # verbatim here for modifications which could not be accomplished by
21 # subclassing. At this point, there are no dependencies at all on the code
21 # subclassing. At this point, there are no dependencies at all on the code
22 # module anymore (it is not even imported). The Python License (sec. 2)
22 # module anymore (it is not even imported). The Python License (sec. 2)
23 # allows for this, but it's always nice to acknowledge credit where credit is
23 # allows for this, but it's always nice to acknowledge credit where credit is
24 # due.
24 # due.
25 #*****************************************************************************
25 #*****************************************************************************
26
26
27 #****************************************************************************
27 #****************************************************************************
28 # Modules and globals
28 # Modules and globals
29
29
30 from IPython import Release
30 from IPython import Release
31 __author__ = '%s <%s>\n%s <%s>' % \
31 __author__ = '%s <%s>\n%s <%s>' % \
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 __license__ = Release.license
33 __license__ = Release.license
34 __version__ = Release.version
34 __version__ = Release.version
35
35
36 # Python standard modules
36 # Python standard modules
37 import __main__
37 import __main__
38 import __builtin__
38 import __builtin__
39 import StringIO
39 import StringIO
40 import bdb
40 import bdb
41 import cPickle as pickle
41 import cPickle as pickle
42 import codeop
42 import codeop
43 import exceptions
43 import exceptions
44 import glob
44 import glob
45 import inspect
45 import inspect
46 import keyword
46 import keyword
47 import new
47 import new
48 import os
48 import os
49 import pydoc
49 import pydoc
50 import re
50 import re
51 import shutil
51 import shutil
52 import string
52 import string
53 import sys
53 import sys
54 import tempfile
54 import tempfile
55 import traceback
55 import traceback
56 import types
56 import types
57 import warnings
57 import warnings
58 warnings.filterwarnings('ignore', r'.*sets module*')
58 warnings.filterwarnings('ignore', r'.*sets module*')
59 from sets import Set
59 from sets import Set
60 from pprint import pprint, pformat
60 from pprint import pprint, pformat
61
61
62 # IPython's own modules
62 # IPython's own modules
63 #import IPython
63 #import IPython
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.Extensions import pickleshare
66 from IPython.Extensions import pickleshare
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 from IPython.strdispatch import StrDispatch
76 from IPython.strdispatch import StrDispatch
77 import IPython.ipapi
77 import IPython.ipapi
78 import IPython.history
78 import IPython.history
79 import IPython.prefilter as prefilter
79 import IPython.prefilter as prefilter
80 import IPython.shadowns
80 import IPython.shadowns
81 # Globals
81 # Globals
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 # compiled regexps for autoindent management
87 # compiled regexps for autoindent management
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89
89
90
90
91 #****************************************************************************
91 #****************************************************************************
92 # Some utility function definitions
92 # Some utility function definitions
93
93
94 ini_spaces_re = re.compile(r'^(\s+)')
94 ini_spaces_re = re.compile(r'^(\s+)')
95
95
96 def num_ini_spaces(strng):
96 def num_ini_spaces(strng):
97 """Return the number of initial spaces in a string"""
97 """Return the number of initial spaces in a string"""
98
98
99 ini_spaces = ini_spaces_re.match(strng)
99 ini_spaces = ini_spaces_re.match(strng)
100 if ini_spaces:
100 if ini_spaces:
101 return ini_spaces.end()
101 return ini_spaces.end()
102 else:
102 else:
103 return 0
103 return 0
104
104
105 def softspace(file, newvalue):
105 def softspace(file, newvalue):
106 """Copied from code.py, to remove the dependency"""
106 """Copied from code.py, to remove the dependency"""
107
107
108 oldvalue = 0
108 oldvalue = 0
109 try:
109 try:
110 oldvalue = file.softspace
110 oldvalue = file.softspace
111 except AttributeError:
111 except AttributeError:
112 pass
112 pass
113 try:
113 try:
114 file.softspace = newvalue
114 file.softspace = newvalue
115 except (AttributeError, TypeError):
115 except (AttributeError, TypeError):
116 # "attribute-less object" or "read-only attributes"
116 # "attribute-less object" or "read-only attributes"
117 pass
117 pass
118 return oldvalue
118 return oldvalue
119
119
120
120
121 #****************************************************************************
121 #****************************************************************************
122 # Local use exceptions
122 # Local use exceptions
123 class SpaceInInput(exceptions.Exception): pass
123 class SpaceInInput(exceptions.Exception): pass
124
124
125
125
126 #****************************************************************************
126 #****************************************************************************
127 # Local use classes
127 # Local use classes
128 class Bunch: pass
128 class Bunch: pass
129
129
130 class Undefined: pass
130 class Undefined: pass
131
131
132 class Quitter(object):
132 class Quitter(object):
133 """Simple class to handle exit, similar to Python 2.5's.
133 """Simple class to handle exit, similar to Python 2.5's.
134
134
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
136 doesn't do (obviously, since it doesn't know about ipython)."""
136 doesn't do (obviously, since it doesn't know about ipython)."""
137
137
138 def __init__(self,shell,name):
138 def __init__(self,shell,name):
139 self.shell = shell
139 self.shell = shell
140 self.name = name
140 self.name = name
141
141
142 def __repr__(self):
142 def __repr__(self):
143 return 'Type %s() to exit.' % self.name
143 return 'Type %s() to exit.' % self.name
144 __str__ = __repr__
144 __str__ = __repr__
145
145
146 def __call__(self):
146 def __call__(self):
147 self.shell.exit()
147 self.shell.exit()
148
148
149 class InputList(list):
149 class InputList(list):
150 """Class to store user input.
150 """Class to store user input.
151
151
152 It's basically a list, but slices return a string instead of a list, thus
152 It's basically a list, but slices return a string instead of a list, thus
153 allowing things like (assuming 'In' is an instance):
153 allowing things like (assuming 'In' is an instance):
154
154
155 exec In[4:7]
155 exec In[4:7]
156
156
157 or
157 or
158
158
159 exec In[5:9] + In[14] + In[21:25]"""
159 exec In[5:9] + In[14] + In[21:25]"""
160
160
161 def __getslice__(self,i,j):
161 def __getslice__(self,i,j):
162 return ''.join(list.__getslice__(self,i,j))
162 return ''.join(list.__getslice__(self,i,j))
163
163
164 class SyntaxTB(ultraTB.ListTB):
164 class SyntaxTB(ultraTB.ListTB):
165 """Extension which holds some state: the last exception value"""
165 """Extension which holds some state: the last exception value"""
166
166
167 def __init__(self,color_scheme = 'NoColor'):
167 def __init__(self,color_scheme = 'NoColor'):
168 ultraTB.ListTB.__init__(self,color_scheme)
168 ultraTB.ListTB.__init__(self,color_scheme)
169 self.last_syntax_error = None
169 self.last_syntax_error = None
170
170
171 def __call__(self, etype, value, elist):
171 def __call__(self, etype, value, elist):
172 self.last_syntax_error = value
172 self.last_syntax_error = value
173 ultraTB.ListTB.__call__(self,etype,value,elist)
173 ultraTB.ListTB.__call__(self,etype,value,elist)
174
174
175 def clear_err_state(self):
175 def clear_err_state(self):
176 """Return the current error state and clear it"""
176 """Return the current error state and clear it"""
177 e = self.last_syntax_error
177 e = self.last_syntax_error
178 self.last_syntax_error = None
178 self.last_syntax_error = None
179 return e
179 return e
180
180
181 #****************************************************************************
181 #****************************************************************************
182 # Main IPython class
182 # Main IPython class
183
183
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
185 # until a full rewrite is made. I've cleaned all cross-class uses of
185 # until a full rewrite is made. I've cleaned all cross-class uses of
186 # attributes and methods, but too much user code out there relies on the
186 # attributes and methods, but too much user code out there relies on the
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
188 #
188 #
189 # But at least now, all the pieces have been separated and we could, in
189 # But at least now, all the pieces have been separated and we could, in
190 # principle, stop using the mixin. This will ease the transition to the
190 # principle, stop using the mixin. This will ease the transition to the
191 # chainsaw branch.
191 # chainsaw branch.
192
192
193 # For reference, the following is the list of 'self.foo' uses in the Magic
193 # For reference, the following is the list of 'self.foo' uses in the Magic
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
195 # class, to prevent clashes.
195 # class, to prevent clashes.
196
196
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
200 # 'self.value']
200 # 'self.value']
201
201
202 class InteractiveShell(object,Magic):
202 class InteractiveShell(object,Magic):
203 """An enhanced console for Python."""
203 """An enhanced console for Python."""
204
204
205 # class attribute to indicate whether the class supports threads or not.
205 # class attribute to indicate whether the class supports threads or not.
206 # Subclasses with thread support should override this as needed.
206 # Subclasses with thread support should override this as needed.
207 isthreaded = False
207 isthreaded = False
208
208
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
210 user_ns=None,user_global_ns=None,banner2='',
210 user_ns=None,user_global_ns=None,banner2='',
211 custom_exceptions=((),None),embedded=False):
211 custom_exceptions=((),None),embedded=False):
212
212
213 # log system
213 # log system
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
215
215
216 # Job manager (for jobs run as background threads)
216 # Job manager (for jobs run as background threads)
217 self.jobs = BackgroundJobManager()
217 self.jobs = BackgroundJobManager()
218
218
219 # Store the actual shell's name
219 # Store the actual shell's name
220 self.name = name
220 self.name = name
221 self.more = False
221 self.more = False
222
222
223 # We need to know whether the instance is meant for embedding, since
223 # We need to know whether the instance is meant for embedding, since
224 # global/local namespaces need to be handled differently in that case
224 # global/local namespaces need to be handled differently in that case
225 self.embedded = embedded
225 self.embedded = embedded
226 if embedded:
226 if embedded:
227 # Control variable so users can, from within the embedded instance,
227 # Control variable so users can, from within the embedded instance,
228 # permanently deactivate it.
228 # permanently deactivate it.
229 self.embedded_active = True
229 self.embedded_active = True
230
230
231 # command compiler
231 # command compiler
232 self.compile = codeop.CommandCompiler()
232 self.compile = codeop.CommandCompiler()
233
233
234 # User input buffer
234 # User input buffer
235 self.buffer = []
235 self.buffer = []
236
236
237 # Default name given in compilation of code
237 # Default name given in compilation of code
238 self.filename = '<ipython console>'
238 self.filename = '<ipython console>'
239
239
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
242 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.exit = Quitter(self,'exit')
243 __builtin__.quit = Quitter(self,'quit')
243 __builtin__.quit = Quitter(self,'quit')
244
244
245 # Make an empty namespace, which extension writers can rely on both
245 # Make an empty namespace, which extension writers can rely on both
246 # existing and NEVER being used by ipython itself. This gives them a
246 # existing and NEVER being used by ipython itself. This gives them a
247 # convenient location for storing additional information and state
247 # convenient location for storing additional information and state
248 # their extensions may require, without fear of collisions with other
248 # their extensions may require, without fear of collisions with other
249 # ipython names that may develop later.
249 # ipython names that may develop later.
250 self.meta = Struct()
250 self.meta = Struct()
251
251
252 # Create the namespace where the user will operate. user_ns is
252 # Create the namespace where the user will operate. user_ns is
253 # normally the only one used, and it is passed to the exec calls as
253 # normally the only one used, and it is passed to the exec calls as
254 # the locals argument. But we do carry a user_global_ns namespace
254 # the locals argument. But we do carry a user_global_ns namespace
255 # given as the exec 'globals' argument, This is useful in embedding
255 # given as the exec 'globals' argument, This is useful in embedding
256 # situations where the ipython shell opens in a context where the
256 # situations where the ipython shell opens in a context where the
257 # distinction between locals and globals is meaningful. For
257 # distinction between locals and globals is meaningful. For
258 # non-embedded contexts, it is just the same object as the user_ns dict.
258 # non-embedded contexts, it is just the same object as the user_ns dict.
259
259
260 # FIXME. For some strange reason, __builtins__ is showing up at user
260 # FIXME. For some strange reason, __builtins__ is showing up at user
261 # level as a dict instead of a module. This is a manual fix, but I
261 # level as a dict instead of a module. This is a manual fix, but I
262 # should really track down where the problem is coming from. Alex
262 # should really track down where the problem is coming from. Alex
263 # Schmolck reported this problem first.
263 # Schmolck reported this problem first.
264
264
265 # A useful post by Alex Martelli on this topic:
265 # A useful post by Alex Martelli on this topic:
266 # Re: inconsistent value from __builtins__
266 # Re: inconsistent value from __builtins__
267 # Von: Alex Martelli <aleaxit@yahoo.com>
267 # Von: Alex Martelli <aleaxit@yahoo.com>
268 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
268 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
269 # Gruppen: comp.lang.python
269 # Gruppen: comp.lang.python
270
270
271 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
271 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
272 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
272 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
273 # > <type 'dict'>
273 # > <type 'dict'>
274 # > >>> print type(__builtins__)
274 # > >>> print type(__builtins__)
275 # > <type 'module'>
275 # > <type 'module'>
276 # > Is this difference in return value intentional?
276 # > Is this difference in return value intentional?
277
277
278 # Well, it's documented that '__builtins__' can be either a dictionary
278 # Well, it's documented that '__builtins__' can be either a dictionary
279 # or a module, and it's been that way for a long time. Whether it's
279 # or a module, and it's been that way for a long time. Whether it's
280 # intentional (or sensible), I don't know. In any case, the idea is
280 # intentional (or sensible), I don't know. In any case, the idea is
281 # that if you need to access the built-in namespace directly, you
281 # that if you need to access the built-in namespace directly, you
282 # should start with "import __builtin__" (note, no 's') which will
282 # should start with "import __builtin__" (note, no 's') which will
283 # definitely give you a module. Yeah, it's somewhat confusing:-(.
283 # definitely give you a module. Yeah, it's somewhat confusing:-(.
284
284
285 # These routines return properly built dicts as needed by the rest of
285 # These routines return properly built dicts as needed by the rest of
286 # the code, and can also be used by extension writers to generate
286 # the code, and can also be used by extension writers to generate
287 # properly initialized namespaces.
287 # properly initialized namespaces.
288 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
288 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
289 user_global_ns)
289 user_global_ns)
290
290
291 # Assign namespaces
291 # Assign namespaces
292 # This is the namespace where all normal user variables live
292 # This is the namespace where all normal user variables live
293 self.user_ns = user_ns
293 self.user_ns = user_ns
294 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
295 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
296 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
297 self.internal_ns = {}
297 self.internal_ns = {}
298
298
299 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
300 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
301 # of positional arguments of the alias.
301 # of positional arguments of the alias.
302 self.alias_table = {}
302 self.alias_table = {}
303
303
304 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
305 # introspection facilities can search easily.
305 # introspection facilities can search easily.
306 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
307 'user_global':user_global_ns,
307 'user_global':user_global_ns,
308 'alias':self.alias_table,
308 'alias':self.alias_table,
309 'internal':self.internal_ns,
309 'internal':self.internal_ns,
310 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
311 }
311 }
312 # The user namespace MUST have a pointer to the shell itself.
312 # The user namespace MUST have a pointer to the shell itself.
313 self.user_ns[name] = self
313 self.user_ns[name] = self
314
314
315 # We need to insert into sys.modules something that looks like a
315 # We need to insert into sys.modules something that looks like a
316 # module but which accesses the IPython namespace, for shelve and
316 # module but which accesses the IPython namespace, for shelve and
317 # pickle to work interactively. Normally they rely on getting
317 # pickle to work interactively. Normally they rely on getting
318 # everything out of __main__, but for embedding purposes each IPython
318 # everything out of __main__, but for embedding purposes each IPython
319 # instance has its own private namespace, so we can't go shoving
319 # instance has its own private namespace, so we can't go shoving
320 # everything into __main__.
320 # everything into __main__.
321
321
322 # note, however, that we should only do this for non-embedded
322 # note, however, that we should only do this for non-embedded
323 # ipythons, which really mimic the __main__.__dict__ with their own
323 # ipythons, which really mimic the __main__.__dict__ with their own
324 # namespace. Embedded instances, on the other hand, should not do
324 # namespace. Embedded instances, on the other hand, should not do
325 # this because they need to manage the user local/global namespaces
325 # this because they need to manage the user local/global namespaces
326 # only, but they live within a 'normal' __main__ (meaning, they
326 # only, but they live within a 'normal' __main__ (meaning, they
327 # shouldn't overtake the execution environment of the script they're
327 # shouldn't overtake the execution environment of the script they're
328 # embedded in).
328 # embedded in).
329
329
330 if not embedded:
330 if not embedded:
331 try:
331 try:
332 main_name = self.user_ns['__name__']
332 main_name = self.user_ns['__name__']
333 except KeyError:
333 except KeyError:
334 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
334 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
335 else:
335 else:
336 #print "pickle hack in place" # dbg
336 #print "pickle hack in place" # dbg
337 #print 'main_name:',main_name # dbg
337 #print 'main_name:',main_name # dbg
338 sys.modules[main_name] = FakeModule(self.user_ns)
338 sys.modules[main_name] = FakeModule(self.user_ns)
339
339
340 # Now that FakeModule produces a real module, we've run into a nasty
340 # Now that FakeModule produces a real module, we've run into a nasty
341 # problem: after script execution (via %run), the module where the user
341 # problem: after script execution (via %run), the module where the user
342 # code ran is deleted. Now that this object is a true module (needed
342 # code ran is deleted. Now that this object is a true module (needed
343 # so docetst and other tools work correctly), the Python module
343 # so docetst and other tools work correctly), the Python module
344 # teardown mechanism runs over it, and sets to None every variable
344 # teardown mechanism runs over it, and sets to None every variable
345 # present in that module. This means that later calls to functions
345 # present in that module. This means that later calls to functions
346 # defined in the script (which have become interactively visible after
346 # defined in the script (which have become interactively visible after
347 # script exit) fail, because they hold references to objects that have
347 # script exit) fail, because they hold references to objects that have
348 # become overwritten into None. The only solution I see right now is
348 # become overwritten into None. The only solution I see right now is
349 # to protect every FakeModule used by %run by holding an internal
349 # to protect every FakeModule used by %run by holding an internal
350 # reference to it. This private list will be used for that. The
350 # reference to it. This private list will be used for that. The
351 # %reset command will flush it as well.
351 # %reset command will flush it as well.
352 self._user_main_modules = []
352 self._user_main_modules = []
353
353
354 # List of input with multi-line handling.
354 # List of input with multi-line handling.
355 # Fill its zero entry, user counter starts at 1
355 # Fill its zero entry, user counter starts at 1
356 self.input_hist = InputList(['\n'])
356 self.input_hist = InputList(['\n'])
357 # This one will hold the 'raw' input history, without any
357 # This one will hold the 'raw' input history, without any
358 # pre-processing. This will allow users to retrieve the input just as
358 # pre-processing. This will allow users to retrieve the input just as
359 # it was exactly typed in by the user, with %hist -r.
359 # it was exactly typed in by the user, with %hist -r.
360 self.input_hist_raw = InputList(['\n'])
360 self.input_hist_raw = InputList(['\n'])
361
361
362 # list of visited directories
362 # list of visited directories
363 try:
363 try:
364 self.dir_hist = [os.getcwd()]
364 self.dir_hist = [os.getcwd()]
365 except OSError:
365 except OSError:
366 self.dir_hist = []
366 self.dir_hist = []
367
367
368 # dict of output history
368 # dict of output history
369 self.output_hist = {}
369 self.output_hist = {}
370
370
371 # Get system encoding at startup time. Certain terminals (like Emacs
371 # Get system encoding at startup time. Certain terminals (like Emacs
372 # under Win32 have it set to None, and we need to have a known valid
372 # under Win32 have it set to None, and we need to have a known valid
373 # encoding to use in the raw_input() method
373 # encoding to use in the raw_input() method
374 try:
374 try:
375 self.stdin_encoding = sys.stdin.encoding or 'ascii'
375 self.stdin_encoding = sys.stdin.encoding or 'ascii'
376 except AttributeError:
376 except AttributeError:
377 self.stdin_encoding = 'ascii'
377 self.stdin_encoding = 'ascii'
378
378
379 # dict of things NOT to alias (keywords, builtins and some magics)
379 # dict of things NOT to alias (keywords, builtins and some magics)
380 no_alias = {}
380 no_alias = {}
381 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
381 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
382 for key in keyword.kwlist + no_alias_magics:
382 for key in keyword.kwlist + no_alias_magics:
383 no_alias[key] = 1
383 no_alias[key] = 1
384 no_alias.update(__builtin__.__dict__)
384 no_alias.update(__builtin__.__dict__)
385 self.no_alias = no_alias
385 self.no_alias = no_alias
386
386
387 # make global variables for user access to these
387 # make global variables for user access to these
388 self.user_ns['_ih'] = self.input_hist
388 self.user_ns['_ih'] = self.input_hist
389 self.user_ns['_oh'] = self.output_hist
389 self.user_ns['_oh'] = self.output_hist
390 self.user_ns['_dh'] = self.dir_hist
390 self.user_ns['_dh'] = self.dir_hist
391
391
392 # user aliases to input and output histories
392 # user aliases to input and output histories
393 self.user_ns['In'] = self.input_hist
393 self.user_ns['In'] = self.input_hist
394 self.user_ns['Out'] = self.output_hist
394 self.user_ns['Out'] = self.output_hist
395
395
396 self.user_ns['_sh'] = IPython.shadowns
396 self.user_ns['_sh'] = IPython.shadowns
397 # Object variable to store code object waiting execution. This is
397 # Object variable to store code object waiting execution. This is
398 # used mainly by the multithreaded shells, but it can come in handy in
398 # used mainly by the multithreaded shells, but it can come in handy in
399 # other situations. No need to use a Queue here, since it's a single
399 # other situations. No need to use a Queue here, since it's a single
400 # item which gets cleared once run.
400 # item which gets cleared once run.
401 self.code_to_run = None
401 self.code_to_run = None
402
402
403 # escapes for automatic behavior on the command line
403 # escapes for automatic behavior on the command line
404 self.ESC_SHELL = '!'
404 self.ESC_SHELL = '!'
405 self.ESC_SH_CAP = '!!'
405 self.ESC_SH_CAP = '!!'
406 self.ESC_HELP = '?'
406 self.ESC_HELP = '?'
407 self.ESC_MAGIC = '%'
407 self.ESC_MAGIC = '%'
408 self.ESC_QUOTE = ','
408 self.ESC_QUOTE = ','
409 self.ESC_QUOTE2 = ';'
409 self.ESC_QUOTE2 = ';'
410 self.ESC_PAREN = '/'
410 self.ESC_PAREN = '/'
411
411
412 # And their associated handlers
412 # And their associated handlers
413 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
413 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
414 self.ESC_QUOTE : self.handle_auto,
414 self.ESC_QUOTE : self.handle_auto,
415 self.ESC_QUOTE2 : self.handle_auto,
415 self.ESC_QUOTE2 : self.handle_auto,
416 self.ESC_MAGIC : self.handle_magic,
416 self.ESC_MAGIC : self.handle_magic,
417 self.ESC_HELP : self.handle_help,
417 self.ESC_HELP : self.handle_help,
418 self.ESC_SHELL : self.handle_shell_escape,
418 self.ESC_SHELL : self.handle_shell_escape,
419 self.ESC_SH_CAP : self.handle_shell_escape,
419 self.ESC_SH_CAP : self.handle_shell_escape,
420 }
420 }
421
421
422 # class initializations
422 # class initializations
423 Magic.__init__(self,self)
423 Magic.__init__(self,self)
424
424
425 # Python source parser/formatter for syntax highlighting
425 # Python source parser/formatter for syntax highlighting
426 pyformat = PyColorize.Parser().format
426 pyformat = PyColorize.Parser().format
427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
428
428
429 # hooks holds pointers used for user-side customizations
429 # hooks holds pointers used for user-side customizations
430 self.hooks = Struct()
430 self.hooks = Struct()
431
431
432 self.strdispatchers = {}
432 self.strdispatchers = {}
433
433
434 # Set all default hooks, defined in the IPython.hooks module.
434 # Set all default hooks, defined in the IPython.hooks module.
435 hooks = IPython.hooks
435 hooks = IPython.hooks
436 for hook_name in hooks.__all__:
436 for hook_name in hooks.__all__:
437 # default hooks have priority 100, i.e. low; user hooks should have
437 # default hooks have priority 100, i.e. low; user hooks should have
438 # 0-100 priority
438 # 0-100 priority
439 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
439 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
440 #print "bound hook",hook_name
440 #print "bound hook",hook_name
441
441
442 # Flag to mark unconditional exit
442 # Flag to mark unconditional exit
443 self.exit_now = False
443 self.exit_now = False
444
444
445 self.usage_min = """\
445 self.usage_min = """\
446 An enhanced console for Python.
446 An enhanced console for Python.
447 Some of its features are:
447 Some of its features are:
448 - Readline support if the readline library is present.
448 - Readline support if the readline library is present.
449 - Tab completion in the local namespace.
449 - Tab completion in the local namespace.
450 - Logging of input, see command-line options.
450 - Logging of input, see command-line options.
451 - System shell escape via ! , eg !ls.
451 - System shell escape via ! , eg !ls.
452 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
452 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
453 - Keeps track of locally defined variables via %who, %whos.
453 - Keeps track of locally defined variables via %who, %whos.
454 - Show object information with a ? eg ?x or x? (use ?? for more info).
454 - Show object information with a ? eg ?x or x? (use ?? for more info).
455 """
455 """
456 if usage: self.usage = usage
456 if usage: self.usage = usage
457 else: self.usage = self.usage_min
457 else: self.usage = self.usage_min
458
458
459 # Storage
459 # Storage
460 self.rc = rc # This will hold all configuration information
460 self.rc = rc # This will hold all configuration information
461 self.pager = 'less'
461 self.pager = 'less'
462 # temporary files used for various purposes. Deleted at exit.
462 # temporary files used for various purposes. Deleted at exit.
463 self.tempfiles = []
463 self.tempfiles = []
464
464
465 # Keep track of readline usage (later set by init_readline)
465 # Keep track of readline usage (later set by init_readline)
466 self.has_readline = False
466 self.has_readline = False
467
467
468 # template for logfile headers. It gets resolved at runtime by the
468 # template for logfile headers. It gets resolved at runtime by the
469 # logstart method.
469 # logstart method.
470 self.loghead_tpl = \
470 self.loghead_tpl = \
471 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
471 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
472 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
472 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
473 #log# opts = %s
473 #log# opts = %s
474 #log# args = %s
474 #log# args = %s
475 #log# It is safe to make manual edits below here.
475 #log# It is safe to make manual edits below here.
476 #log#-----------------------------------------------------------------------
476 #log#-----------------------------------------------------------------------
477 """
477 """
478 # for pushd/popd management
478 # for pushd/popd management
479 try:
479 try:
480 self.home_dir = get_home_dir()
480 self.home_dir = get_home_dir()
481 except HomeDirError,msg:
481 except HomeDirError,msg:
482 fatal(msg)
482 fatal(msg)
483
483
484 self.dir_stack = []
484 self.dir_stack = []
485
485
486 # Functions to call the underlying shell.
486 # Functions to call the underlying shell.
487
487
488 # The first is similar to os.system, but it doesn't return a value,
488 # The first is similar to os.system, but it doesn't return a value,
489 # and it allows interpolation of variables in the user's namespace.
489 # and it allows interpolation of variables in the user's namespace.
490 self.system = lambda cmd: \
490 self.system = lambda cmd: \
491 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
491 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
492
492
493 # These are for getoutput and getoutputerror:
493 # These are for getoutput and getoutputerror:
494 self.getoutput = lambda cmd: \
494 self.getoutput = lambda cmd: \
495 getoutput(self.var_expand(cmd,depth=2),
495 getoutput(self.var_expand(cmd,depth=2),
496 header=self.rc.system_header,
496 header=self.rc.system_header,
497 verbose=self.rc.system_verbose)
497 verbose=self.rc.system_verbose)
498
498
499 self.getoutputerror = lambda cmd: \
499 self.getoutputerror = lambda cmd: \
500 getoutputerror(self.var_expand(cmd,depth=2),
500 getoutputerror(self.var_expand(cmd,depth=2),
501 header=self.rc.system_header,
501 header=self.rc.system_header,
502 verbose=self.rc.system_verbose)
502 verbose=self.rc.system_verbose)
503
503
504
504
505 # keep track of where we started running (mainly for crash post-mortem)
505 # keep track of where we started running (mainly for crash post-mortem)
506 self.starting_dir = os.getcwd()
506 self.starting_dir = os.getcwd()
507
507
508 # Various switches which can be set
508 # Various switches which can be set
509 self.CACHELENGTH = 5000 # this is cheap, it's just text
509 self.CACHELENGTH = 5000 # this is cheap, it's just text
510 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
510 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
511 self.banner2 = banner2
511 self.banner2 = banner2
512
512
513 # TraceBack handlers:
513 # TraceBack handlers:
514
514
515 # Syntax error handler.
515 # Syntax error handler.
516 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
516 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
517
517
518 # The interactive one is initialized with an offset, meaning we always
518 # The interactive one is initialized with an offset, meaning we always
519 # want to remove the topmost item in the traceback, which is our own
519 # want to remove the topmost item in the traceback, which is our own
520 # internal code. Valid modes: ['Plain','Context','Verbose']
520 # internal code. Valid modes: ['Plain','Context','Verbose']
521 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
521 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
522 color_scheme='NoColor',
522 color_scheme='NoColor',
523 tb_offset = 1)
523 tb_offset = 1)
524
524
525 # IPython itself shouldn't crash. This will produce a detailed
525 # IPython itself shouldn't crash. This will produce a detailed
526 # post-mortem if it does. But we only install the crash handler for
526 # post-mortem if it does. But we only install the crash handler for
527 # non-threaded shells, the threaded ones use a normal verbose reporter
527 # non-threaded shells, the threaded ones use a normal verbose reporter
528 # and lose the crash handler. This is because exceptions in the main
528 # and lose the crash handler. This is because exceptions in the main
529 # thread (such as in GUI code) propagate directly to sys.excepthook,
529 # thread (such as in GUI code) propagate directly to sys.excepthook,
530 # and there's no point in printing crash dumps for every user exception.
530 # and there's no point in printing crash dumps for every user exception.
531 if self.isthreaded:
531 if self.isthreaded:
532 ipCrashHandler = ultraTB.FormattedTB()
532 ipCrashHandler = ultraTB.FormattedTB()
533 else:
533 else:
534 from IPython import CrashHandler
534 from IPython import CrashHandler
535 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
535 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
536 self.set_crash_handler(ipCrashHandler)
536 self.set_crash_handler(ipCrashHandler)
537
537
538 # and add any custom exception handlers the user may have specified
538 # and add any custom exception handlers the user may have specified
539 self.set_custom_exc(*custom_exceptions)
539 self.set_custom_exc(*custom_exceptions)
540
540
541 # indentation management
541 # indentation management
542 self.autoindent = False
542 self.autoindent = False
543 self.indent_current_nsp = 0
543 self.indent_current_nsp = 0
544
544
545 # Make some aliases automatically
545 # Make some aliases automatically
546 # Prepare list of shell aliases to auto-define
546 # Prepare list of shell aliases to auto-define
547 if os.name == 'posix':
547 if os.name == 'posix':
548 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
548 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
549 'mv mv -i','rm rm -i','cp cp -i',
549 'mv mv -i','rm rm -i','cp cp -i',
550 'cat cat','less less','clear clear',
550 'cat cat','less less','clear clear',
551 # a better ls
551 # a better ls
552 'ls ls -F',
552 'ls ls -F',
553 # long ls
553 # long ls
554 'll ls -lF')
554 'll ls -lF')
555 # Extra ls aliases with color, which need special treatment on BSD
555 # Extra ls aliases with color, which need special treatment on BSD
556 # variants
556 # variants
557 ls_extra = ( # color ls
557 ls_extra = ( # color ls
558 'lc ls -F -o --color',
558 'lc ls -F -o --color',
559 # ls normal files only
559 # ls normal files only
560 'lf ls -F -o --color %l | grep ^-',
560 'lf ls -F -o --color %l | grep ^-',
561 # ls symbolic links
561 # ls symbolic links
562 'lk ls -F -o --color %l | grep ^l',
562 'lk ls -F -o --color %l | grep ^l',
563 # directories or links to directories,
563 # directories or links to directories,
564 'ldir ls -F -o --color %l | grep /$',
564 'ldir ls -F -o --color %l | grep /$',
565 # things which are executable
565 # things which are executable
566 'lx ls -F -o --color %l | grep ^-..x',
566 'lx ls -F -o --color %l | grep ^-..x',
567 )
567 )
568 # The BSDs don't ship GNU ls, so they don't understand the
568 # The BSDs don't ship GNU ls, so they don't understand the
569 # --color switch out of the box
569 # --color switch out of the box
570 if 'bsd' in sys.platform:
570 if 'bsd' in sys.platform:
571 ls_extra = ( # ls normal files only
571 ls_extra = ( # ls normal files only
572 'lf ls -lF | grep ^-',
572 'lf ls -lF | grep ^-',
573 # ls symbolic links
573 # ls symbolic links
574 'lk ls -lF | grep ^l',
574 'lk ls -lF | grep ^l',
575 # directories or links to directories,
575 # directories or links to directories,
576 'ldir ls -lF | grep /$',
576 'ldir ls -lF | grep /$',
577 # things which are executable
577 # things which are executable
578 'lx ls -lF | grep ^-..x',
578 'lx ls -lF | grep ^-..x',
579 )
579 )
580 auto_alias = auto_alias + ls_extra
580 auto_alias = auto_alias + ls_extra
581 elif os.name in ['nt','dos']:
581 elif os.name in ['nt','dos']:
582 auto_alias = ('ls dir /on',
582 auto_alias = ('ls dir /on',
583 'ddir dir /ad /on', 'ldir dir /ad /on',
583 'ddir dir /ad /on', 'ldir dir /ad /on',
584 'mkdir mkdir','rmdir rmdir','echo echo',
584 'mkdir mkdir','rmdir rmdir','echo echo',
585 'ren ren','cls cls','copy copy')
585 'ren ren','cls cls','copy copy')
586 else:
586 else:
587 auto_alias = ()
587 auto_alias = ()
588 self.auto_alias = [s.split(None,1) for s in auto_alias]
588 self.auto_alias = [s.split(None,1) for s in auto_alias]
589
589
590
590
591 # Produce a public API instance
591 # Produce a public API instance
592 self.api = IPython.ipapi.IPApi(self)
592 self.api = IPython.ipapi.IPApi(self)
593
593
594 # Call the actual (public) initializer
594 # Call the actual (public) initializer
595 self.init_auto_alias()
595 self.init_auto_alias()
596
596
597 # track which builtins we add, so we can clean up later
597 # track which builtins we add, so we can clean up later
598 self.builtins_added = {}
598 self.builtins_added = {}
599 # This method will add the necessary builtins for operation, but
599 # This method will add the necessary builtins for operation, but
600 # tracking what it did via the builtins_added dict.
600 # tracking what it did via the builtins_added dict.
601
601
602 #TODO: remove this, redundant
602 #TODO: remove this, redundant
603 self.add_builtins()
603 self.add_builtins()
604
604
605
605
606
606
607
607
608 # end __init__
608 # end __init__
609
609
610 def var_expand(self,cmd,depth=0):
610 def var_expand(self,cmd,depth=0):
611 """Expand python variables in a string.
611 """Expand python variables in a string.
612
612
613 The depth argument indicates how many frames above the caller should
613 The depth argument indicates how many frames above the caller should
614 be walked to look for the local namespace where to expand variables.
614 be walked to look for the local namespace where to expand variables.
615
615
616 The global namespace for expansion is always the user's interactive
616 The global namespace for expansion is always the user's interactive
617 namespace.
617 namespace.
618 """
618 """
619
619
620 return str(ItplNS(cmd,
620 return str(ItplNS(cmd,
621 self.user_ns, # globals
621 self.user_ns, # globals
622 # Skip our own frame in searching for locals:
622 # Skip our own frame in searching for locals:
623 sys._getframe(depth+1).f_locals # locals
623 sys._getframe(depth+1).f_locals # locals
624 ))
624 ))
625
625
626 def pre_config_initialization(self):
626 def pre_config_initialization(self):
627 """Pre-configuration init method
627 """Pre-configuration init method
628
628
629 This is called before the configuration files are processed to
629 This is called before the configuration files are processed to
630 prepare the services the config files might need.
630 prepare the services the config files might need.
631
631
632 self.rc already has reasonable default values at this point.
632 self.rc already has reasonable default values at this point.
633 """
633 """
634 rc = self.rc
634 rc = self.rc
635 try:
635 try:
636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
637 except exceptions.UnicodeDecodeError:
637 except exceptions.UnicodeDecodeError:
638 print "Your ipythondir can't be decoded to unicode!"
638 print "Your ipythondir can't be decoded to unicode!"
639 print "Please set HOME environment variable to something that"
639 print "Please set HOME environment variable to something that"
640 print r"only has ASCII characters, e.g. c:\home"
640 print r"only has ASCII characters, e.g. c:\home"
641 print "Now it is",rc.ipythondir
641 print "Now it is",rc.ipythondir
642 sys.exit()
642 sys.exit()
643 self.shadowhist = IPython.history.ShadowHist(self.db)
643 self.shadowhist = IPython.history.ShadowHist(self.db)
644
644
645
645
646 def post_config_initialization(self):
646 def post_config_initialization(self):
647 """Post configuration init method
647 """Post configuration init method
648
648
649 This is called after the configuration files have been processed to
649 This is called after the configuration files have been processed to
650 'finalize' the initialization."""
650 'finalize' the initialization."""
651
651
652 rc = self.rc
652 rc = self.rc
653
653
654 # Object inspector
654 # Object inspector
655 self.inspector = OInspect.Inspector(OInspect.InspectColors,
655 self.inspector = OInspect.Inspector(OInspect.InspectColors,
656 PyColorize.ANSICodeColors,
656 PyColorize.ANSICodeColors,
657 'NoColor',
657 'NoColor',
658 rc.object_info_string_level)
658 rc.object_info_string_level)
659
659
660 self.rl_next_input = None
660 self.rl_next_input = None
661 self.rl_do_indent = False
661 self.rl_do_indent = False
662 # Load readline proper
662 # Load readline proper
663 if rc.readline:
663 if rc.readline:
664 self.init_readline()
664 self.init_readline()
665
665
666
666
667 # local shortcut, this is used a LOT
667 # local shortcut, this is used a LOT
668 self.log = self.logger.log
668 self.log = self.logger.log
669
669
670 # Initialize cache, set in/out prompts and printing system
670 # Initialize cache, set in/out prompts and printing system
671 self.outputcache = CachedOutput(self,
671 self.outputcache = CachedOutput(self,
672 rc.cache_size,
672 rc.cache_size,
673 rc.pprint,
673 rc.pprint,
674 input_sep = rc.separate_in,
674 input_sep = rc.separate_in,
675 output_sep = rc.separate_out,
675 output_sep = rc.separate_out,
676 output_sep2 = rc.separate_out2,
676 output_sep2 = rc.separate_out2,
677 ps1 = rc.prompt_in1,
677 ps1 = rc.prompt_in1,
678 ps2 = rc.prompt_in2,
678 ps2 = rc.prompt_in2,
679 ps_out = rc.prompt_out,
679 ps_out = rc.prompt_out,
680 pad_left = rc.prompts_pad_left)
680 pad_left = rc.prompts_pad_left)
681
681
682 # user may have over-ridden the default print hook:
682 # user may have over-ridden the default print hook:
683 try:
683 try:
684 self.outputcache.__class__.display = self.hooks.display
684 self.outputcache.__class__.display = self.hooks.display
685 except AttributeError:
685 except AttributeError:
686 pass
686 pass
687
687
688 # I don't like assigning globally to sys, because it means when
688 # I don't like assigning globally to sys, because it means when
689 # embedding instances, each embedded instance overrides the previous
689 # embedding instances, each embedded instance overrides the previous
690 # choice. But sys.displayhook seems to be called internally by exec,
690 # choice. But sys.displayhook seems to be called internally by exec,
691 # so I don't see a way around it. We first save the original and then
691 # so I don't see a way around it. We first save the original and then
692 # overwrite it.
692 # overwrite it.
693 self.sys_displayhook = sys.displayhook
693 self.sys_displayhook = sys.displayhook
694 sys.displayhook = self.outputcache
694 sys.displayhook = self.outputcache
695
695
696 # Do a proper resetting of doctest, including the necessary displayhook
696 # Do a proper resetting of doctest, including the necessary displayhook
697 # monkeypatching
697 # monkeypatching
698 try:
698 try:
699 doctest_reload()
699 doctest_reload()
700 except ImportError:
700 except ImportError:
701 warn("doctest module does not exist.")
701 warn("doctest module does not exist.")
702
702
703 # Set user colors (don't do it in the constructor above so that it
703 # Set user colors (don't do it in the constructor above so that it
704 # doesn't crash if colors option is invalid)
704 # doesn't crash if colors option is invalid)
705 self.magic_colors(rc.colors)
705 self.magic_colors(rc.colors)
706
706
707 # Set calling of pdb on exceptions
707 # Set calling of pdb on exceptions
708 self.call_pdb = rc.pdb
708 self.call_pdb = rc.pdb
709
709
710 # Load user aliases
710 # Load user aliases
711 for alias in rc.alias:
711 for alias in rc.alias:
712 self.magic_alias(alias)
712 self.magic_alias(alias)
713
713
714 self.hooks.late_startup_hook()
714 self.hooks.late_startup_hook()
715
715
716 for cmd in self.rc.autoexec:
716 for cmd in self.rc.autoexec:
717 #print "autoexec>",cmd #dbg
717 #print "autoexec>",cmd #dbg
718 self.api.runlines(cmd)
718 self.api.runlines(cmd)
719
719
720 batchrun = False
720 batchrun = False
721 for batchfile in [path(arg) for arg in self.rc.args
721 for batchfile in [path(arg) for arg in self.rc.args
722 if arg.lower().endswith('.ipy')]:
722 if arg.lower().endswith('.ipy')]:
723 if not batchfile.isfile():
723 if not batchfile.isfile():
724 print "No such batch file:", batchfile
724 print "No such batch file:", batchfile
725 continue
725 continue
726 self.api.runlines(batchfile.text())
726 self.api.runlines(batchfile.text())
727 batchrun = True
727 batchrun = True
728 # without -i option, exit after running the batch file
728 # without -i option, exit after running the batch file
729 if batchrun and not self.rc.interact:
729 if batchrun and not self.rc.interact:
730 self.ask_exit()
730 self.ask_exit()
731
731
732 def add_builtins(self):
732 def add_builtins(self):
733 """Store ipython references into the builtin namespace.
733 """Store ipython references into the builtin namespace.
734
734
735 Some parts of ipython operate via builtins injected here, which hold a
735 Some parts of ipython operate via builtins injected here, which hold a
736 reference to IPython itself."""
736 reference to IPython itself."""
737
737
738 # TODO: deprecate all of these, they are unsafe
738 # TODO: deprecate all of these, they are unsafe
739 builtins_new = dict(__IPYTHON__ = self,
739 builtins_new = dict(__IPYTHON__ = self,
740 ip_set_hook = self.set_hook,
740 ip_set_hook = self.set_hook,
741 jobs = self.jobs,
741 jobs = self.jobs,
742 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
742 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
743 ipalias = wrap_deprecated(self.ipalias),
743 ipalias = wrap_deprecated(self.ipalias),
744 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
744 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
745 #_ip = self.api
745 #_ip = self.api
746 )
746 )
747 for biname,bival in builtins_new.items():
747 for biname,bival in builtins_new.items():
748 try:
748 try:
749 # store the orignal value so we can restore it
749 # store the orignal value so we can restore it
750 self.builtins_added[biname] = __builtin__.__dict__[biname]
750 self.builtins_added[biname] = __builtin__.__dict__[biname]
751 except KeyError:
751 except KeyError:
752 # or mark that it wasn't defined, and we'll just delete it at
752 # or mark that it wasn't defined, and we'll just delete it at
753 # cleanup
753 # cleanup
754 self.builtins_added[biname] = Undefined
754 self.builtins_added[biname] = Undefined
755 __builtin__.__dict__[biname] = bival
755 __builtin__.__dict__[biname] = bival
756
756
757 # Keep in the builtins a flag for when IPython is active. We set it
757 # Keep in the builtins a flag for when IPython is active. We set it
758 # with setdefault so that multiple nested IPythons don't clobber one
758 # with setdefault so that multiple nested IPythons don't clobber one
759 # another. Each will increase its value by one upon being activated,
759 # another. Each will increase its value by one upon being activated,
760 # which also gives us a way to determine the nesting level.
760 # which also gives us a way to determine the nesting level.
761 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
761 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
762
762
763 def clean_builtins(self):
763 def clean_builtins(self):
764 """Remove any builtins which might have been added by add_builtins, or
764 """Remove any builtins which might have been added by add_builtins, or
765 restore overwritten ones to their previous values."""
765 restore overwritten ones to their previous values."""
766 for biname,bival in self.builtins_added.items():
766 for biname,bival in self.builtins_added.items():
767 if bival is Undefined:
767 if bival is Undefined:
768 del __builtin__.__dict__[biname]
768 del __builtin__.__dict__[biname]
769 else:
769 else:
770 __builtin__.__dict__[biname] = bival
770 __builtin__.__dict__[biname] = bival
771 self.builtins_added.clear()
771 self.builtins_added.clear()
772
772
773 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
773 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
774 """set_hook(name,hook) -> sets an internal IPython hook.
774 """set_hook(name,hook) -> sets an internal IPython hook.
775
775
776 IPython exposes some of its internal API as user-modifiable hooks. By
776 IPython exposes some of its internal API as user-modifiable hooks. By
777 adding your function to one of these hooks, you can modify IPython's
777 adding your function to one of these hooks, you can modify IPython's
778 behavior to call at runtime your own routines."""
778 behavior to call at runtime your own routines."""
779
779
780 # At some point in the future, this should validate the hook before it
780 # At some point in the future, this should validate the hook before it
781 # accepts it. Probably at least check that the hook takes the number
781 # accepts it. Probably at least check that the hook takes the number
782 # of args it's supposed to.
782 # of args it's supposed to.
783
783
784 f = new.instancemethod(hook,self,self.__class__)
784 f = new.instancemethod(hook,self,self.__class__)
785
785
786 # check if the hook is for strdispatcher first
786 # check if the hook is for strdispatcher first
787 if str_key is not None:
787 if str_key is not None:
788 sdp = self.strdispatchers.get(name, StrDispatch())
788 sdp = self.strdispatchers.get(name, StrDispatch())
789 sdp.add_s(str_key, f, priority )
789 sdp.add_s(str_key, f, priority )
790 self.strdispatchers[name] = sdp
790 self.strdispatchers[name] = sdp
791 return
791 return
792 if re_key is not None:
792 if re_key is not None:
793 sdp = self.strdispatchers.get(name, StrDispatch())
793 sdp = self.strdispatchers.get(name, StrDispatch())
794 sdp.add_re(re.compile(re_key), f, priority )
794 sdp.add_re(re.compile(re_key), f, priority )
795 self.strdispatchers[name] = sdp
795 self.strdispatchers[name] = sdp
796 return
796 return
797
797
798 dp = getattr(self.hooks, name, None)
798 dp = getattr(self.hooks, name, None)
799 if name not in IPython.hooks.__all__:
799 if name not in IPython.hooks.__all__:
800 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
800 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
801 if not dp:
801 if not dp:
802 dp = IPython.hooks.CommandChainDispatcher()
802 dp = IPython.hooks.CommandChainDispatcher()
803
803
804 try:
804 try:
805 dp.add(f,priority)
805 dp.add(f,priority)
806 except AttributeError:
806 except AttributeError:
807 # it was not commandchain, plain old func - replace
807 # it was not commandchain, plain old func - replace
808 dp = f
808 dp = f
809
809
810 setattr(self.hooks,name, dp)
810 setattr(self.hooks,name, dp)
811
811
812
812
813 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
813 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
814
814
815 def set_crash_handler(self,crashHandler):
815 def set_crash_handler(self,crashHandler):
816 """Set the IPython crash handler.
816 """Set the IPython crash handler.
817
817
818 This must be a callable with a signature suitable for use as
818 This must be a callable with a signature suitable for use as
819 sys.excepthook."""
819 sys.excepthook."""
820
820
821 # Install the given crash handler as the Python exception hook
821 # Install the given crash handler as the Python exception hook
822 sys.excepthook = crashHandler
822 sys.excepthook = crashHandler
823
823
824 # The instance will store a pointer to this, so that runtime code
824 # The instance will store a pointer to this, so that runtime code
825 # (such as magics) can access it. This is because during the
825 # (such as magics) can access it. This is because during the
826 # read-eval loop, it gets temporarily overwritten (to deal with GUI
826 # read-eval loop, it gets temporarily overwritten (to deal with GUI
827 # frameworks).
827 # frameworks).
828 self.sys_excepthook = sys.excepthook
828 self.sys_excepthook = sys.excepthook
829
829
830
830
831 def set_custom_exc(self,exc_tuple,handler):
831 def set_custom_exc(self,exc_tuple,handler):
832 """set_custom_exc(exc_tuple,handler)
832 """set_custom_exc(exc_tuple,handler)
833
833
834 Set a custom exception handler, which will be called if any of the
834 Set a custom exception handler, which will be called if any of the
835 exceptions in exc_tuple occur in the mainloop (specifically, in the
835 exceptions in exc_tuple occur in the mainloop (specifically, in the
836 runcode() method.
836 runcode() method.
837
837
838 Inputs:
838 Inputs:
839
839
840 - exc_tuple: a *tuple* of valid exceptions to call the defined
840 - exc_tuple: a *tuple* of valid exceptions to call the defined
841 handler for. It is very important that you use a tuple, and NOT A
841 handler for. It is very important that you use a tuple, and NOT A
842 LIST here, because of the way Python's except statement works. If
842 LIST here, because of the way Python's except statement works. If
843 you only want to trap a single exception, use a singleton tuple:
843 you only want to trap a single exception, use a singleton tuple:
844
844
845 exc_tuple == (MyCustomException,)
845 exc_tuple == (MyCustomException,)
846
846
847 - handler: this must be defined as a function with the following
847 - handler: this must be defined as a function with the following
848 basic interface: def my_handler(self,etype,value,tb).
848 basic interface: def my_handler(self,etype,value,tb).
849
849
850 This will be made into an instance method (via new.instancemethod)
850 This will be made into an instance method (via new.instancemethod)
851 of IPython itself, and it will be called if any of the exceptions
851 of IPython itself, and it will be called if any of the exceptions
852 listed in the exc_tuple are caught. If the handler is None, an
852 listed in the exc_tuple are caught. If the handler is None, an
853 internal basic one is used, which just prints basic info.
853 internal basic one is used, which just prints basic info.
854
854
855 WARNING: by putting in your own exception handler into IPython's main
855 WARNING: by putting in your own exception handler into IPython's main
856 execution loop, you run a very good chance of nasty crashes. This
856 execution loop, you run a very good chance of nasty crashes. This
857 facility should only be used if you really know what you are doing."""
857 facility should only be used if you really know what you are doing."""
858
858
859 assert type(exc_tuple)==type(()) , \
859 assert type(exc_tuple)==type(()) , \
860 "The custom exceptions must be given AS A TUPLE."
860 "The custom exceptions must be given AS A TUPLE."
861
861
862 def dummy_handler(self,etype,value,tb):
862 def dummy_handler(self,etype,value,tb):
863 print '*** Simple custom exception handler ***'
863 print '*** Simple custom exception handler ***'
864 print 'Exception type :',etype
864 print 'Exception type :',etype
865 print 'Exception value:',value
865 print 'Exception value:',value
866 print 'Traceback :',tb
866 print 'Traceback :',tb
867 print 'Source code :','\n'.join(self.buffer)
867 print 'Source code :','\n'.join(self.buffer)
868
868
869 if handler is None: handler = dummy_handler
869 if handler is None: handler = dummy_handler
870
870
871 self.CustomTB = new.instancemethod(handler,self,self.__class__)
871 self.CustomTB = new.instancemethod(handler,self,self.__class__)
872 self.custom_exceptions = exc_tuple
872 self.custom_exceptions = exc_tuple
873
873
874 def set_custom_completer(self,completer,pos=0):
874 def set_custom_completer(self,completer,pos=0):
875 """set_custom_completer(completer,pos=0)
875 """set_custom_completer(completer,pos=0)
876
876
877 Adds a new custom completer function.
877 Adds a new custom completer function.
878
878
879 The position argument (defaults to 0) is the index in the completers
879 The position argument (defaults to 0) is the index in the completers
880 list where you want the completer to be inserted."""
880 list where you want the completer to be inserted."""
881
881
882 newcomp = new.instancemethod(completer,self.Completer,
882 newcomp = new.instancemethod(completer,self.Completer,
883 self.Completer.__class__)
883 self.Completer.__class__)
884 self.Completer.matchers.insert(pos,newcomp)
884 self.Completer.matchers.insert(pos,newcomp)
885
885
886 def set_completer(self):
886 def set_completer(self):
887 """reset readline's completer to be our own."""
887 """reset readline's completer to be our own."""
888 self.readline.set_completer(self.Completer.complete)
888 self.readline.set_completer(self.Completer.complete)
889
889
890 def _get_call_pdb(self):
890 def _get_call_pdb(self):
891 return self._call_pdb
891 return self._call_pdb
892
892
893 def _set_call_pdb(self,val):
893 def _set_call_pdb(self,val):
894
894
895 if val not in (0,1,False,True):
895 if val not in (0,1,False,True):
896 raise ValueError,'new call_pdb value must be boolean'
896 raise ValueError,'new call_pdb value must be boolean'
897
897
898 # store value in instance
898 # store value in instance
899 self._call_pdb = val
899 self._call_pdb = val
900
900
901 # notify the actual exception handlers
901 # notify the actual exception handlers
902 self.InteractiveTB.call_pdb = val
902 self.InteractiveTB.call_pdb = val
903 if self.isthreaded:
903 if self.isthreaded:
904 try:
904 try:
905 self.sys_excepthook.call_pdb = val
905 self.sys_excepthook.call_pdb = val
906 except:
906 except:
907 warn('Failed to activate pdb for threaded exception handler')
907 warn('Failed to activate pdb for threaded exception handler')
908
908
909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
910 'Control auto-activation of pdb at exceptions')
910 'Control auto-activation of pdb at exceptions')
911
911
912
912
913 # These special functions get installed in the builtin namespace, to
913 # These special functions get installed in the builtin namespace, to
914 # provide programmatic (pure python) access to magics, aliases and system
914 # provide programmatic (pure python) access to magics, aliases and system
915 # calls. This is important for logging, user scripting, and more.
915 # calls. This is important for logging, user scripting, and more.
916
916
917 # We are basically exposing, via normal python functions, the three
917 # We are basically exposing, via normal python functions, the three
918 # mechanisms in which ipython offers special call modes (magics for
918 # mechanisms in which ipython offers special call modes (magics for
919 # internal control, aliases for direct system access via pre-selected
919 # internal control, aliases for direct system access via pre-selected
920 # names, and !cmd for calling arbitrary system commands).
920 # names, and !cmd for calling arbitrary system commands).
921
921
922 def ipmagic(self,arg_s):
922 def ipmagic(self,arg_s):
923 """Call a magic function by name.
923 """Call a magic function by name.
924
924
925 Input: a string containing the name of the magic function to call and any
925 Input: a string containing the name of the magic function to call and any
926 additional arguments to be passed to the magic.
926 additional arguments to be passed to the magic.
927
927
928 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
928 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
929 prompt:
929 prompt:
930
930
931 In[1]: %name -opt foo bar
931 In[1]: %name -opt foo bar
932
932
933 To call a magic without arguments, simply use ipmagic('name').
933 To call a magic without arguments, simply use ipmagic('name').
934
934
935 This provides a proper Python function to call IPython's magics in any
935 This provides a proper Python function to call IPython's magics in any
936 valid Python code you can type at the interpreter, including loops and
936 valid Python code you can type at the interpreter, including loops and
937 compound statements. It is added by IPython to the Python builtin
937 compound statements. It is added by IPython to the Python builtin
938 namespace upon initialization."""
938 namespace upon initialization."""
939
939
940 args = arg_s.split(' ',1)
940 args = arg_s.split(' ',1)
941 magic_name = args[0]
941 magic_name = args[0]
942 magic_name = magic_name.lstrip(self.ESC_MAGIC)
942 magic_name = magic_name.lstrip(self.ESC_MAGIC)
943
943
944 try:
944 try:
945 magic_args = args[1]
945 magic_args = args[1]
946 except IndexError:
946 except IndexError:
947 magic_args = ''
947 magic_args = ''
948 fn = getattr(self,'magic_'+magic_name,None)
948 fn = getattr(self,'magic_'+magic_name,None)
949 if fn is None:
949 if fn is None:
950 error("Magic function `%s` not found." % magic_name)
950 error("Magic function `%s` not found." % magic_name)
951 else:
951 else:
952 magic_args = self.var_expand(magic_args,1)
952 magic_args = self.var_expand(magic_args,1)
953 return fn(magic_args)
953 return fn(magic_args)
954
954
955 def ipalias(self,arg_s):
955 def ipalias(self,arg_s):
956 """Call an alias by name.
956 """Call an alias by name.
957
957
958 Input: a string containing the name of the alias to call and any
958 Input: a string containing the name of the alias to call and any
959 additional arguments to be passed to the magic.
959 additional arguments to be passed to the magic.
960
960
961 ipalias('name -opt foo bar') is equivalent to typing at the ipython
961 ipalias('name -opt foo bar') is equivalent to typing at the ipython
962 prompt:
962 prompt:
963
963
964 In[1]: name -opt foo bar
964 In[1]: name -opt foo bar
965
965
966 To call an alias without arguments, simply use ipalias('name').
966 To call an alias without arguments, simply use ipalias('name').
967
967
968 This provides a proper Python function to call IPython's aliases in any
968 This provides a proper Python function to call IPython's aliases in any
969 valid Python code you can type at the interpreter, including loops and
969 valid Python code you can type at the interpreter, including loops and
970 compound statements. It is added by IPython to the Python builtin
970 compound statements. It is added by IPython to the Python builtin
971 namespace upon initialization."""
971 namespace upon initialization."""
972
972
973 args = arg_s.split(' ',1)
973 args = arg_s.split(' ',1)
974 alias_name = args[0]
974 alias_name = args[0]
975 try:
975 try:
976 alias_args = args[1]
976 alias_args = args[1]
977 except IndexError:
977 except IndexError:
978 alias_args = ''
978 alias_args = ''
979 if alias_name in self.alias_table:
979 if alias_name in self.alias_table:
980 self.call_alias(alias_name,alias_args)
980 self.call_alias(alias_name,alias_args)
981 else:
981 else:
982 error("Alias `%s` not found." % alias_name)
982 error("Alias `%s` not found." % alias_name)
983
983
984 def ipsystem(self,arg_s):
984 def ipsystem(self,arg_s):
985 """Make a system call, using IPython."""
985 """Make a system call, using IPython."""
986
986
987 self.system(arg_s)
987 self.system(arg_s)
988
988
989 def complete(self,text):
989 def complete(self,text):
990 """Return a sorted list of all possible completions on text.
990 """Return a sorted list of all possible completions on text.
991
991
992 Inputs:
992 Inputs:
993
993
994 - text: a string of text to be completed on.
994 - text: a string of text to be completed on.
995
995
996 This is a wrapper around the completion mechanism, similar to what
996 This is a wrapper around the completion mechanism, similar to what
997 readline does at the command line when the TAB key is hit. By
997 readline does at the command line when the TAB key is hit. By
998 exposing it as a method, it can be used by other non-readline
998 exposing it as a method, it can be used by other non-readline
999 environments (such as GUIs) for text completion.
999 environments (such as GUIs) for text completion.
1000
1000
1001 Simple usage example:
1001 Simple usage example:
1002
1002
1003 In [7]: x = 'hello'
1003 In [7]: x = 'hello'
1004
1004
1005 In [8]: x
1005 In [8]: x
1006 Out[8]: 'hello'
1006 Out[8]: 'hello'
1007
1007
1008 In [9]: print x
1008 In [9]: print x
1009 hello
1009 hello
1010
1010
1011 In [10]: _ip.IP.complete('x.l')
1011 In [10]: _ip.IP.complete('x.l')
1012 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1012 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1013 """
1013 """
1014
1014
1015 complete = self.Completer.complete
1015 complete = self.Completer.complete
1016 state = 0
1016 state = 0
1017 # use a dict so we get unique keys, since ipyhton's multiple
1017 # use a dict so we get unique keys, since ipyhton's multiple
1018 # completers can return duplicates. When we make 2.4 a requirement,
1018 # completers can return duplicates. When we make 2.4 a requirement,
1019 # start using sets instead, which are faster.
1019 # start using sets instead, which are faster.
1020 comps = {}
1020 comps = {}
1021 while True:
1021 while True:
1022 newcomp = complete(text,state,line_buffer=text)
1022 newcomp = complete(text,state,line_buffer=text)
1023 if newcomp is None:
1023 if newcomp is None:
1024 break
1024 break
1025 comps[newcomp] = 1
1025 comps[newcomp] = 1
1026 state += 1
1026 state += 1
1027 outcomps = comps.keys()
1027 outcomps = comps.keys()
1028 outcomps.sort()
1028 outcomps.sort()
1029 #print "T:",text,"OC:",outcomps # dbg
1029 #print "T:",text,"OC:",outcomps # dbg
1030 #print "vars:",self.user_ns.keys()
1030 #print "vars:",self.user_ns.keys()
1031 return outcomps
1031 return outcomps
1032
1032
1033 def set_completer_frame(self, frame=None):
1033 def set_completer_frame(self, frame=None):
1034 if frame:
1034 if frame:
1035 self.Completer.namespace = frame.f_locals
1035 self.Completer.namespace = frame.f_locals
1036 self.Completer.global_namespace = frame.f_globals
1036 self.Completer.global_namespace = frame.f_globals
1037 else:
1037 else:
1038 self.Completer.namespace = self.user_ns
1038 self.Completer.namespace = self.user_ns
1039 self.Completer.global_namespace = self.user_global_ns
1039 self.Completer.global_namespace = self.user_global_ns
1040
1040
1041 def init_auto_alias(self):
1041 def init_auto_alias(self):
1042 """Define some aliases automatically.
1042 """Define some aliases automatically.
1043
1043
1044 These are ALL parameter-less aliases"""
1044 These are ALL parameter-less aliases"""
1045
1045
1046 for alias,cmd in self.auto_alias:
1046 for alias,cmd in self.auto_alias:
1047 self.getapi().defalias(alias,cmd)
1047 self.getapi().defalias(alias,cmd)
1048
1048
1049
1049
1050 def alias_table_validate(self,verbose=0):
1050 def alias_table_validate(self,verbose=0):
1051 """Update information about the alias table.
1051 """Update information about the alias table.
1052
1052
1053 In particular, make sure no Python keywords/builtins are in it."""
1053 In particular, make sure no Python keywords/builtins are in it."""
1054
1054
1055 no_alias = self.no_alias
1055 no_alias = self.no_alias
1056 for k in self.alias_table.keys():
1056 for k in self.alias_table.keys():
1057 if k in no_alias:
1057 if k in no_alias:
1058 del self.alias_table[k]
1058 del self.alias_table[k]
1059 if verbose:
1059 if verbose:
1060 print ("Deleting alias <%s>, it's a Python "
1060 print ("Deleting alias <%s>, it's a Python "
1061 "keyword or builtin." % k)
1061 "keyword or builtin." % k)
1062
1062
1063 def set_autoindent(self,value=None):
1063 def set_autoindent(self,value=None):
1064 """Set the autoindent flag, checking for readline support.
1064 """Set the autoindent flag, checking for readline support.
1065
1065
1066 If called with no arguments, it acts as a toggle."""
1066 If called with no arguments, it acts as a toggle."""
1067
1067
1068 if not self.has_readline:
1068 if not self.has_readline:
1069 if os.name == 'posix':
1069 if os.name == 'posix':
1070 warn("The auto-indent feature requires the readline library")
1070 warn("The auto-indent feature requires the readline library")
1071 self.autoindent = 0
1071 self.autoindent = 0
1072 return
1072 return
1073 if value is None:
1073 if value is None:
1074 self.autoindent = not self.autoindent
1074 self.autoindent = not self.autoindent
1075 else:
1075 else:
1076 self.autoindent = value
1076 self.autoindent = value
1077
1077
1078 def rc_set_toggle(self,rc_field,value=None):
1078 def rc_set_toggle(self,rc_field,value=None):
1079 """Set or toggle a field in IPython's rc config. structure.
1079 """Set or toggle a field in IPython's rc config. structure.
1080
1080
1081 If called with no arguments, it acts as a toggle.
1081 If called with no arguments, it acts as a toggle.
1082
1082
1083 If called with a non-existent field, the resulting AttributeError
1083 If called with a non-existent field, the resulting AttributeError
1084 exception will propagate out."""
1084 exception will propagate out."""
1085
1085
1086 rc_val = getattr(self.rc,rc_field)
1086 rc_val = getattr(self.rc,rc_field)
1087 if value is None:
1087 if value is None:
1088 value = not rc_val
1088 value = not rc_val
1089 setattr(self.rc,rc_field,value)
1089 setattr(self.rc,rc_field,value)
1090
1090
1091 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1091 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1092 """Install the user configuration directory.
1092 """Install the user configuration directory.
1093
1093
1094 Can be called when running for the first time or to upgrade the user's
1094 Can be called when running for the first time or to upgrade the user's
1095 .ipython/ directory with the mode parameter. Valid modes are 'install'
1095 .ipython/ directory with the mode parameter. Valid modes are 'install'
1096 and 'upgrade'."""
1096 and 'upgrade'."""
1097
1097
1098 def wait():
1098 def wait():
1099 try:
1099 try:
1100 raw_input("Please press <RETURN> to start IPython.")
1100 raw_input("Please press <RETURN> to start IPython.")
1101 except EOFError:
1101 except EOFError:
1102 print >> Term.cout
1102 print >> Term.cout
1103 print '*'*70
1103 print '*'*70
1104
1104
1105 cwd = os.getcwd() # remember where we started
1105 cwd = os.getcwd() # remember where we started
1106 glb = glob.glob
1106 glb = glob.glob
1107 print '*'*70
1107 print '*'*70
1108 if mode == 'install':
1108 if mode == 'install':
1109 print \
1109 print \
1110 """Welcome to IPython. I will try to create a personal configuration directory
1110 """Welcome to IPython. I will try to create a personal configuration directory
1111 where you can customize many aspects of IPython's functionality in:\n"""
1111 where you can customize many aspects of IPython's functionality in:\n"""
1112 else:
1112 else:
1113 print 'I am going to upgrade your configuration in:'
1113 print 'I am going to upgrade your configuration in:'
1114
1114
1115 print ipythondir
1115 print ipythondir
1116
1116
1117 rcdirend = os.path.join('IPython','UserConfig')
1117 rcdirend = os.path.join('IPython','UserConfig')
1118 cfg = lambda d: os.path.join(d,rcdirend)
1118 cfg = lambda d: os.path.join(d,rcdirend)
1119 try:
1119 try:
1120 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1120 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1121 print "Initializing from configuration",rcdir
1121 print "Initializing from configuration",rcdir
1122 except IndexError:
1122 except IndexError:
1123 warning = """
1123 warning = """
1124 Installation error. IPython's directory was not found.
1124 Installation error. IPython's directory was not found.
1125
1125
1126 Check the following:
1126 Check the following:
1127
1127
1128 The ipython/IPython directory should be in a directory belonging to your
1128 The ipython/IPython directory should be in a directory belonging to your
1129 PYTHONPATH environment variable (that is, it should be in a directory
1129 PYTHONPATH environment variable (that is, it should be in a directory
1130 belonging to sys.path). You can copy it explicitly there or just link to it.
1130 belonging to sys.path). You can copy it explicitly there or just link to it.
1131
1131
1132 IPython will create a minimal default configuration for you.
1132 IPython will create a minimal default configuration for you.
1133
1133
1134 """
1134 """
1135 warn(warning)
1135 warn(warning)
1136 wait()
1136 wait()
1137
1137
1138 if sys.platform =='win32':
1138 if sys.platform =='win32':
1139 inif = 'ipythonrc.ini'
1139 inif = 'ipythonrc.ini'
1140 else:
1140 else:
1141 inif = 'ipythonrc'
1141 inif = 'ipythonrc'
1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1143 os.makedirs(ipythondir, mode = 0777)
1143 os.makedirs(ipythondir, mode = 0777)
1144 for f, cont in minimal_setup.items():
1144 for f, cont in minimal_setup.items():
1145 open(ipythondir + '/' + f,'w').write(cont)
1145 open(ipythondir + '/' + f,'w').write(cont)
1146
1146
1147 return
1147 return
1148
1148
1149 if mode == 'install':
1149 if mode == 'install':
1150 try:
1150 try:
1151 shutil.copytree(rcdir,ipythondir)
1151 shutil.copytree(rcdir,ipythondir)
1152 os.chdir(ipythondir)
1152 os.chdir(ipythondir)
1153 rc_files = glb("ipythonrc*")
1153 rc_files = glb("ipythonrc*")
1154 for rc_file in rc_files:
1154 for rc_file in rc_files:
1155 os.rename(rc_file,rc_file+rc_suffix)
1155 os.rename(rc_file,rc_file+rc_suffix)
1156 except:
1156 except:
1157 warning = """
1157 warning = """
1158
1158
1159 There was a problem with the installation:
1159 There was a problem with the installation:
1160 %s
1160 %s
1161 Try to correct it or contact the developers if you think it's a bug.
1161 Try to correct it or contact the developers if you think it's a bug.
1162 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1162 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1163 warn(warning)
1163 warn(warning)
1164 wait()
1164 wait()
1165 return
1165 return
1166
1166
1167 elif mode == 'upgrade':
1167 elif mode == 'upgrade':
1168 try:
1168 try:
1169 os.chdir(ipythondir)
1169 os.chdir(ipythondir)
1170 except:
1170 except:
1171 print """
1171 print """
1172 Can not upgrade: changing to directory %s failed. Details:
1172 Can not upgrade: changing to directory %s failed. Details:
1173 %s
1173 %s
1174 """ % (ipythondir,sys.exc_info()[1])
1174 """ % (ipythondir,sys.exc_info()[1])
1175 wait()
1175 wait()
1176 return
1176 return
1177 else:
1177 else:
1178 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1178 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1179 for new_full_path in sources:
1179 for new_full_path in sources:
1180 new_filename = os.path.basename(new_full_path)
1180 new_filename = os.path.basename(new_full_path)
1181 if new_filename.startswith('ipythonrc'):
1181 if new_filename.startswith('ipythonrc'):
1182 new_filename = new_filename + rc_suffix
1182 new_filename = new_filename + rc_suffix
1183 # The config directory should only contain files, skip any
1183 # The config directory should only contain files, skip any
1184 # directories which may be there (like CVS)
1184 # directories which may be there (like CVS)
1185 if os.path.isdir(new_full_path):
1185 if os.path.isdir(new_full_path):
1186 continue
1186 continue
1187 if os.path.exists(new_filename):
1187 if os.path.exists(new_filename):
1188 old_file = new_filename+'.old'
1188 old_file = new_filename+'.old'
1189 if os.path.exists(old_file):
1189 if os.path.exists(old_file):
1190 os.remove(old_file)
1190 os.remove(old_file)
1191 os.rename(new_filename,old_file)
1191 os.rename(new_filename,old_file)
1192 shutil.copy(new_full_path,new_filename)
1192 shutil.copy(new_full_path,new_filename)
1193 else:
1193 else:
1194 raise ValueError,'unrecognized mode for install:',`mode`
1194 raise ValueError,'unrecognized mode for install:',`mode`
1195
1195
1196 # Fix line-endings to those native to each platform in the config
1196 # Fix line-endings to those native to each platform in the config
1197 # directory.
1197 # directory.
1198 try:
1198 try:
1199 os.chdir(ipythondir)
1199 os.chdir(ipythondir)
1200 except:
1200 except:
1201 print """
1201 print """
1202 Problem: changing to directory %s failed.
1202 Problem: changing to directory %s failed.
1203 Details:
1203 Details:
1204 %s
1204 %s
1205
1205
1206 Some configuration files may have incorrect line endings. This should not
1206 Some configuration files may have incorrect line endings. This should not
1207 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1207 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1208 wait()
1208 wait()
1209 else:
1209 else:
1210 for fname in glb('ipythonrc*'):
1210 for fname in glb('ipythonrc*'):
1211 try:
1211 try:
1212 native_line_ends(fname,backup=0)
1212 native_line_ends(fname,backup=0)
1213 except IOError:
1213 except IOError:
1214 pass
1214 pass
1215
1215
1216 if mode == 'install':
1216 if mode == 'install':
1217 print """
1217 print """
1218 Successful installation!
1218 Successful installation!
1219
1219
1220 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1220 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1221 IPython manual (there are both HTML and PDF versions supplied with the
1221 IPython manual (there are both HTML and PDF versions supplied with the
1222 distribution) to make sure that your system environment is properly configured
1222 distribution) to make sure that your system environment is properly configured
1223 to take advantage of IPython's features.
1223 to take advantage of IPython's features.
1224
1224
1225 Important note: the configuration system has changed! The old system is
1225 Important note: the configuration system has changed! The old system is
1226 still in place, but its setting may be partly overridden by the settings in
1226 still in place, but its setting may be partly overridden by the settings in
1227 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1227 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1228 if some of the new settings bother you.
1228 if some of the new settings bother you.
1229
1229
1230 """
1230 """
1231 else:
1231 else:
1232 print """
1232 print """
1233 Successful upgrade!
1233 Successful upgrade!
1234
1234
1235 All files in your directory:
1235 All files in your directory:
1236 %(ipythondir)s
1236 %(ipythondir)s
1237 which would have been overwritten by the upgrade were backed up with a .old
1237 which would have been overwritten by the upgrade were backed up with a .old
1238 extension. If you had made particular customizations in those files you may
1238 extension. If you had made particular customizations in those files you may
1239 want to merge them back into the new files.""" % locals()
1239 want to merge them back into the new files.""" % locals()
1240 wait()
1240 wait()
1241 os.chdir(cwd)
1241 os.chdir(cwd)
1242 # end user_setup()
1242 # end user_setup()
1243
1243
1244 def atexit_operations(self):
1244 def atexit_operations(self):
1245 """This will be executed at the time of exit.
1245 """This will be executed at the time of exit.
1246
1246
1247 Saving of persistent data should be performed here. """
1247 Saving of persistent data should be performed here. """
1248
1248
1249 #print '*** IPython exit cleanup ***' # dbg
1249 #print '*** IPython exit cleanup ***' # dbg
1250 # input history
1250 # input history
1251 self.savehist()
1251 self.savehist()
1252
1252
1253 # Cleanup all tempfiles left around
1253 # Cleanup all tempfiles left around
1254 for tfile in self.tempfiles:
1254 for tfile in self.tempfiles:
1255 try:
1255 try:
1256 os.unlink(tfile)
1256 os.unlink(tfile)
1257 except OSError:
1257 except OSError:
1258 pass
1258 pass
1259
1259
1260 self.hooks.shutdown_hook()
1260 self.hooks.shutdown_hook()
1261
1261
1262 def savehist(self):
1262 def savehist(self):
1263 """Save input history to a file (via readline library)."""
1263 """Save input history to a file (via readline library)."""
1264
1264
1265 if not self.has_readline:
1265 if not self.has_readline:
1266 return
1266 return
1267
1267
1268 try:
1268 try:
1269 self.readline.write_history_file(self.histfile)
1269 self.readline.write_history_file(self.histfile)
1270 except:
1270 except:
1271 print 'Unable to save IPython command history to file: ' + \
1271 print 'Unable to save IPython command history to file: ' + \
1272 `self.histfile`
1272 `self.histfile`
1273
1273
1274 def reloadhist(self):
1274 def reloadhist(self):
1275 """Reload the input history from disk file."""
1275 """Reload the input history from disk file."""
1276
1276
1277 if self.has_readline:
1277 if self.has_readline:
1278 try:
1278 try:
1279 self.readline.clear_history()
1279 self.readline.clear_history()
1280 self.readline.read_history_file(self.shell.histfile)
1280 self.readline.read_history_file(self.shell.histfile)
1281 except AttributeError:
1281 except AttributeError:
1282 pass
1282 pass
1283
1283
1284
1284
1285 def history_saving_wrapper(self, func):
1285 def history_saving_wrapper(self, func):
1286 """ Wrap func for readline history saving
1286 """ Wrap func for readline history saving
1287
1287
1288 Convert func into callable that saves & restores
1288 Convert func into callable that saves & restores
1289 history around the call """
1289 history around the call """
1290
1290
1291 if not self.has_readline:
1291 if not self.has_readline:
1292 return func
1292 return func
1293
1293
1294 def wrapper():
1294 def wrapper():
1295 self.savehist()
1295 self.savehist()
1296 try:
1296 try:
1297 func()
1297 func()
1298 finally:
1298 finally:
1299 readline.read_history_file(self.histfile)
1299 readline.read_history_file(self.histfile)
1300 return wrapper
1300 return wrapper
1301
1301
1302
1302
1303 def pre_readline(self):
1303 def pre_readline(self):
1304 """readline hook to be used at the start of each line.
1304 """readline hook to be used at the start of each line.
1305
1305
1306 Currently it handles auto-indent only."""
1306 Currently it handles auto-indent only."""
1307
1307
1308 #debugx('self.indent_current_nsp','pre_readline:')
1308 #debugx('self.indent_current_nsp','pre_readline:')
1309
1309
1310 if self.rl_do_indent:
1310 if self.rl_do_indent:
1311 self.readline.insert_text(self.indent_current_str())
1311 self.readline.insert_text(self.indent_current_str())
1312 if self.rl_next_input is not None:
1312 if self.rl_next_input is not None:
1313 self.readline.insert_text(self.rl_next_input)
1313 self.readline.insert_text(self.rl_next_input)
1314 self.rl_next_input = None
1314 self.rl_next_input = None
1315
1315
1316 def init_readline(self):
1316 def init_readline(self):
1317 """Command history completion/saving/reloading."""
1317 """Command history completion/saving/reloading."""
1318
1318
1319
1319
1320 import IPython.rlineimpl as readline
1320 import IPython.rlineimpl as readline
1321
1321
1322 if not readline.have_readline:
1322 if not readline.have_readline:
1323 self.has_readline = 0
1323 self.has_readline = 0
1324 self.readline = None
1324 self.readline = None
1325 # no point in bugging windows users with this every time:
1325 # no point in bugging windows users with this every time:
1326 warn('Readline services not available on this platform.')
1326 warn('Readline services not available on this platform.')
1327 else:
1327 else:
1328 sys.modules['readline'] = readline
1328 sys.modules['readline'] = readline
1329 import atexit
1329 import atexit
1330 from IPython.completer import IPCompleter
1330 from IPython.completer import IPCompleter
1331 self.Completer = IPCompleter(self,
1331 self.Completer = IPCompleter(self,
1332 self.user_ns,
1332 self.user_ns,
1333 self.user_global_ns,
1333 self.user_global_ns,
1334 self.rc.readline_omit__names,
1334 self.rc.readline_omit__names,
1335 self.alias_table)
1335 self.alias_table)
1336 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1336 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1337 self.strdispatchers['complete_command'] = sdisp
1337 self.strdispatchers['complete_command'] = sdisp
1338 self.Completer.custom_completers = sdisp
1338 self.Completer.custom_completers = sdisp
1339 # Platform-specific configuration
1339 # Platform-specific configuration
1340 if os.name == 'nt':
1340 if os.name == 'nt':
1341 self.readline_startup_hook = readline.set_pre_input_hook
1341 self.readline_startup_hook = readline.set_pre_input_hook
1342 else:
1342 else:
1343 self.readline_startup_hook = readline.set_startup_hook
1343 self.readline_startup_hook = readline.set_startup_hook
1344
1344
1345 # Load user's initrc file (readline config)
1345 # Load user's initrc file (readline config)
1346 # Or if libedit is used, load editrc.
1346 # Or if libedit is used, load editrc.
1347 inputrc_name = os.environ.get('INPUTRC')
1347 inputrc_name = os.environ.get('INPUTRC')
1348 if inputrc_name is None:
1348 if inputrc_name is None:
1349 home_dir = get_home_dir()
1349 home_dir = get_home_dir()
1350 if home_dir is not None:
1350 if home_dir is not None:
1351 inputrc_name = '.inputrc'
1351 inputrc_name = '.inputrc'
1352 if readline.uses_libedit:
1352 if readline.uses_libedit:
1353 inputrc_name = '.editrc'
1353 inputrc_name = '.editrc'
1354 inputrc_name = os.path.join(home_dir, inputrc_name)
1354 inputrc_name = os.path.join(home_dir, inputrc_name)
1355 if os.path.isfile(inputrc_name):
1355 if os.path.isfile(inputrc_name):
1356 try:
1356 try:
1357 readline.read_init_file(inputrc_name)
1357 readline.read_init_file(inputrc_name)
1358 except:
1358 except:
1359 warn('Problems reading readline initialization file <%s>'
1359 warn('Problems reading readline initialization file <%s>'
1360 % inputrc_name)
1360 % inputrc_name)
1361
1361
1362 self.has_readline = 1
1362 self.has_readline = 1
1363 self.readline = readline
1363 self.readline = readline
1364 # save this in sys so embedded copies can restore it properly
1364 # save this in sys so embedded copies can restore it properly
1365 sys.ipcompleter = self.Completer.complete
1365 sys.ipcompleter = self.Completer.complete
1366 self.set_completer()
1366 self.set_completer()
1367
1367
1368 # Configure readline according to user's prefs
1368 # Configure readline according to user's prefs
1369 # This is only done if GNU readline is being used. If libedit
1369 # This is only done if GNU readline is being used. If libedit
1370 # is being used (as on Leopard) the readline config is
1370 # is being used (as on Leopard) the readline config is
1371 # not run as the syntax for libedit is different.
1371 # not run as the syntax for libedit is different.
1372 if not readline.uses_libedit:
1372 if not readline.uses_libedit:
1373 for rlcommand in self.rc.readline_parse_and_bind:
1373 for rlcommand in self.rc.readline_parse_and_bind:
1374 readline.parse_and_bind(rlcommand)
1374 readline.parse_and_bind(rlcommand)
1375
1375
1376 # remove some chars from the delimiters list
1376 # remove some chars from the delimiters list
1377 delims = readline.get_completer_delims()
1377 delims = readline.get_completer_delims()
1378 delims = delims.translate(string._idmap,
1378 delims = delims.translate(string._idmap,
1379 self.rc.readline_remove_delims)
1379 self.rc.readline_remove_delims)
1380 readline.set_completer_delims(delims)
1380 readline.set_completer_delims(delims)
1381 # otherwise we end up with a monster history after a while:
1381 # otherwise we end up with a monster history after a while:
1382 readline.set_history_length(1000)
1382 readline.set_history_length(1000)
1383 try:
1383 try:
1384 #print '*** Reading readline history' # dbg
1384 #print '*** Reading readline history' # dbg
1385 readline.read_history_file(self.histfile)
1385 readline.read_history_file(self.histfile)
1386 except IOError:
1386 except IOError:
1387 pass # It doesn't exist yet.
1387 pass # It doesn't exist yet.
1388
1388
1389 atexit.register(self.atexit_operations)
1389 atexit.register(self.atexit_operations)
1390 del atexit
1390 del atexit
1391
1391
1392 # Configure auto-indent for all platforms
1392 # Configure auto-indent for all platforms
1393 self.set_autoindent(self.rc.autoindent)
1393 self.set_autoindent(self.rc.autoindent)
1394
1394
1395 def ask_yes_no(self,prompt,default=True):
1395 def ask_yes_no(self,prompt,default=True):
1396 if self.rc.quiet:
1396 if self.rc.quiet:
1397 return True
1397 return True
1398 return ask_yes_no(prompt,default)
1398 return ask_yes_no(prompt,default)
1399
1399
1400 def _should_recompile(self,e):
1400 def _should_recompile(self,e):
1401 """Utility routine for edit_syntax_error"""
1401 """Utility routine for edit_syntax_error"""
1402
1402
1403 if e.filename in ('<ipython console>','<input>','<string>',
1403 if e.filename in ('<ipython console>','<input>','<string>',
1404 '<console>','<BackgroundJob compilation>',
1404 '<console>','<BackgroundJob compilation>',
1405 None):
1405 None):
1406
1406
1407 return False
1407 return False
1408 try:
1408 try:
1409 if (self.rc.autoedit_syntax and
1409 if (self.rc.autoedit_syntax and
1410 not self.ask_yes_no('Return to editor to correct syntax error? '
1410 not self.ask_yes_no('Return to editor to correct syntax error? '
1411 '[Y/n] ','y')):
1411 '[Y/n] ','y')):
1412 return False
1412 return False
1413 except EOFError:
1413 except EOFError:
1414 return False
1414 return False
1415
1415
1416 def int0(x):
1416 def int0(x):
1417 try:
1417 try:
1418 return int(x)
1418 return int(x)
1419 except TypeError:
1419 except TypeError:
1420 return 0
1420 return 0
1421 # always pass integer line and offset values to editor hook
1421 # always pass integer line and offset values to editor hook
1422 try:
1422 self.hooks.fix_error_editor(e.filename,
1423 self.hooks.fix_error_editor(e.filename,
1423 int0(e.lineno),int0(e.offset),e.msg)
1424 int0(e.lineno),int0(e.offset),e.msg)
1425 except IPython.ipapi.TryNext:
1426 warn('Could not open editor')
1427 return False
1424 return True
1428 return True
1425
1429
1426 def edit_syntax_error(self):
1430 def edit_syntax_error(self):
1427 """The bottom half of the syntax error handler called in the main loop.
1431 """The bottom half of the syntax error handler called in the main loop.
1428
1432
1429 Loop until syntax error is fixed or user cancels.
1433 Loop until syntax error is fixed or user cancels.
1430 """
1434 """
1431
1435
1432 while self.SyntaxTB.last_syntax_error:
1436 while self.SyntaxTB.last_syntax_error:
1433 # copy and clear last_syntax_error
1437 # copy and clear last_syntax_error
1434 err = self.SyntaxTB.clear_err_state()
1438 err = self.SyntaxTB.clear_err_state()
1435 if not self._should_recompile(err):
1439 if not self._should_recompile(err):
1436 return
1440 return
1437 try:
1441 try:
1438 # may set last_syntax_error again if a SyntaxError is raised
1442 # may set last_syntax_error again if a SyntaxError is raised
1439 self.safe_execfile(err.filename,self.user_ns)
1443 self.safe_execfile(err.filename,self.user_ns)
1440 except:
1444 except:
1441 self.showtraceback()
1445 self.showtraceback()
1442 else:
1446 else:
1443 try:
1447 try:
1444 f = file(err.filename)
1448 f = file(err.filename)
1445 try:
1449 try:
1446 sys.displayhook(f.read())
1450 sys.displayhook(f.read())
1447 finally:
1451 finally:
1448 f.close()
1452 f.close()
1449 except:
1453 except:
1450 self.showtraceback()
1454 self.showtraceback()
1451
1455
1452 def showsyntaxerror(self, filename=None):
1456 def showsyntaxerror(self, filename=None):
1453 """Display the syntax error that just occurred.
1457 """Display the syntax error that just occurred.
1454
1458
1455 This doesn't display a stack trace because there isn't one.
1459 This doesn't display a stack trace because there isn't one.
1456
1460
1457 If a filename is given, it is stuffed in the exception instead
1461 If a filename is given, it is stuffed in the exception instead
1458 of what was there before (because Python's parser always uses
1462 of what was there before (because Python's parser always uses
1459 "<string>" when reading from a string).
1463 "<string>" when reading from a string).
1460 """
1464 """
1461 etype, value, last_traceback = sys.exc_info()
1465 etype, value, last_traceback = sys.exc_info()
1462
1466
1463 # See note about these variables in showtraceback() below
1467 # See note about these variables in showtraceback() below
1464 sys.last_type = etype
1468 sys.last_type = etype
1465 sys.last_value = value
1469 sys.last_value = value
1466 sys.last_traceback = last_traceback
1470 sys.last_traceback = last_traceback
1467
1471
1468 if filename and etype is SyntaxError:
1472 if filename and etype is SyntaxError:
1469 # Work hard to stuff the correct filename in the exception
1473 # Work hard to stuff the correct filename in the exception
1470 try:
1474 try:
1471 msg, (dummy_filename, lineno, offset, line) = value
1475 msg, (dummy_filename, lineno, offset, line) = value
1472 except:
1476 except:
1473 # Not the format we expect; leave it alone
1477 # Not the format we expect; leave it alone
1474 pass
1478 pass
1475 else:
1479 else:
1476 # Stuff in the right filename
1480 # Stuff in the right filename
1477 try:
1481 try:
1478 # Assume SyntaxError is a class exception
1482 # Assume SyntaxError is a class exception
1479 value = SyntaxError(msg, (filename, lineno, offset, line))
1483 value = SyntaxError(msg, (filename, lineno, offset, line))
1480 except:
1484 except:
1481 # If that failed, assume SyntaxError is a string
1485 # If that failed, assume SyntaxError is a string
1482 value = msg, (filename, lineno, offset, line)
1486 value = msg, (filename, lineno, offset, line)
1483 self.SyntaxTB(etype,value,[])
1487 self.SyntaxTB(etype,value,[])
1484
1488
1485 def debugger(self,force=False):
1489 def debugger(self,force=False):
1486 """Call the pydb/pdb debugger.
1490 """Call the pydb/pdb debugger.
1487
1491
1488 Keywords:
1492 Keywords:
1489
1493
1490 - force(False): by default, this routine checks the instance call_pdb
1494 - force(False): by default, this routine checks the instance call_pdb
1491 flag and does not actually invoke the debugger if the flag is false.
1495 flag and does not actually invoke the debugger if the flag is false.
1492 The 'force' option forces the debugger to activate even if the flag
1496 The 'force' option forces the debugger to activate even if the flag
1493 is false.
1497 is false.
1494 """
1498 """
1495
1499
1496 if not (force or self.call_pdb):
1500 if not (force or self.call_pdb):
1497 return
1501 return
1498
1502
1499 if not hasattr(sys,'last_traceback'):
1503 if not hasattr(sys,'last_traceback'):
1500 error('No traceback has been produced, nothing to debug.')
1504 error('No traceback has been produced, nothing to debug.')
1501 return
1505 return
1502
1506
1503 # use pydb if available
1507 # use pydb if available
1504 if Debugger.has_pydb:
1508 if Debugger.has_pydb:
1505 from pydb import pm
1509 from pydb import pm
1506 else:
1510 else:
1507 # fallback to our internal debugger
1511 # fallback to our internal debugger
1508 pm = lambda : self.InteractiveTB.debugger(force=True)
1512 pm = lambda : self.InteractiveTB.debugger(force=True)
1509 self.history_saving_wrapper(pm)()
1513 self.history_saving_wrapper(pm)()
1510
1514
1511 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1515 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1512 """Display the exception that just occurred.
1516 """Display the exception that just occurred.
1513
1517
1514 If nothing is known about the exception, this is the method which
1518 If nothing is known about the exception, this is the method which
1515 should be used throughout the code for presenting user tracebacks,
1519 should be used throughout the code for presenting user tracebacks,
1516 rather than directly invoking the InteractiveTB object.
1520 rather than directly invoking the InteractiveTB object.
1517
1521
1518 A specific showsyntaxerror() also exists, but this method can take
1522 A specific showsyntaxerror() also exists, but this method can take
1519 care of calling it if needed, so unless you are explicitly catching a
1523 care of calling it if needed, so unless you are explicitly catching a
1520 SyntaxError exception, don't try to analyze the stack manually and
1524 SyntaxError exception, don't try to analyze the stack manually and
1521 simply call this method."""
1525 simply call this method."""
1522
1526
1523
1527
1524 # Though this won't be called by syntax errors in the input line,
1528 # Though this won't be called by syntax errors in the input line,
1525 # there may be SyntaxError cases whith imported code.
1529 # there may be SyntaxError cases whith imported code.
1526
1530
1527 try:
1531 try:
1528 if exc_tuple is None:
1532 if exc_tuple is None:
1529 etype, value, tb = sys.exc_info()
1533 etype, value, tb = sys.exc_info()
1530 else:
1534 else:
1531 etype, value, tb = exc_tuple
1535 etype, value, tb = exc_tuple
1532
1536
1533 if etype is SyntaxError:
1537 if etype is SyntaxError:
1534 self.showsyntaxerror(filename)
1538 self.showsyntaxerror(filename)
1535 elif etype is IPython.ipapi.UsageError:
1539 elif etype is IPython.ipapi.UsageError:
1536 print "UsageError:", value
1540 print "UsageError:", value
1537 else:
1541 else:
1538 # WARNING: these variables are somewhat deprecated and not
1542 # WARNING: these variables are somewhat deprecated and not
1539 # necessarily safe to use in a threaded environment, but tools
1543 # necessarily safe to use in a threaded environment, but tools
1540 # like pdb depend on their existence, so let's set them. If we
1544 # like pdb depend on their existence, so let's set them. If we
1541 # find problems in the field, we'll need to revisit their use.
1545 # find problems in the field, we'll need to revisit their use.
1542 sys.last_type = etype
1546 sys.last_type = etype
1543 sys.last_value = value
1547 sys.last_value = value
1544 sys.last_traceback = tb
1548 sys.last_traceback = tb
1545
1549
1546 if etype in self.custom_exceptions:
1550 if etype in self.custom_exceptions:
1547 self.CustomTB(etype,value,tb)
1551 self.CustomTB(etype,value,tb)
1548 else:
1552 else:
1549 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1553 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1550 if self.InteractiveTB.call_pdb and self.has_readline:
1554 if self.InteractiveTB.call_pdb and self.has_readline:
1551 # pdb mucks up readline, fix it back
1555 # pdb mucks up readline, fix it back
1552 self.set_completer()
1556 self.set_completer()
1553 except KeyboardInterrupt:
1557 except KeyboardInterrupt:
1554 self.write("\nKeyboardInterrupt\n")
1558 self.write("\nKeyboardInterrupt\n")
1555
1559
1556
1560
1557
1561
1558 def mainloop(self,banner=None):
1562 def mainloop(self,banner=None):
1559 """Creates the local namespace and starts the mainloop.
1563 """Creates the local namespace and starts the mainloop.
1560
1564
1561 If an optional banner argument is given, it will override the
1565 If an optional banner argument is given, it will override the
1562 internally created default banner."""
1566 internally created default banner."""
1563
1567
1564 if self.rc.c: # Emulate Python's -c option
1568 if self.rc.c: # Emulate Python's -c option
1565 self.exec_init_cmd()
1569 self.exec_init_cmd()
1566 if banner is None:
1570 if banner is None:
1567 if not self.rc.banner:
1571 if not self.rc.banner:
1568 banner = ''
1572 banner = ''
1569 # banner is string? Use it directly!
1573 # banner is string? Use it directly!
1570 elif isinstance(self.rc.banner,basestring):
1574 elif isinstance(self.rc.banner,basestring):
1571 banner = self.rc.banner
1575 banner = self.rc.banner
1572 else:
1576 else:
1573 banner = self.BANNER+self.banner2
1577 banner = self.BANNER+self.banner2
1574
1578
1579 # if you run stuff with -c <cmd>, raw hist is not updated
1580 # ensure that it's in sync
1581 if len(self.input_hist) != len (self.input_hist_raw):
1582 self.input_hist_raw = InputList(self.input_hist)
1583
1575 while 1:
1584 while 1:
1576 try:
1585 try:
1577 self.interact(banner)
1586 self.interact(banner)
1578 #self.interact_with_readline()
1587 #self.interact_with_readline()
1579 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1588 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1580
1589
1581 break
1590 break
1582 except KeyboardInterrupt:
1591 except KeyboardInterrupt:
1583 # this should not be necessary, but KeyboardInterrupt
1592 # this should not be necessary, but KeyboardInterrupt
1584 # handling seems rather unpredictable...
1593 # handling seems rather unpredictable...
1585 self.write("\nKeyboardInterrupt in interact()\n")
1594 self.write("\nKeyboardInterrupt in interact()\n")
1586
1595
1587 def exec_init_cmd(self):
1596 def exec_init_cmd(self):
1588 """Execute a command given at the command line.
1597 """Execute a command given at the command line.
1589
1598
1590 This emulates Python's -c option."""
1599 This emulates Python's -c option."""
1591
1600
1592 #sys.argv = ['-c']
1601 #sys.argv = ['-c']
1593 self.push(self.prefilter(self.rc.c, False))
1602 self.push(self.prefilter(self.rc.c, False))
1594 if not self.rc.interact:
1603 if not self.rc.interact:
1595 self.ask_exit()
1604 self.ask_exit()
1596
1605
1597 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1606 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1598 """Embeds IPython into a running python program.
1607 """Embeds IPython into a running python program.
1599
1608
1600 Input:
1609 Input:
1601
1610
1602 - header: An optional header message can be specified.
1611 - header: An optional header message can be specified.
1603
1612
1604 - local_ns, global_ns: working namespaces. If given as None, the
1613 - local_ns, global_ns: working namespaces. If given as None, the
1605 IPython-initialized one is updated with __main__.__dict__, so that
1614 IPython-initialized one is updated with __main__.__dict__, so that
1606 program variables become visible but user-specific configuration
1615 program variables become visible but user-specific configuration
1607 remains possible.
1616 remains possible.
1608
1617
1609 - stack_depth: specifies how many levels in the stack to go to
1618 - stack_depth: specifies how many levels in the stack to go to
1610 looking for namespaces (when local_ns and global_ns are None). This
1619 looking for namespaces (when local_ns and global_ns are None). This
1611 allows an intermediate caller to make sure that this function gets
1620 allows an intermediate caller to make sure that this function gets
1612 the namespace from the intended level in the stack. By default (0)
1621 the namespace from the intended level in the stack. By default (0)
1613 it will get its locals and globals from the immediate caller.
1622 it will get its locals and globals from the immediate caller.
1614
1623
1615 Warning: it's possible to use this in a program which is being run by
1624 Warning: it's possible to use this in a program which is being run by
1616 IPython itself (via %run), but some funny things will happen (a few
1625 IPython itself (via %run), but some funny things will happen (a few
1617 globals get overwritten). In the future this will be cleaned up, as
1626 globals get overwritten). In the future this will be cleaned up, as
1618 there is no fundamental reason why it can't work perfectly."""
1627 there is no fundamental reason why it can't work perfectly."""
1619
1628
1620 # Get locals and globals from caller
1629 # Get locals and globals from caller
1621 if local_ns is None or global_ns is None:
1630 if local_ns is None or global_ns is None:
1622 call_frame = sys._getframe(stack_depth).f_back
1631 call_frame = sys._getframe(stack_depth).f_back
1623
1632
1624 if local_ns is None:
1633 if local_ns is None:
1625 local_ns = call_frame.f_locals
1634 local_ns = call_frame.f_locals
1626 if global_ns is None:
1635 if global_ns is None:
1627 global_ns = call_frame.f_globals
1636 global_ns = call_frame.f_globals
1628
1637
1629 # Update namespaces and fire up interpreter
1638 # Update namespaces and fire up interpreter
1630
1639
1631 # The global one is easy, we can just throw it in
1640 # The global one is easy, we can just throw it in
1632 self.user_global_ns = global_ns
1641 self.user_global_ns = global_ns
1633
1642
1634 # but the user/local one is tricky: ipython needs it to store internal
1643 # but the user/local one is tricky: ipython needs it to store internal
1635 # data, but we also need the locals. We'll copy locals in the user
1644 # data, but we also need the locals. We'll copy locals in the user
1636 # one, but will track what got copied so we can delete them at exit.
1645 # one, but will track what got copied so we can delete them at exit.
1637 # This is so that a later embedded call doesn't see locals from a
1646 # This is so that a later embedded call doesn't see locals from a
1638 # previous call (which most likely existed in a separate scope).
1647 # previous call (which most likely existed in a separate scope).
1639 local_varnames = local_ns.keys()
1648 local_varnames = local_ns.keys()
1640 self.user_ns.update(local_ns)
1649 self.user_ns.update(local_ns)
1641 #self.user_ns['local_ns'] = local_ns # dbg
1650 #self.user_ns['local_ns'] = local_ns # dbg
1642
1651
1643 # Patch for global embedding to make sure that things don't overwrite
1652 # Patch for global embedding to make sure that things don't overwrite
1644 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1653 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1645 # FIXME. Test this a bit more carefully (the if.. is new)
1654 # FIXME. Test this a bit more carefully (the if.. is new)
1646 if local_ns is None and global_ns is None:
1655 if local_ns is None and global_ns is None:
1647 self.user_global_ns.update(__main__.__dict__)
1656 self.user_global_ns.update(__main__.__dict__)
1648
1657
1649 # make sure the tab-completer has the correct frame information, so it
1658 # make sure the tab-completer has the correct frame information, so it
1650 # actually completes using the frame's locals/globals
1659 # actually completes using the frame's locals/globals
1651 self.set_completer_frame()
1660 self.set_completer_frame()
1652
1661
1653 # before activating the interactive mode, we need to make sure that
1662 # before activating the interactive mode, we need to make sure that
1654 # all names in the builtin namespace needed by ipython point to
1663 # all names in the builtin namespace needed by ipython point to
1655 # ourselves, and not to other instances.
1664 # ourselves, and not to other instances.
1656 self.add_builtins()
1665 self.add_builtins()
1657
1666
1658 self.interact(header)
1667 self.interact(header)
1659
1668
1660 # now, purge out the user namespace from anything we might have added
1669 # now, purge out the user namespace from anything we might have added
1661 # from the caller's local namespace
1670 # from the caller's local namespace
1662 delvar = self.user_ns.pop
1671 delvar = self.user_ns.pop
1663 for var in local_varnames:
1672 for var in local_varnames:
1664 delvar(var,None)
1673 delvar(var,None)
1665 # and clean builtins we may have overridden
1674 # and clean builtins we may have overridden
1666 self.clean_builtins()
1675 self.clean_builtins()
1667
1676
1668 def interact_prompt(self):
1677 def interact_prompt(self):
1669 """ Print the prompt (in read-eval-print loop)
1678 """ Print the prompt (in read-eval-print loop)
1670
1679
1671 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1680 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1672 used in standard IPython flow.
1681 used in standard IPython flow.
1673 """
1682 """
1674 if self.more:
1683 if self.more:
1675 try:
1684 try:
1676 prompt = self.hooks.generate_prompt(True)
1685 prompt = self.hooks.generate_prompt(True)
1677 except:
1686 except:
1678 self.showtraceback()
1687 self.showtraceback()
1679 if self.autoindent:
1688 if self.autoindent:
1680 self.rl_do_indent = True
1689 self.rl_do_indent = True
1681
1690
1682 else:
1691 else:
1683 try:
1692 try:
1684 prompt = self.hooks.generate_prompt(False)
1693 prompt = self.hooks.generate_prompt(False)
1685 except:
1694 except:
1686 self.showtraceback()
1695 self.showtraceback()
1687 self.write(prompt)
1696 self.write(prompt)
1688
1697
1689 def interact_handle_input(self,line):
1698 def interact_handle_input(self,line):
1690 """ Handle the input line (in read-eval-print loop)
1699 """ Handle the input line (in read-eval-print loop)
1691
1700
1692 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1701 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1693 used in standard IPython flow.
1702 used in standard IPython flow.
1694 """
1703 """
1695 if line.lstrip() == line:
1704 if line.lstrip() == line:
1696 self.shadowhist.add(line.strip())
1705 self.shadowhist.add(line.strip())
1697 lineout = self.prefilter(line,self.more)
1706 lineout = self.prefilter(line,self.more)
1698
1707
1699 if line.strip():
1708 if line.strip():
1700 if self.more:
1709 if self.more:
1701 self.input_hist_raw[-1] += '%s\n' % line
1710 self.input_hist_raw[-1] += '%s\n' % line
1702 else:
1711 else:
1703 self.input_hist_raw.append('%s\n' % line)
1712 self.input_hist_raw.append('%s\n' % line)
1704
1713
1705
1714
1706 self.more = self.push(lineout)
1715 self.more = self.push(lineout)
1707 if (self.SyntaxTB.last_syntax_error and
1716 if (self.SyntaxTB.last_syntax_error and
1708 self.rc.autoedit_syntax):
1717 self.rc.autoedit_syntax):
1709 self.edit_syntax_error()
1718 self.edit_syntax_error()
1710
1719
1711 def interact_with_readline(self):
1720 def interact_with_readline(self):
1712 """ Demo of using interact_handle_input, interact_prompt
1721 """ Demo of using interact_handle_input, interact_prompt
1713
1722
1714 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1723 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1715 it should work like this.
1724 it should work like this.
1716 """
1725 """
1717 self.readline_startup_hook(self.pre_readline)
1726 self.readline_startup_hook(self.pre_readline)
1718 while not self.exit_now:
1727 while not self.exit_now:
1719 self.interact_prompt()
1728 self.interact_prompt()
1720 if self.more:
1729 if self.more:
1721 self.rl_do_indent = True
1730 self.rl_do_indent = True
1722 else:
1731 else:
1723 self.rl_do_indent = False
1732 self.rl_do_indent = False
1724 line = raw_input_original().decode(self.stdin_encoding)
1733 line = raw_input_original().decode(self.stdin_encoding)
1725 self.interact_handle_input(line)
1734 self.interact_handle_input(line)
1726
1735
1727
1736
1728 def interact(self, banner=None):
1737 def interact(self, banner=None):
1729 """Closely emulate the interactive Python console.
1738 """Closely emulate the interactive Python console.
1730
1739
1731 The optional banner argument specify the banner to print
1740 The optional banner argument specify the banner to print
1732 before the first interaction; by default it prints a banner
1741 before the first interaction; by default it prints a banner
1733 similar to the one printed by the real Python interpreter,
1742 similar to the one printed by the real Python interpreter,
1734 followed by the current class name in parentheses (so as not
1743 followed by the current class name in parentheses (so as not
1735 to confuse this with the real interpreter -- since it's so
1744 to confuse this with the real interpreter -- since it's so
1736 close!).
1745 close!).
1737
1746
1738 """
1747 """
1739
1748
1740 if self.exit_now:
1749 if self.exit_now:
1741 # batch run -> do not interact
1750 # batch run -> do not interact
1742 return
1751 return
1743 cprt = 'Type "copyright", "credits" or "license" for more information.'
1752 cprt = 'Type "copyright", "credits" or "license" for more information.'
1744 if banner is None:
1753 if banner is None:
1745 self.write("Python %s on %s\n%s\n(%s)\n" %
1754 self.write("Python %s on %s\n%s\n(%s)\n" %
1746 (sys.version, sys.platform, cprt,
1755 (sys.version, sys.platform, cprt,
1747 self.__class__.__name__))
1756 self.__class__.__name__))
1748 else:
1757 else:
1749 self.write(banner)
1758 self.write(banner)
1750
1759
1751 more = 0
1760 more = 0
1752
1761
1753 # Mark activity in the builtins
1762 # Mark activity in the builtins
1754 __builtin__.__dict__['__IPYTHON__active'] += 1
1763 __builtin__.__dict__['__IPYTHON__active'] += 1
1755
1764
1756 if self.has_readline:
1765 if self.has_readline:
1757 self.readline_startup_hook(self.pre_readline)
1766 self.readline_startup_hook(self.pre_readline)
1758 # exit_now is set by a call to %Exit or %Quit, through the
1767 # exit_now is set by a call to %Exit or %Quit, through the
1759 # ask_exit callback.
1768 # ask_exit callback.
1760
1769
1761 while not self.exit_now:
1770 while not self.exit_now:
1762 self.hooks.pre_prompt_hook()
1771 self.hooks.pre_prompt_hook()
1763 if more:
1772 if more:
1764 try:
1773 try:
1765 prompt = self.hooks.generate_prompt(True)
1774 prompt = self.hooks.generate_prompt(True)
1766 except:
1775 except:
1767 self.showtraceback()
1776 self.showtraceback()
1768 if self.autoindent:
1777 if self.autoindent:
1769 self.rl_do_indent = True
1778 self.rl_do_indent = True
1770
1779
1771 else:
1780 else:
1772 try:
1781 try:
1773 prompt = self.hooks.generate_prompt(False)
1782 prompt = self.hooks.generate_prompt(False)
1774 except:
1783 except:
1775 self.showtraceback()
1784 self.showtraceback()
1776 try:
1785 try:
1777 line = self.raw_input(prompt,more)
1786 line = self.raw_input(prompt,more)
1778 if self.exit_now:
1787 if self.exit_now:
1779 # quick exit on sys.std[in|out] close
1788 # quick exit on sys.std[in|out] close
1780 break
1789 break
1781 if self.autoindent:
1790 if self.autoindent:
1782 self.rl_do_indent = False
1791 self.rl_do_indent = False
1783
1792
1784 except KeyboardInterrupt:
1793 except KeyboardInterrupt:
1785 #double-guard against keyboardinterrupts during kbdint handling
1794 #double-guard against keyboardinterrupts during kbdint handling
1786 try:
1795 try:
1787 self.write('\nKeyboardInterrupt\n')
1796 self.write('\nKeyboardInterrupt\n')
1788 self.resetbuffer()
1797 self.resetbuffer()
1789 # keep cache in sync with the prompt counter:
1798 # keep cache in sync with the prompt counter:
1790 self.outputcache.prompt_count -= 1
1799 self.outputcache.prompt_count -= 1
1791
1800
1792 if self.autoindent:
1801 if self.autoindent:
1793 self.indent_current_nsp = 0
1802 self.indent_current_nsp = 0
1794 more = 0
1803 more = 0
1795 except KeyboardInterrupt:
1804 except KeyboardInterrupt:
1796 pass
1805 pass
1797 except EOFError:
1806 except EOFError:
1798 if self.autoindent:
1807 if self.autoindent:
1799 self.rl_do_indent = False
1808 self.rl_do_indent = False
1800 self.readline_startup_hook(None)
1809 self.readline_startup_hook(None)
1801 self.write('\n')
1810 self.write('\n')
1802 self.exit()
1811 self.exit()
1803 except bdb.BdbQuit:
1812 except bdb.BdbQuit:
1804 warn('The Python debugger has exited with a BdbQuit exception.\n'
1813 warn('The Python debugger has exited with a BdbQuit exception.\n'
1805 'Because of how pdb handles the stack, it is impossible\n'
1814 'Because of how pdb handles the stack, it is impossible\n'
1806 'for IPython to properly format this particular exception.\n'
1815 'for IPython to properly format this particular exception.\n'
1807 'IPython will resume normal operation.')
1816 'IPython will resume normal operation.')
1808 except:
1817 except:
1809 # exceptions here are VERY RARE, but they can be triggered
1818 # exceptions here are VERY RARE, but they can be triggered
1810 # asynchronously by signal handlers, for example.
1819 # asynchronously by signal handlers, for example.
1811 self.showtraceback()
1820 self.showtraceback()
1812 else:
1821 else:
1813 more = self.push(line)
1822 more = self.push(line)
1814 if (self.SyntaxTB.last_syntax_error and
1823 if (self.SyntaxTB.last_syntax_error and
1815 self.rc.autoedit_syntax):
1824 self.rc.autoedit_syntax):
1816 self.edit_syntax_error()
1825 self.edit_syntax_error()
1817
1826
1818 # We are off again...
1827 # We are off again...
1819 __builtin__.__dict__['__IPYTHON__active'] -= 1
1828 __builtin__.__dict__['__IPYTHON__active'] -= 1
1820
1829
1821 def excepthook(self, etype, value, tb):
1830 def excepthook(self, etype, value, tb):
1822 """One more defense for GUI apps that call sys.excepthook.
1831 """One more defense for GUI apps that call sys.excepthook.
1823
1832
1824 GUI frameworks like wxPython trap exceptions and call
1833 GUI frameworks like wxPython trap exceptions and call
1825 sys.excepthook themselves. I guess this is a feature that
1834 sys.excepthook themselves. I guess this is a feature that
1826 enables them to keep running after exceptions that would
1835 enables them to keep running after exceptions that would
1827 otherwise kill their mainloop. This is a bother for IPython
1836 otherwise kill their mainloop. This is a bother for IPython
1828 which excepts to catch all of the program exceptions with a try:
1837 which excepts to catch all of the program exceptions with a try:
1829 except: statement.
1838 except: statement.
1830
1839
1831 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1840 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1832 any app directly invokes sys.excepthook, it will look to the user like
1841 any app directly invokes sys.excepthook, it will look to the user like
1833 IPython crashed. In order to work around this, we can disable the
1842 IPython crashed. In order to work around this, we can disable the
1834 CrashHandler and replace it with this excepthook instead, which prints a
1843 CrashHandler and replace it with this excepthook instead, which prints a
1835 regular traceback using our InteractiveTB. In this fashion, apps which
1844 regular traceback using our InteractiveTB. In this fashion, apps which
1836 call sys.excepthook will generate a regular-looking exception from
1845 call sys.excepthook will generate a regular-looking exception from
1837 IPython, and the CrashHandler will only be triggered by real IPython
1846 IPython, and the CrashHandler will only be triggered by real IPython
1838 crashes.
1847 crashes.
1839
1848
1840 This hook should be used sparingly, only in places which are not likely
1849 This hook should be used sparingly, only in places which are not likely
1841 to be true IPython errors.
1850 to be true IPython errors.
1842 """
1851 """
1843 self.showtraceback((etype,value,tb),tb_offset=0)
1852 self.showtraceback((etype,value,tb),tb_offset=0)
1844
1853
1845 def expand_aliases(self,fn,rest):
1854 def expand_aliases(self,fn,rest):
1846 """ Expand multiple levels of aliases:
1855 """ Expand multiple levels of aliases:
1847
1856
1848 if:
1857 if:
1849
1858
1850 alias foo bar /tmp
1859 alias foo bar /tmp
1851 alias baz foo
1860 alias baz foo
1852
1861
1853 then:
1862 then:
1854
1863
1855 baz huhhahhei -> bar /tmp huhhahhei
1864 baz huhhahhei -> bar /tmp huhhahhei
1856
1865
1857 """
1866 """
1858 line = fn + " " + rest
1867 line = fn + " " + rest
1859
1868
1860 done = Set()
1869 done = Set()
1861 while 1:
1870 while 1:
1862 pre,fn,rest = prefilter.splitUserInput(line,
1871 pre,fn,rest = prefilter.splitUserInput(line,
1863 prefilter.shell_line_split)
1872 prefilter.shell_line_split)
1864 if fn in self.alias_table:
1873 if fn in self.alias_table:
1865 if fn in done:
1874 if fn in done:
1866 warn("Cyclic alias definition, repeated '%s'" % fn)
1875 warn("Cyclic alias definition, repeated '%s'" % fn)
1867 return ""
1876 return ""
1868 done.add(fn)
1877 done.add(fn)
1869
1878
1870 l2 = self.transform_alias(fn,rest)
1879 l2 = self.transform_alias(fn,rest)
1871 # dir -> dir
1880 # dir -> dir
1872 # print "alias",line, "->",l2 #dbg
1881 # print "alias",line, "->",l2 #dbg
1873 if l2 == line:
1882 if l2 == line:
1874 break
1883 break
1875 # ls -> ls -F should not recurse forever
1884 # ls -> ls -F should not recurse forever
1876 if l2.split(None,1)[0] == line.split(None,1)[0]:
1885 if l2.split(None,1)[0] == line.split(None,1)[0]:
1877 line = l2
1886 line = l2
1878 break
1887 break
1879
1888
1880 line=l2
1889 line=l2
1881
1890
1882
1891
1883 # print "al expand to",line #dbg
1892 # print "al expand to",line #dbg
1884 else:
1893 else:
1885 break
1894 break
1886
1895
1887 return line
1896 return line
1888
1897
1889 def transform_alias(self, alias,rest=''):
1898 def transform_alias(self, alias,rest=''):
1890 """ Transform alias to system command string.
1899 """ Transform alias to system command string.
1891 """
1900 """
1892 trg = self.alias_table[alias]
1901 trg = self.alias_table[alias]
1893
1902
1894 nargs,cmd = trg
1903 nargs,cmd = trg
1895 # print trg #dbg
1904 # print trg #dbg
1896 if ' ' in cmd and os.path.isfile(cmd):
1905 if ' ' in cmd and os.path.isfile(cmd):
1897 cmd = '"%s"' % cmd
1906 cmd = '"%s"' % cmd
1898
1907
1899 # Expand the %l special to be the user's input line
1908 # Expand the %l special to be the user's input line
1900 if cmd.find('%l') >= 0:
1909 if cmd.find('%l') >= 0:
1901 cmd = cmd.replace('%l',rest)
1910 cmd = cmd.replace('%l',rest)
1902 rest = ''
1911 rest = ''
1903 if nargs==0:
1912 if nargs==0:
1904 # Simple, argument-less aliases
1913 # Simple, argument-less aliases
1905 cmd = '%s %s' % (cmd,rest)
1914 cmd = '%s %s' % (cmd,rest)
1906 else:
1915 else:
1907 # Handle aliases with positional arguments
1916 # Handle aliases with positional arguments
1908 args = rest.split(None,nargs)
1917 args = rest.split(None,nargs)
1909 if len(args)< nargs:
1918 if len(args)< nargs:
1910 error('Alias <%s> requires %s arguments, %s given.' %
1919 error('Alias <%s> requires %s arguments, %s given.' %
1911 (alias,nargs,len(args)))
1920 (alias,nargs,len(args)))
1912 return None
1921 return None
1913 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1922 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1914 # Now call the macro, evaluating in the user's namespace
1923 # Now call the macro, evaluating in the user's namespace
1915 #print 'new command: <%r>' % cmd # dbg
1924 #print 'new command: <%r>' % cmd # dbg
1916 return cmd
1925 return cmd
1917
1926
1918 def call_alias(self,alias,rest=''):
1927 def call_alias(self,alias,rest=''):
1919 """Call an alias given its name and the rest of the line.
1928 """Call an alias given its name and the rest of the line.
1920
1929
1921 This is only used to provide backwards compatibility for users of
1930 This is only used to provide backwards compatibility for users of
1922 ipalias(), use of which is not recommended for anymore."""
1931 ipalias(), use of which is not recommended for anymore."""
1923
1932
1924 # Now call the macro, evaluating in the user's namespace
1933 # Now call the macro, evaluating in the user's namespace
1925 cmd = self.transform_alias(alias, rest)
1934 cmd = self.transform_alias(alias, rest)
1926 try:
1935 try:
1927 self.system(cmd)
1936 self.system(cmd)
1928 except:
1937 except:
1929 self.showtraceback()
1938 self.showtraceback()
1930
1939
1931 def indent_current_str(self):
1940 def indent_current_str(self):
1932 """return the current level of indentation as a string"""
1941 """return the current level of indentation as a string"""
1933 return self.indent_current_nsp * ' '
1942 return self.indent_current_nsp * ' '
1934
1943
1935 def autoindent_update(self,line):
1944 def autoindent_update(self,line):
1936 """Keep track of the indent level."""
1945 """Keep track of the indent level."""
1937
1946
1938 #debugx('line')
1947 #debugx('line')
1939 #debugx('self.indent_current_nsp')
1948 #debugx('self.indent_current_nsp')
1940 if self.autoindent:
1949 if self.autoindent:
1941 if line:
1950 if line:
1942 inisp = num_ini_spaces(line)
1951 inisp = num_ini_spaces(line)
1943 if inisp < self.indent_current_nsp:
1952 if inisp < self.indent_current_nsp:
1944 self.indent_current_nsp = inisp
1953 self.indent_current_nsp = inisp
1945
1954
1946 if line[-1] == ':':
1955 if line[-1] == ':':
1947 self.indent_current_nsp += 4
1956 self.indent_current_nsp += 4
1948 elif dedent_re.match(line):
1957 elif dedent_re.match(line):
1949 self.indent_current_nsp -= 4
1958 self.indent_current_nsp -= 4
1950 else:
1959 else:
1951 self.indent_current_nsp = 0
1960 self.indent_current_nsp = 0
1952
1961
1953 def runlines(self,lines):
1962 def runlines(self,lines):
1954 """Run a string of one or more lines of source.
1963 """Run a string of one or more lines of source.
1955
1964
1956 This method is capable of running a string containing multiple source
1965 This method is capable of running a string containing multiple source
1957 lines, as if they had been entered at the IPython prompt. Since it
1966 lines, as if they had been entered at the IPython prompt. Since it
1958 exposes IPython's processing machinery, the given strings can contain
1967 exposes IPython's processing machinery, the given strings can contain
1959 magic calls (%magic), special shell access (!cmd), etc."""
1968 magic calls (%magic), special shell access (!cmd), etc."""
1960
1969
1961 # We must start with a clean buffer, in case this is run from an
1970 # We must start with a clean buffer, in case this is run from an
1962 # interactive IPython session (via a magic, for example).
1971 # interactive IPython session (via a magic, for example).
1963 self.resetbuffer()
1972 self.resetbuffer()
1964 lines = lines.split('\n')
1973 lines = lines.split('\n')
1965 more = 0
1974 more = 0
1966
1975
1967 for line in lines:
1976 for line in lines:
1968 # skip blank lines so we don't mess up the prompt counter, but do
1977 # skip blank lines so we don't mess up the prompt counter, but do
1969 # NOT skip even a blank line if we are in a code block (more is
1978 # NOT skip even a blank line if we are in a code block (more is
1970 # true)
1979 # true)
1971
1980
1972
1981
1973 if line or more:
1982 if line or more:
1974 # push to raw history, so hist line numbers stay in sync
1983 # push to raw history, so hist line numbers stay in sync
1975 self.input_hist_raw.append("# " + line + "\n")
1984 self.input_hist_raw.append("# " + line + "\n")
1976 more = self.push(self.prefilter(line,more))
1985 more = self.push(self.prefilter(line,more))
1977 # IPython's runsource returns None if there was an error
1986 # IPython's runsource returns None if there was an error
1978 # compiling the code. This allows us to stop processing right
1987 # compiling the code. This allows us to stop processing right
1979 # away, so the user gets the error message at the right place.
1988 # away, so the user gets the error message at the right place.
1980 if more is None:
1989 if more is None:
1981 break
1990 break
1982 else:
1991 else:
1983 self.input_hist_raw.append("\n")
1992 self.input_hist_raw.append("\n")
1984 # final newline in case the input didn't have it, so that the code
1993 # final newline in case the input didn't have it, so that the code
1985 # actually does get executed
1994 # actually does get executed
1986 if more:
1995 if more:
1987 self.push('\n')
1996 self.push('\n')
1988
1997
1989 def runsource(self, source, filename='<input>', symbol='single'):
1998 def runsource(self, source, filename='<input>', symbol='single'):
1990 """Compile and run some source in the interpreter.
1999 """Compile and run some source in the interpreter.
1991
2000
1992 Arguments are as for compile_command().
2001 Arguments are as for compile_command().
1993
2002
1994 One several things can happen:
2003 One several things can happen:
1995
2004
1996 1) The input is incorrect; compile_command() raised an
2005 1) The input is incorrect; compile_command() raised an
1997 exception (SyntaxError or OverflowError). A syntax traceback
2006 exception (SyntaxError or OverflowError). A syntax traceback
1998 will be printed by calling the showsyntaxerror() method.
2007 will be printed by calling the showsyntaxerror() method.
1999
2008
2000 2) The input is incomplete, and more input is required;
2009 2) The input is incomplete, and more input is required;
2001 compile_command() returned None. Nothing happens.
2010 compile_command() returned None. Nothing happens.
2002
2011
2003 3) The input is complete; compile_command() returned a code
2012 3) The input is complete; compile_command() returned a code
2004 object. The code is executed by calling self.runcode() (which
2013 object. The code is executed by calling self.runcode() (which
2005 also handles run-time exceptions, except for SystemExit).
2014 also handles run-time exceptions, except for SystemExit).
2006
2015
2007 The return value is:
2016 The return value is:
2008
2017
2009 - True in case 2
2018 - True in case 2
2010
2019
2011 - False in the other cases, unless an exception is raised, where
2020 - False in the other cases, unless an exception is raised, where
2012 None is returned instead. This can be used by external callers to
2021 None is returned instead. This can be used by external callers to
2013 know whether to continue feeding input or not.
2022 know whether to continue feeding input or not.
2014
2023
2015 The return value can be used to decide whether to use sys.ps1 or
2024 The return value can be used to decide whether to use sys.ps1 or
2016 sys.ps2 to prompt the next line."""
2025 sys.ps2 to prompt the next line."""
2017
2026
2018 # if the source code has leading blanks, add 'if 1:\n' to it
2027 # if the source code has leading blanks, add 'if 1:\n' to it
2019 # this allows execution of indented pasted code. It is tempting
2028 # this allows execution of indented pasted code. It is tempting
2020 # to add '\n' at the end of source to run commands like ' a=1'
2029 # to add '\n' at the end of source to run commands like ' a=1'
2021 # directly, but this fails for more complicated scenarios
2030 # directly, but this fails for more complicated scenarios
2022 source=source.encode(self.stdin_encoding)
2031 source=source.encode(self.stdin_encoding)
2023 if source[:1] in [' ', '\t']:
2032 if source[:1] in [' ', '\t']:
2024 source = 'if 1:\n%s' % source
2033 source = 'if 1:\n%s' % source
2025
2034
2026 try:
2035 try:
2027 code = self.compile(source,filename,symbol)
2036 code = self.compile(source,filename,symbol)
2028 except (OverflowError, SyntaxError, ValueError, TypeError):
2037 except (OverflowError, SyntaxError, ValueError, TypeError):
2029 # Case 1
2038 # Case 1
2030 self.showsyntaxerror(filename)
2039 self.showsyntaxerror(filename)
2031 return None
2040 return None
2032
2041
2033 if code is None:
2042 if code is None:
2034 # Case 2
2043 # Case 2
2035 return True
2044 return True
2036
2045
2037 # Case 3
2046 # Case 3
2038 # We store the code object so that threaded shells and
2047 # We store the code object so that threaded shells and
2039 # custom exception handlers can access all this info if needed.
2048 # custom exception handlers can access all this info if needed.
2040 # The source corresponding to this can be obtained from the
2049 # The source corresponding to this can be obtained from the
2041 # buffer attribute as '\n'.join(self.buffer).
2050 # buffer attribute as '\n'.join(self.buffer).
2042 self.code_to_run = code
2051 self.code_to_run = code
2043 # now actually execute the code object
2052 # now actually execute the code object
2044 if self.runcode(code) == 0:
2053 if self.runcode(code) == 0:
2045 return False
2054 return False
2046 else:
2055 else:
2047 return None
2056 return None
2048
2057
2049 def runcode(self,code_obj):
2058 def runcode(self,code_obj):
2050 """Execute a code object.
2059 """Execute a code object.
2051
2060
2052 When an exception occurs, self.showtraceback() is called to display a
2061 When an exception occurs, self.showtraceback() is called to display a
2053 traceback.
2062 traceback.
2054
2063
2055 Return value: a flag indicating whether the code to be run completed
2064 Return value: a flag indicating whether the code to be run completed
2056 successfully:
2065 successfully:
2057
2066
2058 - 0: successful execution.
2067 - 0: successful execution.
2059 - 1: an error occurred.
2068 - 1: an error occurred.
2060 """
2069 """
2061
2070
2062 # Set our own excepthook in case the user code tries to call it
2071 # Set our own excepthook in case the user code tries to call it
2063 # directly, so that the IPython crash handler doesn't get triggered
2072 # directly, so that the IPython crash handler doesn't get triggered
2064 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2073 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2065
2074
2066 # we save the original sys.excepthook in the instance, in case config
2075 # we save the original sys.excepthook in the instance, in case config
2067 # code (such as magics) needs access to it.
2076 # code (such as magics) needs access to it.
2068 self.sys_excepthook = old_excepthook
2077 self.sys_excepthook = old_excepthook
2069 outflag = 1 # happens in more places, so it's easier as default
2078 outflag = 1 # happens in more places, so it's easier as default
2070 try:
2079 try:
2071 try:
2080 try:
2072 self.hooks.pre_runcode_hook()
2081 self.hooks.pre_runcode_hook()
2073 exec code_obj in self.user_global_ns, self.user_ns
2082 exec code_obj in self.user_global_ns, self.user_ns
2074 finally:
2083 finally:
2075 # Reset our crash handler in place
2084 # Reset our crash handler in place
2076 sys.excepthook = old_excepthook
2085 sys.excepthook = old_excepthook
2077 except SystemExit:
2086 except SystemExit:
2078 self.resetbuffer()
2087 self.resetbuffer()
2079 self.showtraceback()
2088 self.showtraceback()
2080 warn("Type %exit or %quit to exit IPython "
2089 warn("Type %exit or %quit to exit IPython "
2081 "(%Exit or %Quit do so unconditionally).",level=1)
2090 "(%Exit or %Quit do so unconditionally).",level=1)
2082 except self.custom_exceptions:
2091 except self.custom_exceptions:
2083 etype,value,tb = sys.exc_info()
2092 etype,value,tb = sys.exc_info()
2084 self.CustomTB(etype,value,tb)
2093 self.CustomTB(etype,value,tb)
2085 except:
2094 except:
2086 self.showtraceback()
2095 self.showtraceback()
2087 else:
2096 else:
2088 outflag = 0
2097 outflag = 0
2089 if softspace(sys.stdout, 0):
2098 if softspace(sys.stdout, 0):
2090 print
2099 print
2091 # Flush out code object which has been run (and source)
2100 # Flush out code object which has been run (and source)
2092 self.code_to_run = None
2101 self.code_to_run = None
2093 return outflag
2102 return outflag
2094
2103
2095 def push(self, line):
2104 def push(self, line):
2096 """Push a line to the interpreter.
2105 """Push a line to the interpreter.
2097
2106
2098 The line should not have a trailing newline; it may have
2107 The line should not have a trailing newline; it may have
2099 internal newlines. The line is appended to a buffer and the
2108 internal newlines. The line is appended to a buffer and the
2100 interpreter's runsource() method is called with the
2109 interpreter's runsource() method is called with the
2101 concatenated contents of the buffer as source. If this
2110 concatenated contents of the buffer as source. If this
2102 indicates that the command was executed or invalid, the buffer
2111 indicates that the command was executed or invalid, the buffer
2103 is reset; otherwise, the command is incomplete, and the buffer
2112 is reset; otherwise, the command is incomplete, and the buffer
2104 is left as it was after the line was appended. The return
2113 is left as it was after the line was appended. The return
2105 value is 1 if more input is required, 0 if the line was dealt
2114 value is 1 if more input is required, 0 if the line was dealt
2106 with in some way (this is the same as runsource()).
2115 with in some way (this is the same as runsource()).
2107 """
2116 """
2108
2117
2109 # autoindent management should be done here, and not in the
2118 # autoindent management should be done here, and not in the
2110 # interactive loop, since that one is only seen by keyboard input. We
2119 # interactive loop, since that one is only seen by keyboard input. We
2111 # need this done correctly even for code run via runlines (which uses
2120 # need this done correctly even for code run via runlines (which uses
2112 # push).
2121 # push).
2113
2122
2114 #print 'push line: <%s>' % line # dbg
2123 #print 'push line: <%s>' % line # dbg
2115 for subline in line.splitlines():
2124 for subline in line.splitlines():
2116 self.autoindent_update(subline)
2125 self.autoindent_update(subline)
2117 self.buffer.append(line)
2126 self.buffer.append(line)
2118 more = self.runsource('\n'.join(self.buffer), self.filename)
2127 more = self.runsource('\n'.join(self.buffer), self.filename)
2119 if not more:
2128 if not more:
2120 self.resetbuffer()
2129 self.resetbuffer()
2121 return more
2130 return more
2122
2131
2123 def split_user_input(self, line):
2132 def split_user_input(self, line):
2124 # This is really a hold-over to support ipapi and some extensions
2133 # This is really a hold-over to support ipapi and some extensions
2125 return prefilter.splitUserInput(line)
2134 return prefilter.splitUserInput(line)
2126
2135
2127 def resetbuffer(self):
2136 def resetbuffer(self):
2128 """Reset the input buffer."""
2137 """Reset the input buffer."""
2129 self.buffer[:] = []
2138 self.buffer[:] = []
2130
2139
2131 def raw_input(self,prompt='',continue_prompt=False):
2140 def raw_input(self,prompt='',continue_prompt=False):
2132 """Write a prompt and read a line.
2141 """Write a prompt and read a line.
2133
2142
2134 The returned line does not include the trailing newline.
2143 The returned line does not include the trailing newline.
2135 When the user enters the EOF key sequence, EOFError is raised.
2144 When the user enters the EOF key sequence, EOFError is raised.
2136
2145
2137 Optional inputs:
2146 Optional inputs:
2138
2147
2139 - prompt(''): a string to be printed to prompt the user.
2148 - prompt(''): a string to be printed to prompt the user.
2140
2149
2141 - continue_prompt(False): whether this line is the first one or a
2150 - continue_prompt(False): whether this line is the first one or a
2142 continuation in a sequence of inputs.
2151 continuation in a sequence of inputs.
2143 """
2152 """
2144
2153
2145 # Code run by the user may have modified the readline completer state.
2154 # Code run by the user may have modified the readline completer state.
2146 # We must ensure that our completer is back in place.
2155 # We must ensure that our completer is back in place.
2147 if self.has_readline:
2156 if self.has_readline:
2148 self.set_completer()
2157 self.set_completer()
2149
2158
2150 try:
2159 try:
2151 line = raw_input_original(prompt).decode(self.stdin_encoding)
2160 line = raw_input_original(prompt).decode(self.stdin_encoding)
2152 except ValueError:
2161 except ValueError:
2153 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2162 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2154 " or sys.stdout.close()!\nExiting IPython!")
2163 " or sys.stdout.close()!\nExiting IPython!")
2155 self.ask_exit()
2164 self.ask_exit()
2156 return ""
2165 return ""
2157
2166
2158 # Try to be reasonably smart about not re-indenting pasted input more
2167 # Try to be reasonably smart about not re-indenting pasted input more
2159 # than necessary. We do this by trimming out the auto-indent initial
2168 # than necessary. We do this by trimming out the auto-indent initial
2160 # spaces, if the user's actual input started itself with whitespace.
2169 # spaces, if the user's actual input started itself with whitespace.
2161 #debugx('self.buffer[-1]')
2170 #debugx('self.buffer[-1]')
2162
2171
2163 if self.autoindent:
2172 if self.autoindent:
2164 if num_ini_spaces(line) > self.indent_current_nsp:
2173 if num_ini_spaces(line) > self.indent_current_nsp:
2165 line = line[self.indent_current_nsp:]
2174 line = line[self.indent_current_nsp:]
2166 self.indent_current_nsp = 0
2175 self.indent_current_nsp = 0
2167
2176
2168 # store the unfiltered input before the user has any chance to modify
2177 # store the unfiltered input before the user has any chance to modify
2169 # it.
2178 # it.
2170 if line.strip():
2179 if line.strip():
2171 if continue_prompt:
2180 if continue_prompt:
2172 self.input_hist_raw[-1] += '%s\n' % line
2181 self.input_hist_raw[-1] += '%s\n' % line
2173 if self.has_readline: # and some config option is set?
2182 if self.has_readline: # and some config option is set?
2174 try:
2183 try:
2175 histlen = self.readline.get_current_history_length()
2184 histlen = self.readline.get_current_history_length()
2176 if histlen > 1:
2185 if histlen > 1:
2177 newhist = self.input_hist_raw[-1].rstrip()
2186 newhist = self.input_hist_raw[-1].rstrip()
2178 self.readline.remove_history_item(histlen-1)
2187 self.readline.remove_history_item(histlen-1)
2179 self.readline.replace_history_item(histlen-2,
2188 self.readline.replace_history_item(histlen-2,
2180 newhist.encode(self.stdin_encoding))
2189 newhist.encode(self.stdin_encoding))
2181 except AttributeError:
2190 except AttributeError:
2182 pass # re{move,place}_history_item are new in 2.4.
2191 pass # re{move,place}_history_item are new in 2.4.
2183 else:
2192 else:
2184 self.input_hist_raw.append('%s\n' % line)
2193 self.input_hist_raw.append('%s\n' % line)
2185 # only entries starting at first column go to shadow history
2194 # only entries starting at first column go to shadow history
2186 if line.lstrip() == line:
2195 if line.lstrip() == line:
2187 self.shadowhist.add(line.strip())
2196 self.shadowhist.add(line.strip())
2188 elif not continue_prompt:
2197 elif not continue_prompt:
2189 self.input_hist_raw.append('\n')
2198 self.input_hist_raw.append('\n')
2190 try:
2199 try:
2191 lineout = self.prefilter(line,continue_prompt)
2200 lineout = self.prefilter(line,continue_prompt)
2192 except:
2201 except:
2193 # blanket except, in case a user-defined prefilter crashes, so it
2202 # blanket except, in case a user-defined prefilter crashes, so it
2194 # can't take all of ipython with it.
2203 # can't take all of ipython with it.
2195 self.showtraceback()
2204 self.showtraceback()
2196 return ''
2205 return ''
2197 else:
2206 else:
2198 return lineout
2207 return lineout
2199
2208
2200 def _prefilter(self, line, continue_prompt):
2209 def _prefilter(self, line, continue_prompt):
2201 """Calls different preprocessors, depending on the form of line."""
2210 """Calls different preprocessors, depending on the form of line."""
2202
2211
2203 # All handlers *must* return a value, even if it's blank ('').
2212 # All handlers *must* return a value, even if it's blank ('').
2204
2213
2205 # Lines are NOT logged here. Handlers should process the line as
2214 # Lines are NOT logged here. Handlers should process the line as
2206 # needed, update the cache AND log it (so that the input cache array
2215 # needed, update the cache AND log it (so that the input cache array
2207 # stays synced).
2216 # stays synced).
2208
2217
2209 #.....................................................................
2218 #.....................................................................
2210 # Code begins
2219 # Code begins
2211
2220
2212 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2221 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2213
2222
2214 # save the line away in case we crash, so the post-mortem handler can
2223 # save the line away in case we crash, so the post-mortem handler can
2215 # record it
2224 # record it
2216 self._last_input_line = line
2225 self._last_input_line = line
2217
2226
2218 #print '***line: <%s>' % line # dbg
2227 #print '***line: <%s>' % line # dbg
2219
2228
2220 if not line:
2229 if not line:
2221 # Return immediately on purely empty lines, so that if the user
2230 # Return immediately on purely empty lines, so that if the user
2222 # previously typed some whitespace that started a continuation
2231 # previously typed some whitespace that started a continuation
2223 # prompt, he can break out of that loop with just an empty line.
2232 # prompt, he can break out of that loop with just an empty line.
2224 # This is how the default python prompt works.
2233 # This is how the default python prompt works.
2225
2234
2226 # Only return if the accumulated input buffer was just whitespace!
2235 # Only return if the accumulated input buffer was just whitespace!
2227 if ''.join(self.buffer).isspace():
2236 if ''.join(self.buffer).isspace():
2228 self.buffer[:] = []
2237 self.buffer[:] = []
2229 return ''
2238 return ''
2230
2239
2231 line_info = prefilter.LineInfo(line, continue_prompt)
2240 line_info = prefilter.LineInfo(line, continue_prompt)
2232
2241
2233 # the input history needs to track even empty lines
2242 # the input history needs to track even empty lines
2234 stripped = line.strip()
2243 stripped = line.strip()
2235
2244
2236 if not stripped:
2245 if not stripped:
2237 if not continue_prompt:
2246 if not continue_prompt:
2238 self.outputcache.prompt_count -= 1
2247 self.outputcache.prompt_count -= 1
2239 return self.handle_normal(line_info)
2248 return self.handle_normal(line_info)
2240
2249
2241 # print '***cont',continue_prompt # dbg
2250 # print '***cont',continue_prompt # dbg
2242 # special handlers are only allowed for single line statements
2251 # special handlers are only allowed for single line statements
2243 if continue_prompt and not self.rc.multi_line_specials:
2252 if continue_prompt and not self.rc.multi_line_specials:
2244 return self.handle_normal(line_info)
2253 return self.handle_normal(line_info)
2245
2254
2246
2255
2247 # See whether any pre-existing handler can take care of it
2256 # See whether any pre-existing handler can take care of it
2248 rewritten = self.hooks.input_prefilter(stripped)
2257 rewritten = self.hooks.input_prefilter(stripped)
2249 if rewritten != stripped: # ok, some prefilter did something
2258 if rewritten != stripped: # ok, some prefilter did something
2250 rewritten = line_info.pre + rewritten # add indentation
2259 rewritten = line_info.pre + rewritten # add indentation
2251 return self.handle_normal(prefilter.LineInfo(rewritten,
2260 return self.handle_normal(prefilter.LineInfo(rewritten,
2252 continue_prompt))
2261 continue_prompt))
2253
2262
2254 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2263 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2255
2264
2256 return prefilter.prefilter(line_info, self)
2265 return prefilter.prefilter(line_info, self)
2257
2266
2258
2267
2259 def _prefilter_dumb(self, line, continue_prompt):
2268 def _prefilter_dumb(self, line, continue_prompt):
2260 """simple prefilter function, for debugging"""
2269 """simple prefilter function, for debugging"""
2261 return self.handle_normal(line,continue_prompt)
2270 return self.handle_normal(line,continue_prompt)
2262
2271
2263
2272
2264 def multiline_prefilter(self, line, continue_prompt):
2273 def multiline_prefilter(self, line, continue_prompt):
2265 """ Run _prefilter for each line of input
2274 """ Run _prefilter for each line of input
2266
2275
2267 Covers cases where there are multiple lines in the user entry,
2276 Covers cases where there are multiple lines in the user entry,
2268 which is the case when the user goes back to a multiline history
2277 which is the case when the user goes back to a multiline history
2269 entry and presses enter.
2278 entry and presses enter.
2270
2279
2271 """
2280 """
2272 out = []
2281 out = []
2273 for l in line.rstrip('\n').split('\n'):
2282 for l in line.rstrip('\n').split('\n'):
2274 out.append(self._prefilter(l, continue_prompt))
2283 out.append(self._prefilter(l, continue_prompt))
2275 return '\n'.join(out)
2284 return '\n'.join(out)
2276
2285
2277 # Set the default prefilter() function (this can be user-overridden)
2286 # Set the default prefilter() function (this can be user-overridden)
2278 prefilter = multiline_prefilter
2287 prefilter = multiline_prefilter
2279
2288
2280 def handle_normal(self,line_info):
2289 def handle_normal(self,line_info):
2281 """Handle normal input lines. Use as a template for handlers."""
2290 """Handle normal input lines. Use as a template for handlers."""
2282
2291
2283 # With autoindent on, we need some way to exit the input loop, and I
2292 # With autoindent on, we need some way to exit the input loop, and I
2284 # don't want to force the user to have to backspace all the way to
2293 # don't want to force the user to have to backspace all the way to
2285 # clear the line. The rule will be in this case, that either two
2294 # clear the line. The rule will be in this case, that either two
2286 # lines of pure whitespace in a row, or a line of pure whitespace but
2295 # lines of pure whitespace in a row, or a line of pure whitespace but
2287 # of a size different to the indent level, will exit the input loop.
2296 # of a size different to the indent level, will exit the input loop.
2288 line = line_info.line
2297 line = line_info.line
2289 continue_prompt = line_info.continue_prompt
2298 continue_prompt = line_info.continue_prompt
2290
2299
2291 if (continue_prompt and self.autoindent and line.isspace() and
2300 if (continue_prompt and self.autoindent and line.isspace() and
2292 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2301 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2293 (self.buffer[-1]).isspace() )):
2302 (self.buffer[-1]).isspace() )):
2294 line = ''
2303 line = ''
2295
2304
2296 self.log(line,line,continue_prompt)
2305 self.log(line,line,continue_prompt)
2297 return line
2306 return line
2298
2307
2299 def handle_alias(self,line_info):
2308 def handle_alias(self,line_info):
2300 """Handle alias input lines. """
2309 """Handle alias input lines. """
2301 tgt = self.alias_table[line_info.iFun]
2310 tgt = self.alias_table[line_info.iFun]
2302 # print "=>",tgt #dbg
2311 # print "=>",tgt #dbg
2303 if callable(tgt):
2312 if callable(tgt):
2304 if '$' in line_info.line:
2313 if '$' in line_info.line:
2305 call_meth = '(_ip, _ip.itpl(%s))'
2314 call_meth = '(_ip, _ip.itpl(%s))'
2306 else:
2315 else:
2307 call_meth = '(_ip,%s)'
2316 call_meth = '(_ip,%s)'
2308 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2317 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2309 line_info.iFun,
2318 line_info.iFun,
2310 make_quoted_expr(line_info.line))
2319 make_quoted_expr(line_info.line))
2311 else:
2320 else:
2312 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2321 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2313
2322
2314 # pre is needed, because it carries the leading whitespace. Otherwise
2323 # pre is needed, because it carries the leading whitespace. Otherwise
2315 # aliases won't work in indented sections.
2324 # aliases won't work in indented sections.
2316 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2325 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2317 make_quoted_expr( transformed ))
2326 make_quoted_expr( transformed ))
2318
2327
2319 self.log(line_info.line,line_out,line_info.continue_prompt)
2328 self.log(line_info.line,line_out,line_info.continue_prompt)
2320 #print 'line out:',line_out # dbg
2329 #print 'line out:',line_out # dbg
2321 return line_out
2330 return line_out
2322
2331
2323 def handle_shell_escape(self, line_info):
2332 def handle_shell_escape(self, line_info):
2324 """Execute the line in a shell, empty return value"""
2333 """Execute the line in a shell, empty return value"""
2325 #print 'line in :', `line` # dbg
2334 #print 'line in :', `line` # dbg
2326 line = line_info.line
2335 line = line_info.line
2327 if line.lstrip().startswith('!!'):
2336 if line.lstrip().startswith('!!'):
2328 # rewrite LineInfo's line, iFun and theRest to properly hold the
2337 # rewrite LineInfo's line, iFun and theRest to properly hold the
2329 # call to %sx and the actual command to be executed, so
2338 # call to %sx and the actual command to be executed, so
2330 # handle_magic can work correctly. Note that this works even if
2339 # handle_magic can work correctly. Note that this works even if
2331 # the line is indented, so it handles multi_line_specials
2340 # the line is indented, so it handles multi_line_specials
2332 # properly.
2341 # properly.
2333 new_rest = line.lstrip()[2:]
2342 new_rest = line.lstrip()[2:]
2334 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2343 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2335 line_info.iFun = 'sx'
2344 line_info.iFun = 'sx'
2336 line_info.theRest = new_rest
2345 line_info.theRest = new_rest
2337 return self.handle_magic(line_info)
2346 return self.handle_magic(line_info)
2338 else:
2347 else:
2339 cmd = line.lstrip().lstrip('!')
2348 cmd = line.lstrip().lstrip('!')
2340 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2349 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2341 make_quoted_expr(cmd))
2350 make_quoted_expr(cmd))
2342 # update cache/log and return
2351 # update cache/log and return
2343 self.log(line,line_out,line_info.continue_prompt)
2352 self.log(line,line_out,line_info.continue_prompt)
2344 return line_out
2353 return line_out
2345
2354
2346 def handle_magic(self, line_info):
2355 def handle_magic(self, line_info):
2347 """Execute magic functions."""
2356 """Execute magic functions."""
2348 iFun = line_info.iFun
2357 iFun = line_info.iFun
2349 theRest = line_info.theRest
2358 theRest = line_info.theRest
2350 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2359 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2351 make_quoted_expr(iFun + " " + theRest))
2360 make_quoted_expr(iFun + " " + theRest))
2352 self.log(line_info.line,cmd,line_info.continue_prompt)
2361 self.log(line_info.line,cmd,line_info.continue_prompt)
2353 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2362 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2354 return cmd
2363 return cmd
2355
2364
2356 def handle_auto(self, line_info):
2365 def handle_auto(self, line_info):
2357 """Hande lines which can be auto-executed, quoting if requested."""
2366 """Hande lines which can be auto-executed, quoting if requested."""
2358
2367
2359 line = line_info.line
2368 line = line_info.line
2360 iFun = line_info.iFun
2369 iFun = line_info.iFun
2361 theRest = line_info.theRest
2370 theRest = line_info.theRest
2362 pre = line_info.pre
2371 pre = line_info.pre
2363 continue_prompt = line_info.continue_prompt
2372 continue_prompt = line_info.continue_prompt
2364 obj = line_info.ofind(self)['obj']
2373 obj = line_info.ofind(self)['obj']
2365
2374
2366 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2375 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2367
2376
2368 # This should only be active for single-line input!
2377 # This should only be active for single-line input!
2369 if continue_prompt:
2378 if continue_prompt:
2370 self.log(line,line,continue_prompt)
2379 self.log(line,line,continue_prompt)
2371 return line
2380 return line
2372
2381
2373 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2382 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2374 auto_rewrite = True
2383 auto_rewrite = True
2375
2384
2376 if pre == self.ESC_QUOTE:
2385 if pre == self.ESC_QUOTE:
2377 # Auto-quote splitting on whitespace
2386 # Auto-quote splitting on whitespace
2378 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2387 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2379 elif pre == self.ESC_QUOTE2:
2388 elif pre == self.ESC_QUOTE2:
2380 # Auto-quote whole string
2389 # Auto-quote whole string
2381 newcmd = '%s("%s")' % (iFun,theRest)
2390 newcmd = '%s("%s")' % (iFun,theRest)
2382 elif pre == self.ESC_PAREN:
2391 elif pre == self.ESC_PAREN:
2383 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2392 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2384 else:
2393 else:
2385 # Auto-paren.
2394 # Auto-paren.
2386 # We only apply it to argument-less calls if the autocall
2395 # We only apply it to argument-less calls if the autocall
2387 # parameter is set to 2. We only need to check that autocall is <
2396 # parameter is set to 2. We only need to check that autocall is <
2388 # 2, since this function isn't called unless it's at least 1.
2397 # 2, since this function isn't called unless it's at least 1.
2389 if not theRest and (self.rc.autocall < 2) and not force_auto:
2398 if not theRest and (self.rc.autocall < 2) and not force_auto:
2390 newcmd = '%s %s' % (iFun,theRest)
2399 newcmd = '%s %s' % (iFun,theRest)
2391 auto_rewrite = False
2400 auto_rewrite = False
2392 else:
2401 else:
2393 if not force_auto and theRest.startswith('['):
2402 if not force_auto and theRest.startswith('['):
2394 if hasattr(obj,'__getitem__'):
2403 if hasattr(obj,'__getitem__'):
2395 # Don't autocall in this case: item access for an object
2404 # Don't autocall in this case: item access for an object
2396 # which is BOTH callable and implements __getitem__.
2405 # which is BOTH callable and implements __getitem__.
2397 newcmd = '%s %s' % (iFun,theRest)
2406 newcmd = '%s %s' % (iFun,theRest)
2398 auto_rewrite = False
2407 auto_rewrite = False
2399 else:
2408 else:
2400 # if the object doesn't support [] access, go ahead and
2409 # if the object doesn't support [] access, go ahead and
2401 # autocall
2410 # autocall
2402 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2411 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2403 elif theRest.endswith(';'):
2412 elif theRest.endswith(';'):
2404 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2413 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2405 else:
2414 else:
2406 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2415 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2407
2416
2408 if auto_rewrite:
2417 if auto_rewrite:
2409 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2418 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2410
2419
2411 try:
2420 try:
2412 # plain ascii works better w/ pyreadline, on some machines, so
2421 # plain ascii works better w/ pyreadline, on some machines, so
2413 # we use it and only print uncolored rewrite if we have unicode
2422 # we use it and only print uncolored rewrite if we have unicode
2414 rw = str(rw)
2423 rw = str(rw)
2415 print >>Term.cout, rw
2424 print >>Term.cout, rw
2416 except UnicodeEncodeError:
2425 except UnicodeEncodeError:
2417 print "-------------->" + newcmd
2426 print "-------------->" + newcmd
2418
2427
2419 # log what is now valid Python, not the actual user input (without the
2428 # log what is now valid Python, not the actual user input (without the
2420 # final newline)
2429 # final newline)
2421 self.log(line,newcmd,continue_prompt)
2430 self.log(line,newcmd,continue_prompt)
2422 return newcmd
2431 return newcmd
2423
2432
2424 def handle_help(self, line_info):
2433 def handle_help(self, line_info):
2425 """Try to get some help for the object.
2434 """Try to get some help for the object.
2426
2435
2427 obj? or ?obj -> basic information.
2436 obj? or ?obj -> basic information.
2428 obj?? or ??obj -> more details.
2437 obj?? or ??obj -> more details.
2429 """
2438 """
2430
2439
2431 line = line_info.line
2440 line = line_info.line
2432 # We need to make sure that we don't process lines which would be
2441 # We need to make sure that we don't process lines which would be
2433 # otherwise valid python, such as "x=1 # what?"
2442 # otherwise valid python, such as "x=1 # what?"
2434 try:
2443 try:
2435 codeop.compile_command(line)
2444 codeop.compile_command(line)
2436 except SyntaxError:
2445 except SyntaxError:
2437 # We should only handle as help stuff which is NOT valid syntax
2446 # We should only handle as help stuff which is NOT valid syntax
2438 if line[0]==self.ESC_HELP:
2447 if line[0]==self.ESC_HELP:
2439 line = line[1:]
2448 line = line[1:]
2440 elif line[-1]==self.ESC_HELP:
2449 elif line[-1]==self.ESC_HELP:
2441 line = line[:-1]
2450 line = line[:-1]
2442 self.log(line,'#?'+line,line_info.continue_prompt)
2451 self.log(line,'#?'+line,line_info.continue_prompt)
2443 if line:
2452 if line:
2444 #print 'line:<%r>' % line # dbg
2453 #print 'line:<%r>' % line # dbg
2445 self.magic_pinfo(line)
2454 self.magic_pinfo(line)
2446 else:
2455 else:
2447 page(self.usage,screen_lines=self.rc.screen_length)
2456 page(self.usage,screen_lines=self.rc.screen_length)
2448 return '' # Empty string is needed here!
2457 return '' # Empty string is needed here!
2449 except:
2458 except:
2450 # Pass any other exceptions through to the normal handler
2459 # Pass any other exceptions through to the normal handler
2451 return self.handle_normal(line_info)
2460 return self.handle_normal(line_info)
2452 else:
2461 else:
2453 # If the code compiles ok, we should handle it normally
2462 # If the code compiles ok, we should handle it normally
2454 return self.handle_normal(line_info)
2463 return self.handle_normal(line_info)
2455
2464
2456 def getapi(self):
2465 def getapi(self):
2457 """ Get an IPApi object for this shell instance
2466 """ Get an IPApi object for this shell instance
2458
2467
2459 Getting an IPApi object is always preferable to accessing the shell
2468 Getting an IPApi object is always preferable to accessing the shell
2460 directly, but this holds true especially for extensions.
2469 directly, but this holds true especially for extensions.
2461
2470
2462 It should always be possible to implement an extension with IPApi
2471 It should always be possible to implement an extension with IPApi
2463 alone. If not, contact maintainer to request an addition.
2472 alone. If not, contact maintainer to request an addition.
2464
2473
2465 """
2474 """
2466 return self.api
2475 return self.api
2467
2476
2468 def handle_emacs(self, line_info):
2477 def handle_emacs(self, line_info):
2469 """Handle input lines marked by python-mode."""
2478 """Handle input lines marked by python-mode."""
2470
2479
2471 # Currently, nothing is done. Later more functionality can be added
2480 # Currently, nothing is done. Later more functionality can be added
2472 # here if needed.
2481 # here if needed.
2473
2482
2474 # The input cache shouldn't be updated
2483 # The input cache shouldn't be updated
2475 return line_info.line
2484 return line_info.line
2476
2485
2477
2486
2478 def mktempfile(self,data=None):
2487 def mktempfile(self,data=None):
2479 """Make a new tempfile and return its filename.
2488 """Make a new tempfile and return its filename.
2480
2489
2481 This makes a call to tempfile.mktemp, but it registers the created
2490 This makes a call to tempfile.mktemp, but it registers the created
2482 filename internally so ipython cleans it up at exit time.
2491 filename internally so ipython cleans it up at exit time.
2483
2492
2484 Optional inputs:
2493 Optional inputs:
2485
2494
2486 - data(None): if data is given, it gets written out to the temp file
2495 - data(None): if data is given, it gets written out to the temp file
2487 immediately, and the file is closed again."""
2496 immediately, and the file is closed again."""
2488
2497
2489 filename = tempfile.mktemp('.py','ipython_edit_')
2498 filename = tempfile.mktemp('.py','ipython_edit_')
2490 self.tempfiles.append(filename)
2499 self.tempfiles.append(filename)
2491
2500
2492 if data:
2501 if data:
2493 tmp_file = open(filename,'w')
2502 tmp_file = open(filename,'w')
2494 tmp_file.write(data)
2503 tmp_file.write(data)
2495 tmp_file.close()
2504 tmp_file.close()
2496 return filename
2505 return filename
2497
2506
2498 def write(self,data):
2507 def write(self,data):
2499 """Write a string to the default output"""
2508 """Write a string to the default output"""
2500 Term.cout.write(data)
2509 Term.cout.write(data)
2501
2510
2502 def write_err(self,data):
2511 def write_err(self,data):
2503 """Write a string to the default error output"""
2512 """Write a string to the default error output"""
2504 Term.cerr.write(data)
2513 Term.cerr.write(data)
2505
2514
2506 def ask_exit(self):
2515 def ask_exit(self):
2507 """ Call for exiting. Can be overiden and used as a callback. """
2516 """ Call for exiting. Can be overiden and used as a callback. """
2508 self.exit_now = True
2517 self.exit_now = True
2509
2518
2510 def exit(self):
2519 def exit(self):
2511 """Handle interactive exit.
2520 """Handle interactive exit.
2512
2521
2513 This method calls the ask_exit callback."""
2522 This method calls the ask_exit callback."""
2514
2523
2515 if self.rc.confirm_exit:
2524 if self.rc.confirm_exit:
2516 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2525 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2517 self.ask_exit()
2526 self.ask_exit()
2518 else:
2527 else:
2519 self.ask_exit()
2528 self.ask_exit()
2520
2529
2521 def safe_execfile(self,fname,*where,**kw):
2530 def safe_execfile(self,fname,*where,**kw):
2522 """A safe version of the builtin execfile().
2531 """A safe version of the builtin execfile().
2523
2532
2524 This version will never throw an exception, and knows how to handle
2533 This version will never throw an exception, and knows how to handle
2525 ipython logs as well.
2534 ipython logs as well.
2526
2535
2527 :Parameters:
2536 :Parameters:
2528 fname : string
2537 fname : string
2529 Name of the file to be executed.
2538 Name of the file to be executed.
2530
2539
2531 where : tuple
2540 where : tuple
2532 One or two namespaces, passed to execfile() as (globals,locals).
2541 One or two namespaces, passed to execfile() as (globals,locals).
2533 If only one is given, it is passed as both.
2542 If only one is given, it is passed as both.
2534
2543
2535 :Keywords:
2544 :Keywords:
2536 islog : boolean (False)
2545 islog : boolean (False)
2537
2546
2538 quiet : boolean (True)
2547 quiet : boolean (True)
2539
2548
2540 exit_ignore : boolean (False)
2549 exit_ignore : boolean (False)
2541 """
2550 """
2542
2551
2543 def syspath_cleanup():
2552 def syspath_cleanup():
2544 """Internal cleanup routine for sys.path."""
2553 """Internal cleanup routine for sys.path."""
2545 if add_dname:
2554 if add_dname:
2546 try:
2555 try:
2547 sys.path.remove(dname)
2556 sys.path.remove(dname)
2548 except ValueError:
2557 except ValueError:
2549 # For some reason the user has already removed it, ignore.
2558 # For some reason the user has already removed it, ignore.
2550 pass
2559 pass
2551
2560
2552 fname = os.path.expanduser(fname)
2561 fname = os.path.expanduser(fname)
2553
2562
2554 # Find things also in current directory. This is needed to mimic the
2563 # Find things also in current directory. This is needed to mimic the
2555 # behavior of running a script from the system command line, where
2564 # behavior of running a script from the system command line, where
2556 # Python inserts the script's directory into sys.path
2565 # Python inserts the script's directory into sys.path
2557 dname = os.path.dirname(os.path.abspath(fname))
2566 dname = os.path.dirname(os.path.abspath(fname))
2558 add_dname = False
2567 add_dname = False
2559 if dname not in sys.path:
2568 if dname not in sys.path:
2560 sys.path.insert(0,dname)
2569 sys.path.insert(0,dname)
2561 add_dname = True
2570 add_dname = True
2562
2571
2563 try:
2572 try:
2564 xfile = open(fname)
2573 xfile = open(fname)
2565 except:
2574 except:
2566 print >> Term.cerr, \
2575 print >> Term.cerr, \
2567 'Could not open file <%s> for safe execution.' % fname
2576 'Could not open file <%s> for safe execution.' % fname
2568 syspath_cleanup()
2577 syspath_cleanup()
2569 return None
2578 return None
2570
2579
2571 kw.setdefault('islog',0)
2580 kw.setdefault('islog',0)
2572 kw.setdefault('quiet',1)
2581 kw.setdefault('quiet',1)
2573 kw.setdefault('exit_ignore',0)
2582 kw.setdefault('exit_ignore',0)
2574
2583
2575 first = xfile.readline()
2584 first = xfile.readline()
2576 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2585 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2577 xfile.close()
2586 xfile.close()
2578 # line by line execution
2587 # line by line execution
2579 if first.startswith(loghead) or kw['islog']:
2588 if first.startswith(loghead) or kw['islog']:
2580 print 'Loading log file <%s> one line at a time...' % fname
2589 print 'Loading log file <%s> one line at a time...' % fname
2581 if kw['quiet']:
2590 if kw['quiet']:
2582 stdout_save = sys.stdout
2591 stdout_save = sys.stdout
2583 sys.stdout = StringIO.StringIO()
2592 sys.stdout = StringIO.StringIO()
2584 try:
2593 try:
2585 globs,locs = where[0:2]
2594 globs,locs = where[0:2]
2586 except:
2595 except:
2587 try:
2596 try:
2588 globs = locs = where[0]
2597 globs = locs = where[0]
2589 except:
2598 except:
2590 globs = locs = globals()
2599 globs = locs = globals()
2591 badblocks = []
2600 badblocks = []
2592
2601
2593 # we also need to identify indented blocks of code when replaying
2602 # we also need to identify indented blocks of code when replaying
2594 # logs and put them together before passing them to an exec
2603 # logs and put them together before passing them to an exec
2595 # statement. This takes a bit of regexp and look-ahead work in the
2604 # statement. This takes a bit of regexp and look-ahead work in the
2596 # file. It's easiest if we swallow the whole thing in memory
2605 # file. It's easiest if we swallow the whole thing in memory
2597 # first, and manually walk through the lines list moving the
2606 # first, and manually walk through the lines list moving the
2598 # counter ourselves.
2607 # counter ourselves.
2599 indent_re = re.compile('\s+\S')
2608 indent_re = re.compile('\s+\S')
2600 xfile = open(fname)
2609 xfile = open(fname)
2601 filelines = xfile.readlines()
2610 filelines = xfile.readlines()
2602 xfile.close()
2611 xfile.close()
2603 nlines = len(filelines)
2612 nlines = len(filelines)
2604 lnum = 0
2613 lnum = 0
2605 while lnum < nlines:
2614 while lnum < nlines:
2606 line = filelines[lnum]
2615 line = filelines[lnum]
2607 lnum += 1
2616 lnum += 1
2608 # don't re-insert logger status info into cache
2617 # don't re-insert logger status info into cache
2609 if line.startswith('#log#'):
2618 if line.startswith('#log#'):
2610 continue
2619 continue
2611 else:
2620 else:
2612 # build a block of code (maybe a single line) for execution
2621 # build a block of code (maybe a single line) for execution
2613 block = line
2622 block = line
2614 try:
2623 try:
2615 next = filelines[lnum] # lnum has already incremented
2624 next = filelines[lnum] # lnum has already incremented
2616 except:
2625 except:
2617 next = None
2626 next = None
2618 while next and indent_re.match(next):
2627 while next and indent_re.match(next):
2619 block += next
2628 block += next
2620 lnum += 1
2629 lnum += 1
2621 try:
2630 try:
2622 next = filelines[lnum]
2631 next = filelines[lnum]
2623 except:
2632 except:
2624 next = None
2633 next = None
2625 # now execute the block of one or more lines
2634 # now execute the block of one or more lines
2626 try:
2635 try:
2627 exec block in globs,locs
2636 exec block in globs,locs
2628 except SystemExit:
2637 except SystemExit:
2629 pass
2638 pass
2630 except:
2639 except:
2631 badblocks.append(block.rstrip())
2640 badblocks.append(block.rstrip())
2632 if kw['quiet']: # restore stdout
2641 if kw['quiet']: # restore stdout
2633 sys.stdout.close()
2642 sys.stdout.close()
2634 sys.stdout = stdout_save
2643 sys.stdout = stdout_save
2635 print 'Finished replaying log file <%s>' % fname
2644 print 'Finished replaying log file <%s>' % fname
2636 if badblocks:
2645 if badblocks:
2637 print >> sys.stderr, ('\nThe following lines/blocks in file '
2646 print >> sys.stderr, ('\nThe following lines/blocks in file '
2638 '<%s> reported errors:' % fname)
2647 '<%s> reported errors:' % fname)
2639
2648
2640 for badline in badblocks:
2649 for badline in badblocks:
2641 print >> sys.stderr, badline
2650 print >> sys.stderr, badline
2642 else: # regular file execution
2651 else: # regular file execution
2643 try:
2652 try:
2644 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2653 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2645 # Work around a bug in Python for Windows. The bug was
2654 # Work around a bug in Python for Windows. The bug was
2646 # fixed in in Python 2.5 r54159 and 54158, but that's still
2655 # fixed in in Python 2.5 r54159 and 54158, but that's still
2647 # SVN Python as of March/07. For details, see:
2656 # SVN Python as of March/07. For details, see:
2648 # http://projects.scipy.org/ipython/ipython/ticket/123
2657 # http://projects.scipy.org/ipython/ipython/ticket/123
2649 try:
2658 try:
2650 globs,locs = where[0:2]
2659 globs,locs = where[0:2]
2651 except:
2660 except:
2652 try:
2661 try:
2653 globs = locs = where[0]
2662 globs = locs = where[0]
2654 except:
2663 except:
2655 globs = locs = globals()
2664 globs = locs = globals()
2656 exec file(fname) in globs,locs
2665 exec file(fname) in globs,locs
2657 else:
2666 else:
2658 execfile(fname,*where)
2667 execfile(fname,*where)
2659 except SyntaxError:
2668 except SyntaxError:
2660 self.showsyntaxerror()
2669 self.showsyntaxerror()
2661 warn('Failure executing file: <%s>' % fname)
2670 warn('Failure executing file: <%s>' % fname)
2662 except SystemExit,status:
2671 except SystemExit,status:
2663 # Code that correctly sets the exit status flag to success (0)
2672 # Code that correctly sets the exit status flag to success (0)
2664 # shouldn't be bothered with a traceback. Note that a plain
2673 # shouldn't be bothered with a traceback. Note that a plain
2665 # sys.exit() does NOT set the message to 0 (it's empty) so that
2674 # sys.exit() does NOT set the message to 0 (it's empty) so that
2666 # will still get a traceback. Note that the structure of the
2675 # will still get a traceback. Note that the structure of the
2667 # SystemExit exception changed between Python 2.4 and 2.5, so
2676 # SystemExit exception changed between Python 2.4 and 2.5, so
2668 # the checks must be done in a version-dependent way.
2677 # the checks must be done in a version-dependent way.
2669 show = False
2678 show = False
2670
2679
2671 if sys.version_info[:2] > (2,5):
2680 if sys.version_info[:2] > (2,5):
2672 if status.message!=0 and not kw['exit_ignore']:
2681 if status.message!=0 and not kw['exit_ignore']:
2673 show = True
2682 show = True
2674 else:
2683 else:
2675 if status.code and not kw['exit_ignore']:
2684 if status.code and not kw['exit_ignore']:
2676 show = True
2685 show = True
2677 if show:
2686 if show:
2678 self.showtraceback()
2687 self.showtraceback()
2679 warn('Failure executing file: <%s>' % fname)
2688 warn('Failure executing file: <%s>' % fname)
2680 except:
2689 except:
2681 self.showtraceback()
2690 self.showtraceback()
2682 warn('Failure executing file: <%s>' % fname)
2691 warn('Failure executing file: <%s>' % fname)
2683
2692
2684 syspath_cleanup()
2693 syspath_cleanup()
2685
2694
2686 #************************* end of file <iplib.py> *****************************
2695 #************************* end of file <iplib.py> *****************************
@@ -1,3162 +1,3200 b''
1 .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008.
1 .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008.
2 You can adapt this file completely to your liking, but it should at least
2 You can adapt this file completely to your liking, but it should at least
3 contain the root 'toctree' directive.
3 contain the root 'toctree' directive.
4
4
5 =================
5 =================
6 IPython reference
6 IPython reference
7 =================
7 =================
8
8
9 .. contents::
9 .. contents::
10
10
11 .. _command_line_options:
11 .. _command_line_options:
12
12
13 Command-line usage
13 Command-line usage
14 ==================
14 ==================
15
15
16 You start IPython with the command::
16 You start IPython with the command::
17
17
18 $ ipython [options] files
18 $ ipython [options] files
19
19
20 If invoked with no options, it executes all the files listed in sequence
20 If invoked with no options, it executes all the files listed in sequence
21 and drops you into the interpreter while still acknowledging any options
21 and drops you into the interpreter while still acknowledging any options
22 you may have set in your ipythonrc file. This behavior is different from
22 you may have set in your ipythonrc file. This behavior is different from
23 standard Python, which when called as python -i will only execute one
23 standard Python, which when called as python -i will only execute one
24 file and ignore your configuration setup.
24 file and ignore your configuration setup.
25
25
26 Please note that some of the configuration options are not available at
26 Please note that some of the configuration options are not available at
27 the command line, simply because they are not practical here. Look into
27 the command line, simply because they are not practical here. Look into
28 your ipythonrc configuration file for details on those. This file
28 your ipythonrc configuration file for details on those. This file
29 typically installed in the $HOME/.ipython directory. For Windows users,
29 typically installed in the $HOME/.ipython directory. For Windows users,
30 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
30 $HOME resolves to C:\\Documents and Settings\\YourUserName in most
31 instances. In the rest of this text, we will refer to this directory as
31 instances. In the rest of this text, we will refer to this directory as
32 IPYTHONDIR.
32 IPYTHONDIR.
33
33
34 .. _Threading options:
34 .. _Threading options:
35
35
36
36
37 Special Threading Options
37 Special Threading Options
38 -------------------------
38 -------------------------
39
39
40 The following special options are ONLY valid at the beginning of the
40 The following special options are ONLY valid at the beginning of the
41 command line, and not later. This is because they control the initial-
41 command line, and not later. This is because they control the initial-
42 ization of ipython itself, before the normal option-handling mechanism
42 ization of ipython itself, before the normal option-handling mechanism
43 is active.
43 is active.
44
44
45 -gthread, -qthread, -q4thread, -wthread, -pylab:
45 -gthread, -qthread, -q4thread, -wthread, -pylab:
46 Only one of these can be given, and it can only be given as
46 Only one of these can be given, and it can only be given as
47 the first option passed to IPython (it will have no effect in
47 the first option passed to IPython (it will have no effect in
48 any other position). They provide threading support for the
48 any other position). They provide threading support for the
49 GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the
49 GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the
50 matplotlib library.
50 matplotlib library.
51
51
52 With any of the first four options, IPython starts running a
52 With any of the first four options, IPython starts running a
53 separate thread for the graphical toolkit's operation, so that
53 separate thread for the graphical toolkit's operation, so that
54 you can open and control graphical elements from within an
54 you can open and control graphical elements from within an
55 IPython command line, without blocking. All four provide
55 IPython command line, without blocking. All four provide
56 essentially the same functionality, respectively for GTK, Qt3,
56 essentially the same functionality, respectively for GTK, Qt3,
57 Qt4 and WXWidgets (via their Python interfaces).
57 Qt4 and WXWidgets (via their Python interfaces).
58
58
59 Note that with -wthread, you can additionally use the
59 Note that with -wthread, you can additionally use the
60 -wxversion option to request a specific version of wx to be
60 -wxversion option to request a specific version of wx to be
61 used. This requires that you have the wxversion Python module
61 used. This requires that you have the wxversion Python module
62 installed, which is part of recent wxPython distributions.
62 installed, which is part of recent wxPython distributions.
63
63
64 If -pylab is given, IPython loads special support for the mat
64 If -pylab is given, IPython loads special support for the mat
65 plotlib library (http://matplotlib.sourceforge.net), allowing
65 plotlib library (http://matplotlib.sourceforge.net), allowing
66 interactive usage of any of its backends as defined in the
66 interactive usage of any of its backends as defined in the
67 user's ~/.matplotlib/matplotlibrc file. It automatically
67 user's ~/.matplotlib/matplotlibrc file. It automatically
68 activates GTK, Qt or WX threading for IPyhton if the choice of
68 activates GTK, Qt or WX threading for IPyhton if the choice of
69 matplotlib backend requires it. It also modifies the %run
69 matplotlib backend requires it. It also modifies the %run
70 command to correctly execute (without blocking) any
70 command to correctly execute (without blocking) any
71 matplotlib-based script which calls show() at the end.
71 matplotlib-based script which calls show() at the end.
72
72
73 -tk
73 -tk
74 The -g/q/q4/wthread options, and -pylab (if matplotlib is
74 The -g/q/q4/wthread options, and -pylab (if matplotlib is
75 configured to use GTK, Qt3, Qt4 or WX), will normally block Tk
75 configured to use GTK, Qt3, Qt4 or WX), will normally block Tk
76 graphical interfaces. This means that when either GTK, Qt or WX
76 graphical interfaces. This means that when either GTK, Qt or WX
77 threading is active, any attempt to open a Tk GUI will result in a
77 threading is active, any attempt to open a Tk GUI will result in a
78 dead window, and possibly cause the Python interpreter to crash.
78 dead window, and possibly cause the Python interpreter to crash.
79 An extra option, -tk, is available to address this issue. It can
79 An extra option, -tk, is available to address this issue. It can
80 only be given as a second option after any of the above (-gthread,
80 only be given as a second option after any of the above (-gthread,
81 -wthread or -pylab).
81 -wthread or -pylab).
82
82
83 If -tk is given, IPython will try to coordinate Tk threading
83 If -tk is given, IPython will try to coordinate Tk threading
84 with GTK, Qt or WX. This is however potentially unreliable, and
84 with GTK, Qt or WX. This is however potentially unreliable, and
85 you will have to test on your platform and Python configuration to
85 you will have to test on your platform and Python configuration to
86 determine whether it works for you. Debian users have reported
86 determine whether it works for you. Debian users have reported
87 success, apparently due to the fact that Debian builds all of Tcl,
87 success, apparently due to the fact that Debian builds all of Tcl,
88 Tk, Tkinter and Python with pthreads support. Under other Linux
88 Tk, Tkinter and Python with pthreads support. Under other Linux
89 environments (such as Fedora Core 2/3), this option has caused
89 environments (such as Fedora Core 2/3), this option has caused
90 random crashes and lockups of the Python interpreter. Under other
90 random crashes and lockups of the Python interpreter. Under other
91 operating systems (Mac OSX and Windows), you'll need to try it to
91 operating systems (Mac OSX and Windows), you'll need to try it to
92 find out, since currently no user reports are available.
92 find out, since currently no user reports are available.
93
93
94 There is unfortunately no way for IPython to determine at run time
94 There is unfortunately no way for IPython to determine at run time
95 whether -tk will work reliably or not, so you will need to do some
95 whether -tk will work reliably or not, so you will need to do some
96 experiments before relying on it for regular work.
96 experiments before relying on it for regular work.
97
97
98
98
99
99
100 Regular Options
100 Regular Options
101 ---------------
101 ---------------
102
102
103 After the above threading options have been given, regular options can
103 After the above threading options have been given, regular options can
104 follow in any order. All options can be abbreviated to their shortest
104 follow in any order. All options can be abbreviated to their shortest
105 non-ambiguous form and are case-sensitive. One or two dashes can be
105 non-ambiguous form and are case-sensitive. One or two dashes can be
106 used. Some options have an alternate short form, indicated after a ``|``.
106 used. Some options have an alternate short form, indicated after a ``|``.
107
107
108 Most options can also be set from your ipythonrc configuration file. See
108 Most options can also be set from your ipythonrc configuration file. See
109 the provided example for more details on what the options do. Options
109 the provided example for more details on what the options do. Options
110 given at the command line override the values set in the ipythonrc file.
110 given at the command line override the values set in the ipythonrc file.
111
111
112 All options with a [no] prepended can be specified in negated form
112 All options with a [no] prepended can be specified in negated form
113 (-nooption instead of -option) to turn the feature off.
113 (-nooption instead of -option) to turn the feature off.
114
114
115 -help print a help message and exit.
115 -help print a help message and exit.
116
116
117 -pylab
117 -pylab
118 this can only be given as the first option passed to IPython
118 this can only be given as the first option passed to IPython
119 (it will have no effect in any other position). It adds
119 (it will have no effect in any other position). It adds
120 special support for the matplotlib library
120 special support for the matplotlib library
121 (http://matplotlib.sourceforge.ne), allowing interactive usage
121 (http://matplotlib.sourceforge.ne), allowing interactive usage
122 of any of its backends as defined in the user's .matplotlibrc
122 of any of its backends as defined in the user's .matplotlibrc
123 file. It automatically activates GTK or WX threading for
123 file. It automatically activates GTK or WX threading for
124 IPyhton if the choice of matplotlib backend requires it. It
124 IPyhton if the choice of matplotlib backend requires it. It
125 also modifies the %run command to correctly execute (without
125 also modifies the %run command to correctly execute (without
126 blocking) any matplotlib-based script which calls show() at
126 blocking) any matplotlib-based script which calls show() at
127 the end. See `Matplotlib support`_ for more details.
127 the end. See `Matplotlib support`_ for more details.
128
128
129 -autocall <val>
129 -autocall <val>
130 Make IPython automatically call any callable object even if you
130 Make IPython automatically call any callable object even if you
131 didn't type explicit parentheses. For example, 'str 43' becomes
131 didn't type explicit parentheses. For example, 'str 43' becomes
132 'str(43)' automatically. The value can be '0' to disable the feature,
132 'str(43)' automatically. The value can be '0' to disable the feature,
133 '1' for smart autocall, where it is not applied if there are no more
133 '1' for smart autocall, where it is not applied if there are no more
134 arguments on the line, and '2' for full autocall, where all callable
134 arguments on the line, and '2' for full autocall, where all callable
135 objects are automatically called (even if no arguments are
135 objects are automatically called (even if no arguments are
136 present). The default is '1'.
136 present). The default is '1'.
137
137
138 -[no]autoindent
138 -[no]autoindent
139 Turn automatic indentation on/off.
139 Turn automatic indentation on/off.
140
140
141 -[no]automagic
141 -[no]automagic
142 make magic commands automatic (without needing their first character
142 make magic commands automatic (without needing their first character
143 to be %). Type %magic at the IPython prompt for more information.
143 to be %). Type %magic at the IPython prompt for more information.
144
144
145 -[no]autoedit_syntax
145 -[no]autoedit_syntax
146 When a syntax error occurs after editing a file, automatically
146 When a syntax error occurs after editing a file, automatically
147 open the file to the trouble causing line for convenient
147 open the file to the trouble causing line for convenient
148 fixing.
148 fixing.
149
149
150 -[no]banner Print the initial information banner (default on).
150 -[no]banner Print the initial information banner (default on).
151
151
152 -c <command>
152 -c <command>
153 execute the given command string. This is similar to the -c
153 execute the given command string. This is similar to the -c
154 option in the normal Python interpreter.
154 option in the normal Python interpreter.
155
155
156 -cache_size, cs <n>
156 -cache_size, cs <n>
157 size of the output cache (maximum number of entries to hold in
157 size of the output cache (maximum number of entries to hold in
158 memory). The default is 1000, you can change it permanently in your
158 memory). The default is 1000, you can change it permanently in your
159 config file. Setting it to 0 completely disables the caching system,
159 config file. Setting it to 0 completely disables the caching system,
160 and the minimum value accepted is 20 (if you provide a value less than
160 and the minimum value accepted is 20 (if you provide a value less than
161 20, it is reset to 0 and a warning is issued) This limit is defined
161 20, it is reset to 0 and a warning is issued) This limit is defined
162 because otherwise you'll spend more time re-flushing a too small cache
162 because otherwise you'll spend more time re-flushing a too small cache
163 than working.
163 than working.
164
164
165 -classic, cl
165 -classic, cl
166 Gives IPython a similar feel to the classic Python
166 Gives IPython a similar feel to the classic Python
167 prompt.
167 prompt.
168
168
169 -colors <scheme>
169 -colors <scheme>
170 Color scheme for prompts and exception reporting. Currently
170 Color scheme for prompts and exception reporting. Currently
171 implemented: NoColor, Linux and LightBG.
171 implemented: NoColor, Linux and LightBG.
172
172
173 -[no]color_info
173 -[no]color_info
174 IPython can display information about objects via a set of functions,
174 IPython can display information about objects via a set of functions,
175 and optionally can use colors for this, syntax highlighting source
175 and optionally can use colors for this, syntax highlighting source
176 code and various other elements. However, because this information is
176 code and various other elements. However, because this information is
177 passed through a pager (like 'less') and many pagers get confused with
177 passed through a pager (like 'less') and many pagers get confused with
178 color codes, this option is off by default. You can test it and turn
178 color codes, this option is off by default. You can test it and turn
179 it on permanently in your ipythonrc file if it works for you. As a
179 it on permanently in your ipythonrc file if it works for you. As a
180 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
180 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
181 that in RedHat 7.2 doesn't.
181 that in RedHat 7.2 doesn't.
182
182
183 Test it and turn it on permanently if it works with your
183 Test it and turn it on permanently if it works with your
184 system. The magic function %color_info allows you to toggle this
184 system. The magic function %color_info allows you to toggle this
185 interactively for testing.
185 interactively for testing.
186
186
187 -[no]debug
187 -[no]debug
188 Show information about the loading process. Very useful to pin down
188 Show information about the loading process. Very useful to pin down
189 problems with your configuration files or to get details about
189 problems with your configuration files or to get details about
190 session restores.
190 session restores.
191
191
192 -[no]deep_reload:
192 -[no]deep_reload:
193 IPython can use the deep_reload module which reloads changes in
193 IPython can use the deep_reload module which reloads changes in
194 modules recursively (it replaces the reload() function, so you don't
194 modules recursively (it replaces the reload() function, so you don't
195 need to change anything to use it). deep_reload() forces a full
195 need to change anything to use it). deep_reload() forces a full
196 reload of modules whose code may have changed, which the default
196 reload of modules whose code may have changed, which the default
197 reload() function does not.
197 reload() function does not.
198
198
199 When deep_reload is off, IPython will use the normal reload(),
199 When deep_reload is off, IPython will use the normal reload(),
200 but deep_reload will still be available as dreload(). This
200 but deep_reload will still be available as dreload(). This
201 feature is off by default [which means that you have both
201 feature is off by default [which means that you have both
202 normal reload() and dreload()].
202 normal reload() and dreload()].
203
203
204 -editor <name>
204 -editor <name>
205 Which editor to use with the %edit command. By default,
205 Which editor to use with the %edit command. By default,
206 IPython will honor your EDITOR environment variable (if not
206 IPython will honor your EDITOR environment variable (if not
207 set, vi is the Unix default and notepad the Windows one).
207 set, vi is the Unix default and notepad the Windows one).
208 Since this editor is invoked on the fly by IPython and is
208 Since this editor is invoked on the fly by IPython and is
209 meant for editing small code snippets, you may want to use a
209 meant for editing small code snippets, you may want to use a
210 small, lightweight editor here (in case your default EDITOR is
210 small, lightweight editor here (in case your default EDITOR is
211 something like Emacs).
211 something like Emacs).
212
212
213 -ipythondir <name>
213 -ipythondir <name>
214 name of your IPython configuration directory IPYTHONDIR. This
214 name of your IPython configuration directory IPYTHONDIR. This
215 can also be specified through the environment variable
215 can also be specified through the environment variable
216 IPYTHONDIR.
216 IPYTHONDIR.
217
217
218 -log, l
218 -log, l
219 generate a log file of all input. The file is named
219 generate a log file of all input. The file is named
220 ipython_log.py in your current directory (which prevents logs
220 ipython_log.py in your current directory (which prevents logs
221 from multiple IPython sessions from trampling each other). You
221 from multiple IPython sessions from trampling each other). You
222 can use this to later restore a session by loading your
222 can use this to later restore a session by loading your
223 logfile as a file to be executed with option -logplay (see
223 logfile as a file to be executed with option -logplay (see
224 below).
224 below).
225
225
226 -logfile, lf <name> specify the name of your logfile.
226 -logfile, lf <name> specify the name of your logfile.
227
227
228 -logplay, lp <name>
228 -logplay, lp <name>
229
229
230 you can replay a previous log. For restoring a session as close as
230 you can replay a previous log. For restoring a session as close as
231 possible to the state you left it in, use this option (don't just run
231 possible to the state you left it in, use this option (don't just run
232 the logfile). With -logplay, IPython will try to reconstruct the
232 the logfile). With -logplay, IPython will try to reconstruct the
233 previous working environment in full, not just execute the commands in
233 previous working environment in full, not just execute the commands in
234 the logfile.
234 the logfile.
235
235
236 When a session is restored, logging is automatically turned on
236 When a session is restored, logging is automatically turned on
237 again with the name of the logfile it was invoked with (it is
237 again with the name of the logfile it was invoked with (it is
238 read from the log header). So once you've turned logging on for
238 read from the log header). So once you've turned logging on for
239 a session, you can quit IPython and reload it as many times as
239 a session, you can quit IPython and reload it as many times as
240 you want and it will continue to log its history and restore
240 you want and it will continue to log its history and restore
241 from the beginning every time.
241 from the beginning every time.
242
242
243 Caveats: there are limitations in this option. The history
243 Caveats: there are limitations in this option. The history
244 variables _i*,_* and _dh don't get restored properly. In the
244 variables _i*,_* and _dh don't get restored properly. In the
245 future we will try to implement full session saving by writing
245 future we will try to implement full session saving by writing
246 and retrieving a 'snapshot' of the memory state of IPython. But
246 and retrieving a 'snapshot' of the memory state of IPython. But
247 our first attempts failed because of inherent limitations of
247 our first attempts failed because of inherent limitations of
248 Python's Pickle module, so this may have to wait.
248 Python's Pickle module, so this may have to wait.
249
249
250 -[no]messages
250 -[no]messages
251 Print messages which IPython collects about its startup
251 Print messages which IPython collects about its startup
252 process (default on).
252 process (default on).
253
253
254 -[no]pdb
254 -[no]pdb
255 Automatically call the pdb debugger after every uncaught
255 Automatically call the pdb debugger after every uncaught
256 exception. If you are used to debugging using pdb, this puts
256 exception. If you are used to debugging using pdb, this puts
257 you automatically inside of it after any call (either in
257 you automatically inside of it after any call (either in
258 IPython or in code called by it) which triggers an exception
258 IPython or in code called by it) which triggers an exception
259 which goes uncaught.
259 which goes uncaught.
260
260
261 -pydb
261 -pydb
262 Makes IPython use the third party "pydb" package as debugger,
262 Makes IPython use the third party "pydb" package as debugger,
263 instead of pdb. Requires that pydb is installed.
263 instead of pdb. Requires that pydb is installed.
264
264
265 -[no]pprint
265 -[no]pprint
266 ipython can optionally use the pprint (pretty printer) module
266 ipython can optionally use the pprint (pretty printer) module
267 for displaying results. pprint tends to give a nicer display
267 for displaying results. pprint tends to give a nicer display
268 of nested data structures. If you like it, you can turn it on
268 of nested data structures. If you like it, you can turn it on
269 permanently in your config file (default off).
269 permanently in your config file (default off).
270
270
271 -profile, p <name>
271 -profile, p <name>
272
272
273 assume that your config file is ipythonrc-<name> or
273 assume that your config file is ipythonrc-<name> or
274 ipy_profile_<name>.py (looks in current dir first, then in
274 ipy_profile_<name>.py (looks in current dir first, then in
275 IPYTHONDIR). This is a quick way to keep and load multiple
275 IPYTHONDIR). This is a quick way to keep and load multiple
276 config files for different tasks, especially if you use the
276 config files for different tasks, especially if you use the
277 include option of config files. You can keep a basic
277 include option of config files. You can keep a basic
278 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
278 IPYTHONDIR/ipythonrc file and then have other 'profiles' which
279 include this one and load extra things for particular
279 include this one and load extra things for particular
280 tasks. For example:
280 tasks. For example:
281
281
282 1. $HOME/.ipython/ipythonrc : load basic things you always want.
282 1. $HOME/.ipython/ipythonrc : load basic things you always want.
283 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
283 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules.
284 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
284 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules.
285
285
286 Since it is possible to create an endless loop by having
286 Since it is possible to create an endless loop by having
287 circular file inclusions, IPython will stop if it reaches 15
287 circular file inclusions, IPython will stop if it reaches 15
288 recursive inclusions.
288 recursive inclusions.
289
289
290 -prompt_in1, pi1 <string>
290 -prompt_in1, pi1 <string>
291
291
292 Specify the string used for input prompts. Note that if you are using
292 Specify the string used for input prompts. Note that if you are using
293 numbered prompts, the number is represented with a '\#' in the
293 numbered prompts, the number is represented with a '\#' in the
294 string. Don't forget to quote strings with spaces embedded in
294 string. Don't forget to quote strings with spaces embedded in
295 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
295 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
296 discusses in detail all the available escapes to customize your
296 discusses in detail all the available escapes to customize your
297 prompts.
297 prompts.
298
298
299 -prompt_in2, pi2 <string>
299 -prompt_in2, pi2 <string>
300 Similar to the previous option, but used for the continuation
300 Similar to the previous option, but used for the continuation
301 prompts. The special sequence '\D' is similar to '\#', but
301 prompts. The special sequence '\D' is similar to '\#', but
302 with all digits replaced dots (so you can have your
302 with all digits replaced dots (so you can have your
303 continuation prompt aligned with your input prompt). Default:
303 continuation prompt aligned with your input prompt). Default:
304 ' .\D.:' (note three spaces at the start for alignment with
304 ' .\D.:' (note three spaces at the start for alignment with
305 'In [\#]').
305 'In [\#]').
306
306
307 -prompt_out,po <string>
307 -prompt_out,po <string>
308 String used for output prompts, also uses numbers like
308 String used for output prompts, also uses numbers like
309 prompt_in1. Default: 'Out[\#]:'
309 prompt_in1. Default: 'Out[\#]:'
310
310
311 -quick start in bare bones mode (no config file loaded).
311 -quick start in bare bones mode (no config file loaded).
312
312
313 -rcfile <name>
313 -rcfile <name>
314 name of your IPython resource configuration file. Normally
314 name of your IPython resource configuration file. Normally
315 IPython loads ipythonrc (from current directory) or
315 IPython loads ipythonrc (from current directory) or
316 IPYTHONDIR/ipythonrc.
316 IPYTHONDIR/ipythonrc.
317
317
318 If the loading of your config file fails, IPython starts with
318 If the loading of your config file fails, IPython starts with
319 a bare bones configuration (no modules loaded at all).
319 a bare bones configuration (no modules loaded at all).
320
320
321 -[no]readline
321 -[no]readline
322 use the readline library, which is needed to support name
322 use the readline library, which is needed to support name
323 completion and command history, among other things. It is
323 completion and command history, among other things. It is
324 enabled by default, but may cause problems for users of
324 enabled by default, but may cause problems for users of
325 X/Emacs in Python comint or shell buffers.
325 X/Emacs in Python comint or shell buffers.
326
326
327 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
327 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
328 IPython's readline and syntax coloring fine, only 'emacs' (M-x
328 IPython's readline and syntax coloring fine, only 'emacs' (M-x
329 shell and C-c !) buffers do not.
329 shell and C-c !) buffers do not.
330
330
331 -screen_length, sl <n>
331 -screen_length, sl <n>
332 number of lines of your screen. This is used to control
332 number of lines of your screen. This is used to control
333 printing of very long strings. Strings longer than this number
333 printing of very long strings. Strings longer than this number
334 of lines will be sent through a pager instead of directly
334 of lines will be sent through a pager instead of directly
335 printed.
335 printed.
336
336
337 The default value for this is 0, which means IPython will
337 The default value for this is 0, which means IPython will
338 auto-detect your screen size every time it needs to print certain
338 auto-detect your screen size every time it needs to print certain
339 potentially long strings (this doesn't change the behavior of the
339 potentially long strings (this doesn't change the behavior of the
340 'print' keyword, it's only triggered internally). If for some
340 'print' keyword, it's only triggered internally). If for some
341 reason this isn't working well (it needs curses support), specify
341 reason this isn't working well (it needs curses support), specify
342 it yourself. Otherwise don't change the default.
342 it yourself. Otherwise don't change the default.
343
343
344 -separate_in, si <string>
344 -separate_in, si <string>
345
345
346 separator before input prompts.
346 separator before input prompts.
347 Default: '\n'
347 Default: '\n'
348
348
349 -separate_out, so <string>
349 -separate_out, so <string>
350 separator before output prompts.
350 separator before output prompts.
351 Default: nothing.
351 Default: nothing.
352
352
353 -separate_out2, so2
353 -separate_out2, so2
354 separator after output prompts.
354 separator after output prompts.
355 Default: nothing.
355 Default: nothing.
356 For these three options, use the value 0 to specify no separator.
356 For these three options, use the value 0 to specify no separator.
357
357
358 -nosep
358 -nosep
359 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
359 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
360 0'. Simply removes all input/output separators.
360 0'. Simply removes all input/output separators.
361
361
362 -upgrade
362 -upgrade
363 allows you to upgrade your IPYTHONDIR configuration when you
363 allows you to upgrade your IPYTHONDIR configuration when you
364 install a new version of IPython. Since new versions may
364 install a new version of IPython. Since new versions may
365 include new command line options or example files, this copies
365 include new command line options or example files, this copies
366 updated ipythonrc-type files. However, it backs up (with a
366 updated ipythonrc-type files. However, it backs up (with a
367 .old extension) all files which it overwrites so that you can
367 .old extension) all files which it overwrites so that you can
368 merge back any customizations you might have in your personal
368 merge back any customizations you might have in your personal
369 files. Note that you should probably use %upgrade instead,
369 files. Note that you should probably use %upgrade instead,
370 it's a safer alternative.
370 it's a safer alternative.
371
371
372
372
373 -Version print version information and exit.
373 -Version print version information and exit.
374
374
375 -wxversion <string>
375 -wxversion <string>
376 Select a specific version of wxPython (used in conjunction
376 Select a specific version of wxPython (used in conjunction
377 with -wthread). Requires the wxversion module, part of recent
377 with -wthread). Requires the wxversion module, part of recent
378 wxPython distributions
378 wxPython distributions
379
379
380 -xmode <modename>
380 -xmode <modename>
381
381
382 Mode for exception reporting.
382 Mode for exception reporting.
383
383
384 Valid modes: Plain, Context and Verbose.
384 Valid modes: Plain, Context and Verbose.
385
385
386 * Plain: similar to python's normal traceback printing.
386 * Plain: similar to python's normal traceback printing.
387 * Context: prints 5 lines of context source code around each
387 * Context: prints 5 lines of context source code around each
388 line in the traceback.
388 line in the traceback.
389 * Verbose: similar to Context, but additionally prints the
389 * Verbose: similar to Context, but additionally prints the
390 variables currently visible where the exception happened
390 variables currently visible where the exception happened
391 (shortening their strings if too long). This can potentially be
391 (shortening their strings if too long). This can potentially be
392 very slow, if you happen to have a huge data structure whose
392 very slow, if you happen to have a huge data structure whose
393 string representation is complex to compute. Your computer may
393 string representation is complex to compute. Your computer may
394 appear to freeze for a while with cpu usage at 100%. If this
394 appear to freeze for a while with cpu usage at 100%. If this
395 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
395 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
396 more than once).
396 more than once).
397
397
398 Interactive use
398 Interactive use
399 ===============
399 ===============
400
400
401 Warning: IPython relies on the existence of a global variable called
401 Warning: IPython relies on the existence of a global variable called
402 _ip which controls the shell itself. If you redefine _ip to anything,
402 _ip which controls the shell itself. If you redefine _ip to anything,
403 bizarre behavior will quickly occur.
403 bizarre behavior will quickly occur.
404
404
405 Other than the above warning, IPython is meant to work as a drop-in
405 Other than the above warning, IPython is meant to work as a drop-in
406 replacement for the standard interactive interpreter. As such, any code
406 replacement for the standard interactive interpreter. As such, any code
407 which is valid python should execute normally under IPython (cases where
407 which is valid python should execute normally under IPython (cases where
408 this is not true should be reported as bugs). It does, however, offer
408 this is not true should be reported as bugs). It does, however, offer
409 many features which are not available at a standard python prompt. What
409 many features which are not available at a standard python prompt. What
410 follows is a list of these.
410 follows is a list of these.
411
411
412
412
413 Caution for Windows users
413 Caution for Windows users
414 -------------------------
414 -------------------------
415
415
416 Windows, unfortunately, uses the '\' character as a path
416 Windows, unfortunately, uses the '\' character as a path
417 separator. This is a terrible choice, because '\' also represents the
417 separator. This is a terrible choice, because '\' also represents the
418 escape character in most modern programming languages, including
418 escape character in most modern programming languages, including
419 Python. For this reason, using '/' character is recommended if you
419 Python. For this reason, using '/' character is recommended if you
420 have problems with ``\``. However, in Windows commands '/' flags
420 have problems with ``\``. However, in Windows commands '/' flags
421 options, so you can not use it for the root directory. This means that
421 options, so you can not use it for the root directory. This means that
422 paths beginning at the root must be typed in a contrived manner like:
422 paths beginning at the root must be typed in a contrived manner like:
423 ``%copy \opt/foo/bar.txt \tmp``
423 ``%copy \opt/foo/bar.txt \tmp``
424
424
425 .. _magic:
425 .. _magic:
426
426
427 Magic command system
427 Magic command system
428 --------------------
428 --------------------
429
429
430 IPython will treat any line whose first character is a % as a special
430 IPython will treat any line whose first character is a % as a special
431 call to a 'magic' function. These allow you to control the behavior of
431 call to a 'magic' function. These allow you to control the behavior of
432 IPython itself, plus a lot of system-type features. They are all
432 IPython itself, plus a lot of system-type features. They are all
433 prefixed with a % character, but parameters are given without
433 prefixed with a % character, but parameters are given without
434 parentheses or quotes.
434 parentheses or quotes.
435
435
436 Example: typing '%cd mydir' (without the quotes) changes you working
436 Example: typing '%cd mydir' (without the quotes) changes you working
437 directory to 'mydir', if it exists.
437 directory to 'mydir', if it exists.
438
438
439 If you have 'automagic' enabled (in your ipythonrc file, via the command
439 If you have 'automagic' enabled (in your ipythonrc file, via the command
440 line option -automagic or with the %automagic function), you don't need
440 line option -automagic or with the %automagic function), you don't need
441 to type in the % explicitly. IPython will scan its internal list of
441 to type in the % explicitly. IPython will scan its internal list of
442 magic functions and call one if it exists. With automagic on you can
442 magic functions and call one if it exists. With automagic on you can
443 then just type 'cd mydir' to go to directory 'mydir'. The automagic
443 then just type 'cd mydir' to go to directory 'mydir'. The automagic
444 system has the lowest possible precedence in name searches, so defining
444 system has the lowest possible precedence in name searches, so defining
445 an identifier with the same name as an existing magic function will
445 an identifier with the same name as an existing magic function will
446 shadow it for automagic use. You can still access the shadowed magic
446 shadow it for automagic use. You can still access the shadowed magic
447 function by explicitly using the % character at the beginning of the line.
447 function by explicitly using the % character at the beginning of the line.
448
448
449 An example (with automagic on) should clarify all this::
449 An example (with automagic on) should clarify all this::
450
450
451 In [1]: cd ipython # %cd is called by automagic
451 In [1]: cd ipython # %cd is called by automagic
452
452
453 /home/fperez/ipython
453 /home/fperez/ipython
454
454
455 In [2]: cd=1 # now cd is just a variable
455 In [2]: cd=1 # now cd is just a variable
456
456
457 In [3]: cd .. # and doesn't work as a function anymore
457 In [3]: cd .. # and doesn't work as a function anymore
458
458
459 ------------------------------
459 ------------------------------
460
460
461 File "<console>", line 1
461 File "<console>", line 1
462
462
463 cd ..
463 cd ..
464
464
465 ^
465 ^
466
466
467 SyntaxError: invalid syntax
467 SyntaxError: invalid syntax
468
468
469 In [4]: %cd .. # but %cd always works
469 In [4]: %cd .. # but %cd always works
470
470
471 /home/fperez
471 /home/fperez
472
472
473 In [5]: del cd # if you remove the cd variable
473 In [5]: del cd # if you remove the cd variable
474
474
475 In [6]: cd ipython # automagic can work again
475 In [6]: cd ipython # automagic can work again
476
476
477 /home/fperez/ipython
477 /home/fperez/ipython
478
478
479 You can define your own magic functions to extend the system. The
479 You can define your own magic functions to extend the system. The
480 following example defines a new magic command, %impall::
480 following example defines a new magic command, %impall::
481
481
482 import IPython.ipapi
482 import IPython.ipapi
483
483
484 ip = IPython.ipapi.get()
484 ip = IPython.ipapi.get()
485
485
486 def doimp(self, arg):
486 def doimp(self, arg):
487
487
488 ip = self.api
488 ip = self.api
489
489
490 ip.ex("import %s; reload(%s); from %s import *" % (
490 ip.ex("import %s; reload(%s); from %s import *" % (
491
491
492 arg,arg,arg)
492 arg,arg,arg)
493
493
494 )
494 )
495
495
496 ip.expose_magic('impall', doimp)
496 ip.expose_magic('impall', doimp)
497
497
498 You can also define your own aliased names for magic functions. In your
498 You can also define your own aliased names for magic functions. In your
499 ipythonrc file, placing a line like:
499 ipythonrc file, placing a line like:
500
500
501 execute __IP.magic_cl = __IP.magic_clear
501 execute __IP.magic_cl = __IP.magic_clear
502
502
503 will define %cl as a new name for %clear.
503 will define %cl as a new name for %clear.
504
504
505 Type %magic for more information, including a list of all available
505 Type %magic for more information, including a list of all available
506 magic functions at any time and their docstrings. You can also type
506 magic functions at any time and their docstrings. You can also type
507 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
507 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
508 information on the '?' system) to get information about any particular
508 information on the '?' system) to get information about any particular
509 magic function you are interested in.
509 magic function you are interested in.
510
510
511
511
512 Magic commands
512 Magic commands
513 --------------
513 --------------
514
514
515 The rest of this section is automatically generated for each release
515 The rest of this section is automatically generated for each release
516 from the docstrings in the IPython code. Therefore the formatting is
516 from the docstrings in the IPython code. Therefore the formatting is
517 somewhat minimal, but this method has the advantage of having
517 somewhat minimal, but this method has the advantage of having
518 information always in sync with the code.
518 information always in sync with the code.
519
519
520 A list of all the magic commands available in IPython's default
520 A list of all the magic commands available in IPython's default
521 installation follows. This is similar to what you'll see by simply
521 installation follows. This is similar to what you'll see by simply
522 typing %magic at the prompt, but that will also give you information
522 typing %magic at the prompt, but that will also give you information
523 about magic commands you may have added as part of your personal
523 about magic commands you may have added as part of your personal
524 customizations.
524 customizations.
525
525
526 .. magic_start
526 .. magic_start
527
527
528 **%Exit**::
528 **%Exit**::
529
529
530 Exit IPython without confirmation.
530 Exit IPython without confirmation.
531
531
532 **%Pprint**::
532 **%Pprint**::
533
533
534 Toggle pretty printing on/off.
534 Toggle pretty printing on/off.
535
535
536 **%alias**::
536 **%alias**::
537
537
538 Define an alias for a system command.
538 Define an alias for a system command.
539
539
540 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
540 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
541
541
542 Then, typing 'alias_name params' will execute the system command 'cmd
542 Then, typing 'alias_name params' will execute the system command 'cmd
543 params' (from your underlying operating system).
543 params' (from your underlying operating system).
544
544
545 Aliases have lower precedence than magic functions and Python normal
545 Aliases have lower precedence than magic functions and Python normal
546 variables, so if 'foo' is both a Python variable and an alias, the
546 variables, so if 'foo' is both a Python variable and an alias, the
547 alias can not be executed until 'del foo' removes the Python variable.
547 alias can not be executed until 'del foo' removes the Python variable.
548
548
549 You can use the %l specifier in an alias definition to represent the
549 You can use the %l specifier in an alias definition to represent the
550 whole line when the alias is called. For example:
550 whole line when the alias is called. For example:
551
551
552 In [2]: alias all echo "Input in brackets: <%l>"\
552 In [2]: alias all echo "Input in brackets: <%l>"\
553 In [3]: all hello world\
553 In [3]: all hello world\
554 Input in brackets: <hello world>
554 Input in brackets: <hello world>
555
555
556 You can also define aliases with parameters using %s specifiers (one
556 You can also define aliases with parameters using %s specifiers (one
557 per parameter):
557 per parameter):
558
558
559 In [1]: alias parts echo first %s second %s\
559 In [1]: alias parts echo first %s second %s\
560 In [2]: %parts A B\
560 In [2]: %parts A B\
561 first A second B\
561 first A second B\
562 In [3]: %parts A\
562 In [3]: %parts A\
563 Incorrect number of arguments: 2 expected.\
563 Incorrect number of arguments: 2 expected.\
564 parts is an alias to: 'echo first %s second %s'
564 parts is an alias to: 'echo first %s second %s'
565
565
566 Note that %l and %s are mutually exclusive. You can only use one or
566 Note that %l and %s are mutually exclusive. You can only use one or
567 the other in your aliases.
567 the other in your aliases.
568
568
569 Aliases expand Python variables just like system calls using ! or !!
569 Aliases expand Python variables just like system calls using ! or !!
570 do: all expressions prefixed with '$' get expanded. For details of
570 do: all expressions prefixed with '$' get expanded. For details of
571 the semantic rules, see PEP-215:
571 the semantic rules, see PEP-215:
572 http://www.python.org/peps/pep-0215.html. This is the library used by
572 http://www.python.org/peps/pep-0215.html. This is the library used by
573 IPython for variable expansion. If you want to access a true shell
573 IPython for variable expansion. If you want to access a true shell
574 variable, an extra $ is necessary to prevent its expansion by IPython:
574 variable, an extra $ is necessary to prevent its expansion by IPython:
575
575
576 In [6]: alias show echo\
576 In [6]: alias show echo\
577 In [7]: PATH='A Python string'\
577 In [7]: PATH='A Python string'\
578 In [8]: show $PATH\
578 In [8]: show $PATH\
579 A Python string\
579 A Python string\
580 In [9]: show $$PATH\
580 In [9]: show $$PATH\
581 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
581 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
582
582
583 You can use the alias facility to acess all of $PATH. See the %rehash
583 You can use the alias facility to acess all of $PATH. See the %rehash
584 and %rehashx functions, which automatically create aliases for the
584 and %rehashx functions, which automatically create aliases for the
585 contents of your $PATH.
585 contents of your $PATH.
586
586
587 If called with no parameters, %alias prints the current alias table.
587 If called with no parameters, %alias prints the current alias table.
588
588
589 **%autocall**::
589 **%autocall**::
590
590
591 Make functions callable without having to type parentheses.
591 Make functions callable without having to type parentheses.
592
592
593 Usage:
593 Usage:
594
594
595 %autocall [mode]
595 %autocall [mode]
596
596
597 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
597 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
598 value is toggled on and off (remembering the previous state).
598 value is toggled on and off (remembering the previous state).
599
599
600 In more detail, these values mean:
600 In more detail, these values mean:
601
601
602 0 -> fully disabled
602 0 -> fully disabled
603
603
604 1 -> active, but do not apply if there are no arguments on the line.
604 1 -> active, but do not apply if there are no arguments on the line.
605
605
606 In this mode, you get:
606 In this mode, you get:
607
607
608 In [1]: callable
608 In [1]: callable
609 Out[1]: <built-in function callable>
609 Out[1]: <built-in function callable>
610
610
611 In [2]: callable 'hello'
611 In [2]: callable 'hello'
612 ------> callable('hello')
612 ------> callable('hello')
613 Out[2]: False
613 Out[2]: False
614
614
615 2 -> Active always. Even if no arguments are present, the callable
615 2 -> Active always. Even if no arguments are present, the callable
616 object is called:
616 object is called:
617
617
618 In [4]: callable
618 In [4]: callable
619 ------> callable()
619 ------> callable()
620
620
621 Note that even with autocall off, you can still use '/' at the start of
621 Note that even with autocall off, you can still use '/' at the start of
622 a line to treat the first argument on the command line as a function
622 a line to treat the first argument on the command line as a function
623 and add parentheses to it:
623 and add parentheses to it:
624
624
625 In [8]: /str 43
625 In [8]: /str 43
626 ------> str(43)
626 ------> str(43)
627 Out[8]: '43'
627 Out[8]: '43'
628
628
629 **%autoindent**::
629 **%autoindent**::
630
630
631 Toggle autoindent on/off (if available).
631 Toggle autoindent on/off (if available).
632
632
633 **%automagic**::
633 **%automagic**::
634
634
635 Make magic functions callable without having to type the initial %.
635 Make magic functions callable without having to type the initial %.
636
636
637 Without argumentsl toggles on/off (when off, you must call it as
637 Without argumentsl toggles on/off (when off, you must call it as
638 %automagic, of course). With arguments it sets the value, and you can
638 %automagic, of course). With arguments it sets the value, and you can
639 use any of (case insensitive):
639 use any of (case insensitive):
640
640
641 - on,1,True: to activate
641 - on,1,True: to activate
642
642
643 - off,0,False: to deactivate.
643 - off,0,False: to deactivate.
644
644
645 Note that magic functions have lowest priority, so if there's a
645 Note that magic functions have lowest priority, so if there's a
646 variable whose name collides with that of a magic fn, automagic won't
646 variable whose name collides with that of a magic fn, automagic won't
647 work for that function (you get the variable instead). However, if you
647 work for that function (you get the variable instead). However, if you
648 delete the variable (del var), the previously shadowed magic function
648 delete the variable (del var), the previously shadowed magic function
649 becomes visible to automagic again.
649 becomes visible to automagic again.
650
650
651 **%bg**::
651 **%bg**::
652
652
653 Run a job in the background, in a separate thread.
653 Run a job in the background, in a separate thread.
654
654
655 For example,
655 For example,
656
656
657 %bg myfunc(x,y,z=1)
657 %bg myfunc(x,y,z=1)
658
658
659 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
659 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
660 execution starts, a message will be printed indicating the job
660 execution starts, a message will be printed indicating the job
661 number. If your job number is 5, you can use
661 number. If your job number is 5, you can use
662
662
663 myvar = jobs.result(5) or myvar = jobs[5].result
663 myvar = jobs.result(5) or myvar = jobs[5].result
664
664
665 to assign this result to variable 'myvar'.
665 to assign this result to variable 'myvar'.
666
666
667 IPython has a job manager, accessible via the 'jobs' object. You can
667 IPython has a job manager, accessible via the 'jobs' object. You can
668 type jobs? to get more information about it, and use jobs.<TAB> to see
668 type jobs? to get more information about it, and use jobs.<TAB> to see
669 its attributes. All attributes not starting with an underscore are
669 its attributes. All attributes not starting with an underscore are
670 meant for public use.
670 meant for public use.
671
671
672 In particular, look at the jobs.new() method, which is used to create
672 In particular, look at the jobs.new() method, which is used to create
673 new jobs. This magic %bg function is just a convenience wrapper
673 new jobs. This magic %bg function is just a convenience wrapper
674 around jobs.new(), for expression-based jobs. If you want to create a
674 around jobs.new(), for expression-based jobs. If you want to create a
675 new job with an explicit function object and arguments, you must call
675 new job with an explicit function object and arguments, you must call
676 jobs.new() directly.
676 jobs.new() directly.
677
677
678 The jobs.new docstring also describes in detail several important
678 The jobs.new docstring also describes in detail several important
679 caveats associated with a thread-based model for background job
679 caveats associated with a thread-based model for background job
680 execution. Type jobs.new? for details.
680 execution. Type jobs.new? for details.
681
681
682 You can check the status of all jobs with jobs.status().
682 You can check the status of all jobs with jobs.status().
683
683
684 The jobs variable is set by IPython into the Python builtin namespace.
684 The jobs variable is set by IPython into the Python builtin namespace.
685 If you ever declare a variable named 'jobs', you will shadow this
685 If you ever declare a variable named 'jobs', you will shadow this
686 name. You can either delete your global jobs variable to regain
686 name. You can either delete your global jobs variable to regain
687 access to the job manager, or make a new name and assign it manually
687 access to the job manager, or make a new name and assign it manually
688 to the manager (stored in IPython's namespace). For example, to
688 to the manager (stored in IPython's namespace). For example, to
689 assign the job manager to the Jobs name, use:
689 assign the job manager to the Jobs name, use:
690
690
691 Jobs = __builtins__.jobs
691 Jobs = __builtins__.jobs
692
692
693 **%bookmark**::
693 **%bookmark**::
694
694
695 Manage IPython's bookmark system.
695 Manage IPython's bookmark system.
696
696
697 %bookmark <name> - set bookmark to current dir
697 %bookmark <name> - set bookmark to current dir
698 %bookmark <name> <dir> - set bookmark to <dir>
698 %bookmark <name> <dir> - set bookmark to <dir>
699 %bookmark -l - list all bookmarks
699 %bookmark -l - list all bookmarks
700 %bookmark -d <name> - remove bookmark
700 %bookmark -d <name> - remove bookmark
701 %bookmark -r - remove all bookmarks
701 %bookmark -r - remove all bookmarks
702
702
703 You can later on access a bookmarked folder with:
703 You can later on access a bookmarked folder with:
704 %cd -b <name>
704 %cd -b <name>
705 or simply '%cd <name>' if there is no directory called <name> AND
705 or simply '%cd <name>' if there is no directory called <name> AND
706 there is such a bookmark defined.
706 there is such a bookmark defined.
707
707
708 Your bookmarks persist through IPython sessions, but they are
708 Your bookmarks persist through IPython sessions, but they are
709 associated with each profile.
709 associated with each profile.
710
710
711 **%cd**::
711 **%cd**::
712
712
713 Change the current working directory.
713 Change the current working directory.
714
714
715 This command automatically maintains an internal list of directories
715 This command automatically maintains an internal list of directories
716 you visit during your IPython session, in the variable _dh. The
716 you visit during your IPython session, in the variable _dh. The
717 command %dhist shows this history nicely formatted. You can also
717 command %dhist shows this history nicely formatted. You can also
718 do 'cd -<tab>' to see directory history conveniently.
718 do 'cd -<tab>' to see directory history conveniently.
719
719
720 Usage:
720 Usage:
721
721
722 cd 'dir': changes to directory 'dir'.
722 cd 'dir': changes to directory 'dir'.
723
723
724 cd -: changes to the last visited directory.
724 cd -: changes to the last visited directory.
725
725
726 cd -<n>: changes to the n-th directory in the directory history.
726 cd -<n>: changes to the n-th directory in the directory history.
727
727
728 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
728 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
729 (note: cd <bookmark_name> is enough if there is no
729 (note: cd <bookmark_name> is enough if there is no
730 directory <bookmark_name>, but a bookmark with the name exists.)
730 directory <bookmark_name>, but a bookmark with the name exists.)
731 'cd -b <tab>' allows you to tab-complete bookmark names.
731 'cd -b <tab>' allows you to tab-complete bookmark names.
732
732
733 Options:
733 Options:
734
734
735 -q: quiet. Do not print the working directory after the cd command is
735 -q: quiet. Do not print the working directory after the cd command is
736 executed. By default IPython's cd command does print this directory,
736 executed. By default IPython's cd command does print this directory,
737 since the default prompts do not display path information.
737 since the default prompts do not display path information.
738
738
739 Note that !cd doesn't work for this purpose because the shell where
739 Note that !cd doesn't work for this purpose because the shell where
740 !command runs is immediately discarded after executing 'command'.
740 !command runs is immediately discarded after executing 'command'.
741
741
742 **%clear**::
742 **%clear**::
743
743
744 Clear various data (e.g. stored history data)
744 Clear various data (e.g. stored history data)
745
745
746 %clear out - clear output history
746 %clear out - clear output history
747 %clear in - clear input history
747 %clear in - clear input history
748 %clear shadow_compress - Compresses shadow history (to speed up ipython)
748 %clear shadow_compress - Compresses shadow history (to speed up ipython)
749 %clear shadow_nuke - permanently erase all entries in shadow history
749 %clear shadow_nuke - permanently erase all entries in shadow history
750 %clear dhist - clear dir history
750 %clear dhist - clear dir history
751
751
752 **%color_info**::
752 **%color_info**::
753
753
754 Toggle color_info.
754 Toggle color_info.
755
755
756 The color_info configuration parameter controls whether colors are
756 The color_info configuration parameter controls whether colors are
757 used for displaying object details (by things like %psource, %pfile or
757 used for displaying object details (by things like %psource, %pfile or
758 the '?' system). This function toggles this value with each call.
758 the '?' system). This function toggles this value with each call.
759
759
760 Note that unless you have a fairly recent pager (less works better
760 Note that unless you have a fairly recent pager (less works better
761 than more) in your system, using colored object information displays
761 than more) in your system, using colored object information displays
762 will not work properly. Test it and see.
762 will not work properly. Test it and see.
763
763
764 **%colors**::
764 **%colors**::
765
765
766 Switch color scheme for prompts, info system and exception handlers.
766 Switch color scheme for prompts, info system and exception handlers.
767
767
768 Currently implemented schemes: NoColor, Linux, LightBG.
768 Currently implemented schemes: NoColor, Linux, LightBG.
769
769
770 Color scheme names are not case-sensitive.
770 Color scheme names are not case-sensitive.
771
771
772 **%cpaste**::
772 **%cpaste**::
773
773
774 Allows you to paste & execute a pre-formatted code block from clipboard
774 Allows you to paste & execute a pre-formatted code block from clipboard
775
775
776 You must terminate the block with '--' (two minus-signs) alone on the
776 You must terminate the block with '--' (two minus-signs) alone on the
777 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
777 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
778 is the new sentinel for this operation)
778 is the new sentinel for this operation)
779
779
780 The block is dedented prior to execution to enable execution of method
780 The block is dedented prior to execution to enable execution of method
781 definitions. '>' and '+' characters at the beginning of a line are
781 definitions. '>' and '+' characters at the beginning of a line are
782 ignored, to allow pasting directly from e-mails or diff files. The
782 ignored, to allow pasting directly from e-mails or diff files. The
783 executed block is also assigned to variable named 'pasted_block' for
783 executed block is also assigned to variable named 'pasted_block' for
784 later editing with '%edit pasted_block'.
784 later editing with '%edit pasted_block'.
785
785
786 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
786 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
787 This assigns the pasted block to variable 'foo' as string, without
787 This assigns the pasted block to variable 'foo' as string, without
788 dedenting or executing it.
788 dedenting or executing it.
789
789
790 Do not be alarmed by garbled output on Windows (it's a readline bug).
790 Do not be alarmed by garbled output on Windows (it's a readline bug).
791 Just press enter and type -- (and press enter again) and the block
791 Just press enter and type -- (and press enter again) and the block
792 will be what was just pasted.
792 will be what was just pasted.
793
793
794 IPython statements (magics, shell escapes) are not supported (yet).
794 IPython statements (magics, shell escapes) are not supported (yet).
795
795
796 **%debug**::
796 **%debug**::
797
797
798 Activate the interactive debugger in post-mortem mode.
798 Activate the interactive debugger in post-mortem mode.
799
799
800 If an exception has just occurred, this lets you inspect its stack
800 If an exception has just occurred, this lets you inspect its stack
801 frames interactively. Note that this will always work only on the last
801 frames interactively. Note that this will always work only on the last
802 traceback that occurred, so you must call this quickly after an
802 traceback that occurred, so you must call this quickly after an
803 exception that you wish to inspect has fired, because if another one
803 exception that you wish to inspect has fired, because if another one
804 occurs, it clobbers the previous one.
804 occurs, it clobbers the previous one.
805
805
806 If you want IPython to automatically do this on every exception, see
806 If you want IPython to automatically do this on every exception, see
807 the %pdb magic for more details.
807 the %pdb magic for more details.
808
808
809 **%dhist**::
809 **%dhist**::
810
810
811 Print your history of visited directories.
811 Print your history of visited directories.
812
812
813 %dhist -> print full history\
813 %dhist -> print full history\
814 %dhist n -> print last n entries only\
814 %dhist n -> print last n entries only\
815 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\
815 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\
816
816
817 This history is automatically maintained by the %cd command, and
817 This history is automatically maintained by the %cd command, and
818 always available as the global list variable _dh. You can use %cd -<n>
818 always available as the global list variable _dh. You can use %cd -<n>
819 to go to directory number <n>.
819 to go to directory number <n>.
820
820
821 Note that most of time, you should view directory history by entering
821 Note that most of time, you should view directory history by entering
822 cd -<TAB>.
822 cd -<TAB>.
823
823
824 **%dirs**::
824 **%dirs**::
825
825
826 Return the current directory stack.
826 Return the current directory stack.
827
827
828 **%doctest_mode**::
828 **%doctest_mode**::
829
829
830 Toggle doctest mode on and off.
830 Toggle doctest mode on and off.
831
831
832 This mode allows you to toggle the prompt behavior between normal
832 This mode allows you to toggle the prompt behavior between normal
833 IPython prompts and ones that are as similar to the default IPython
833 IPython prompts and ones that are as similar to the default IPython
834 interpreter as possible.
834 interpreter as possible.
835
835
836 It also supports the pasting of code snippets that have leading '>>>'
836 It also supports the pasting of code snippets that have leading '>>>'
837 and '...' prompts in them. This means that you can paste doctests from
837 and '...' prompts in them. This means that you can paste doctests from
838 files or docstrings (even if they have leading whitespace), and the
838 files or docstrings (even if they have leading whitespace), and the
839 code will execute correctly. You can then use '%history -tn' to see
839 code will execute correctly. You can then use '%history -tn' to see
840 the translated history without line numbers; this will give you the
840 the translated history without line numbers; this will give you the
841 input after removal of all the leading prompts and whitespace, which
841 input after removal of all the leading prompts and whitespace, which
842 can be pasted back into an editor.
842 can be pasted back into an editor.
843
843
844 With these features, you can switch into this mode easily whenever you
844 With these features, you can switch into this mode easily whenever you
845 need to do testing and changes to doctests, without having to leave
845 need to do testing and changes to doctests, without having to leave
846 your existing IPython session.
846 your existing IPython session.
847
847
848 **%ed**::
848 **%ed**::
849
849
850 Alias to %edit.
850 Alias to %edit.
851
851
852 **%edit**::
852 **%edit**::
853
853
854 Bring up an editor and execute the resulting code.
854 Bring up an editor and execute the resulting code.
855
855
856 Usage:
856 Usage:
857 %edit [options] [args]
857 %edit [options] [args]
858
858
859 %edit runs IPython's editor hook. The default version of this hook is
859 %edit runs IPython's editor hook. The default version of this hook is
860 set to call the __IPYTHON__.rc.editor command. This is read from your
860 set to call the __IPYTHON__.rc.editor command. This is read from your
861 environment variable $EDITOR. If this isn't found, it will default to
861 environment variable $EDITOR. If this isn't found, it will default to
862 vi under Linux/Unix and to notepad under Windows. See the end of this
862 vi under Linux/Unix and to notepad under Windows. See the end of this
863 docstring for how to change the editor hook.
863 docstring for how to change the editor hook.
864
864
865 You can also set the value of this editor via the command line option
865 You can also set the value of this editor via the command line option
866 '-editor' or in your ipythonrc file. This is useful if you wish to use
866 '-editor' or in your ipythonrc file. This is useful if you wish to use
867 specifically for IPython an editor different from your typical default
867 specifically for IPython an editor different from your typical default
868 (and for Windows users who typically don't set environment variables).
868 (and for Windows users who typically don't set environment variables).
869
869
870 This command allows you to conveniently edit multi-line code right in
870 This command allows you to conveniently edit multi-line code right in
871 your IPython session.
871 your IPython session.
872
872
873 If called without arguments, %edit opens up an empty editor with a
873 If called without arguments, %edit opens up an empty editor with a
874 temporary file and will execute the contents of this file when you
874 temporary file and will execute the contents of this file when you
875 close it (don't forget to save it!).
875 close it (don't forget to save it!).
876
876
877
877
878 Options:
878 Options:
879
879
880 -n <number>: open the editor at a specified line number. By default,
880 -n <number>: open the editor at a specified line number. By default,
881 the IPython editor hook uses the unix syntax 'editor +N filename', but
881 the IPython editor hook uses the unix syntax 'editor +N filename', but
882 you can configure this by providing your own modified hook if your
882 you can configure this by providing your own modified hook if your
883 favorite editor supports line-number specifications with a different
883 favorite editor supports line-number specifications with a different
884 syntax.
884 syntax.
885
885
886 -p: this will call the editor with the same data as the previous time
886 -p: this will call the editor with the same data as the previous time
887 it was used, regardless of how long ago (in your current session) it
887 it was used, regardless of how long ago (in your current session) it
888 was.
888 was.
889
889
890 -r: use 'raw' input. This option only applies to input taken from the
890 -r: use 'raw' input. This option only applies to input taken from the
891 user's history. By default, the 'processed' history is used, so that
891 user's history. By default, the 'processed' history is used, so that
892 magics are loaded in their transformed version to valid Python. If
892 magics are loaded in their transformed version to valid Python. If
893 this option is given, the raw input as typed as the command line is
893 this option is given, the raw input as typed as the command line is
894 used instead. When you exit the editor, it will be executed by
894 used instead. When you exit the editor, it will be executed by
895 IPython's own processor.
895 IPython's own processor.
896
896
897 -x: do not execute the edited code immediately upon exit. This is
897 -x: do not execute the edited code immediately upon exit. This is
898 mainly useful if you are editing programs which need to be called with
898 mainly useful if you are editing programs which need to be called with
899 command line arguments, which you can then do using %run.
899 command line arguments, which you can then do using %run.
900
900
901
901
902 Arguments:
902 Arguments:
903
903
904 If arguments are given, the following possibilites exist:
904 If arguments are given, the following possibilites exist:
905
905
906 - The arguments are numbers or pairs of colon-separated numbers (like
906 - The arguments are numbers or pairs of colon-separated numbers (like
907 1 4:8 9). These are interpreted as lines of previous input to be
907 1 4:8 9). These are interpreted as lines of previous input to be
908 loaded into the editor. The syntax is the same of the %macro command.
908 loaded into the editor. The syntax is the same of the %macro command.
909
909
910 - If the argument doesn't start with a number, it is evaluated as a
910 - If the argument doesn't start with a number, it is evaluated as a
911 variable and its contents loaded into the editor. You can thus edit
911 variable and its contents loaded into the editor. You can thus edit
912 any string which contains python code (including the result of
912 any string which contains python code (including the result of
913 previous edits).
913 previous edits).
914
914
915 - If the argument is the name of an object (other than a string),
915 - If the argument is the name of an object (other than a string),
916 IPython will try to locate the file where it was defined and open the
916 IPython will try to locate the file where it was defined and open the
917 editor at the point where it is defined. You can use `%edit function`
917 editor at the point where it is defined. You can use `%edit function`
918 to load an editor exactly at the point where 'function' is defined,
918 to load an editor exactly at the point where 'function' is defined,
919 edit it and have the file be executed automatically.
919 edit it and have the file be executed automatically.
920
920
921 If the object is a macro (see %macro for details), this opens up your
921 If the object is a macro (see %macro for details), this opens up your
922 specified editor with a temporary file containing the macro's data.
922 specified editor with a temporary file containing the macro's data.
923 Upon exit, the macro is reloaded with the contents of the file.
923 Upon exit, the macro is reloaded with the contents of the file.
924
924
925 Note: opening at an exact line is only supported under Unix, and some
925 Note: opening at an exact line is only supported under Unix, and some
926 editors (like kedit and gedit up to Gnome 2.8) do not understand the
926 editors (like kedit and gedit up to Gnome 2.8) do not understand the
927 '+NUMBER' parameter necessary for this feature. Good editors like
927 '+NUMBER' parameter necessary for this feature. Good editors like
928 (X)Emacs, vi, jed, pico and joe all do.
928 (X)Emacs, vi, jed, pico and joe all do.
929
929
930 - If the argument is not found as a variable, IPython will look for a
930 - If the argument is not found as a variable, IPython will look for a
931 file with that name (adding .py if necessary) and load it into the
931 file with that name (adding .py if necessary) and load it into the
932 editor. It will execute its contents with execfile() when you exit,
932 editor. It will execute its contents with execfile() when you exit,
933 loading any code in the file into your interactive namespace.
933 loading any code in the file into your interactive namespace.
934
934
935 After executing your code, %edit will return as output the code you
935 After executing your code, %edit will return as output the code you
936 typed in the editor (except when it was an existing file). This way
936 typed in the editor (except when it was an existing file). This way
937 you can reload the code in further invocations of %edit as a variable,
937 you can reload the code in further invocations of %edit as a variable,
938 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
938 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
939 the output.
939 the output.
940
940
941 Note that %edit is also available through the alias %ed.
941 Note that %edit is also available through the alias %ed.
942
942
943 This is an example of creating a simple function inside the editor and
943 This is an example of creating a simple function inside the editor and
944 then modifying it. First, start up the editor:
944 then modifying it. First, start up the editor:
945
945
946 In [1]: ed\
946 In [1]: ed\
947 Editing... done. Executing edited code...\
947 Editing... done. Executing edited code...\
948 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
948 Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n'
949
949
950 We can then call the function foo():
950 We can then call the function foo():
951
951
952 In [2]: foo()\
952 In [2]: foo()\
953 foo() was defined in an editing session
953 foo() was defined in an editing session
954
954
955 Now we edit foo. IPython automatically loads the editor with the
955 Now we edit foo. IPython automatically loads the editor with the
956 (temporary) file where foo() was previously defined:
956 (temporary) file where foo() was previously defined:
957
957
958 In [3]: ed foo\
958 In [3]: ed foo\
959 Editing... done. Executing edited code...
959 Editing... done. Executing edited code...
960
960
961 And if we call foo() again we get the modified version:
961 And if we call foo() again we get the modified version:
962
962
963 In [4]: foo()\
963 In [4]: foo()\
964 foo() has now been changed!
964 foo() has now been changed!
965
965
966 Here is an example of how to edit a code snippet successive
966 Here is an example of how to edit a code snippet successive
967 times. First we call the editor:
967 times. First we call the editor:
968
968
969 In [8]: ed\
969 In [8]: ed\
970 Editing... done. Executing edited code...\
970 Editing... done. Executing edited code...\
971 hello\
971 hello\
972 Out[8]: "print 'hello'\n"
972 Out[8]: "print 'hello'\n"
973
973
974 Now we call it again with the previous output (stored in _):
974 Now we call it again with the previous output (stored in _):
975
975
976 In [9]: ed _\
976 In [9]: ed _\
977 Editing... done. Executing edited code...\
977 Editing... done. Executing edited code...\
978 hello world\
978 hello world\
979 Out[9]: "print 'hello world'\n"
979 Out[9]: "print 'hello world'\n"
980
980
981 Now we call it with the output #8 (stored in _8, also as Out[8]):
981 Now we call it with the output #8 (stored in _8, also as Out[8]):
982
982
983 In [10]: ed _8\
983 In [10]: ed _8\
984 Editing... done. Executing edited code...\
984 Editing... done. Executing edited code...\
985 hello again\
985 hello again\
986 Out[10]: "print 'hello again'\n"
986 Out[10]: "print 'hello again'\n"
987
987
988
988
989 Changing the default editor hook:
989 Changing the default editor hook:
990
990
991 If you wish to write your own editor hook, you can put it in a
991 If you wish to write your own editor hook, you can put it in a
992 configuration file which you load at startup time. The default hook
992 configuration file which you load at startup time. The default hook
993 is defined in the IPython.hooks module, and you can use that as a
993 is defined in the IPython.hooks module, and you can use that as a
994 starting example for further modifications. That file also has
994 starting example for further modifications. That file also has
995 general instructions on how to set a new hook for use once you've
995 general instructions on how to set a new hook for use once you've
996 defined it.
996 defined it.
997
997
998 **%env**::
998 **%env**::
999
999
1000 List environment variables.
1000 List environment variables.
1001
1001
1002 **%exit**::
1002 **%exit**::
1003
1003
1004 Exit IPython, confirming if configured to do so.
1004 Exit IPython, confirming if configured to do so.
1005
1005
1006 You can configure whether IPython asks for confirmation upon exit by
1006 You can configure whether IPython asks for confirmation upon exit by
1007 setting the confirm_exit flag in the ipythonrc file.
1007 setting the confirm_exit flag in the ipythonrc file.
1008
1008
1009 **%hist**::
1009 **%hist**::
1010
1010
1011 Alternate name for %history.
1011 Alternate name for %history.
1012
1012
1013 **%history**::
1013 **%history**::
1014
1014
1015 Print input history (_i<n> variables), with most recent last.
1015 Print input history (_i<n> variables), with most recent last.
1016
1016
1017 %history -> print at most 40 inputs (some may be multi-line)\
1017 %history -> print at most 40 inputs (some may be multi-line)\
1018 %history n -> print at most n inputs\
1018 %history n -> print at most n inputs\
1019 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\
1019 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\
1020
1020
1021 Each input's number <n> is shown, and is accessible as the
1021 Each input's number <n> is shown, and is accessible as the
1022 automatically generated variable _i<n>. Multi-line statements are
1022 automatically generated variable _i<n>. Multi-line statements are
1023 printed starting at a new line for easy copy/paste.
1023 printed starting at a new line for easy copy/paste.
1024
1024
1025
1025
1026 Options:
1026 Options:
1027
1027
1028 -n: do NOT print line numbers. This is useful if you want to get a
1028 -n: do NOT print line numbers. This is useful if you want to get a
1029 printout of many lines which can be directly pasted into a text
1029 printout of many lines which can be directly pasted into a text
1030 editor.
1030 editor.
1031
1031
1032 This feature is only available if numbered prompts are in use.
1032 This feature is only available if numbered prompts are in use.
1033
1033
1034 -t: (default) print the 'translated' history, as IPython understands it.
1034 -t: (default) print the 'translated' history, as IPython understands it.
1035 IPython filters your input and converts it all into valid Python source
1035 IPython filters your input and converts it all into valid Python source
1036 before executing it (things like magics or aliases are turned into
1036 before executing it (things like magics or aliases are turned into
1037 function calls, for example). With this option, you'll see the native
1037 function calls, for example). With this option, you'll see the native
1038 history instead of the user-entered version: '%cd /' will be seen as
1038 history instead of the user-entered version: '%cd /' will be seen as
1039 '_ip.magic("%cd /")' instead of '%cd /'.
1039 '_ip.magic("%cd /")' instead of '%cd /'.
1040
1040
1041 -r: print the 'raw' history, i.e. the actual commands you typed.
1041 -r: print the 'raw' history, i.e. the actual commands you typed.
1042
1042
1043 -g: treat the arg as a pattern to grep for in (full) history.
1043 -g: treat the arg as a pattern to grep for in (full) history.
1044 This includes the "shadow history" (almost all commands ever written).
1044 This includes the "shadow history" (almost all commands ever written).
1045 Use '%hist -g' to show full shadow history (may be very long).
1045 Use '%hist -g' to show full shadow history (may be very long).
1046 In shadow history, every index nuwber starts with 0.
1046 In shadow history, every index nuwber starts with 0.
1047
1047
1048 -f FILENAME: instead of printing the output to the screen, redirect it to
1048 -f FILENAME: instead of printing the output to the screen, redirect it to
1049 the given file. The file is always overwritten, though IPython asks for
1049 the given file. The file is always overwritten, though IPython asks for
1050 confirmation first if it already exists.
1050 confirmation first if it already exists.
1051
1051
1052 **%logoff**::
1052 **%logoff**::
1053
1053
1054 Temporarily stop logging.
1054 Temporarily stop logging.
1055
1055
1056 You must have previously started logging.
1056 You must have previously started logging.
1057
1057
1058 **%logon**::
1058 **%logon**::
1059
1059
1060 Restart logging.
1060 Restart logging.
1061
1061
1062 This function is for restarting logging which you've temporarily
1062 This function is for restarting logging which you've temporarily
1063 stopped with %logoff. For starting logging for the first time, you
1063 stopped with %logoff. For starting logging for the first time, you
1064 must use the %logstart function, which allows you to specify an
1064 must use the %logstart function, which allows you to specify an
1065 optional log filename.
1065 optional log filename.
1066
1066
1067 **%logstart**::
1067 **%logstart**::
1068
1068
1069 Start logging anywhere in a session.
1069 Start logging anywhere in a session.
1070
1070
1071 %logstart [-o|-r|-t] [log_name [log_mode]]
1071 %logstart [-o|-r|-t] [log_name [log_mode]]
1072
1072
1073 If no name is given, it defaults to a file named 'ipython_log.py' in your
1073 If no name is given, it defaults to a file named 'ipython_log.py' in your
1074 current directory, in 'rotate' mode (see below).
1074 current directory, in 'rotate' mode (see below).
1075
1075
1076 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1076 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1077 history up to that point and then continues logging.
1077 history up to that point and then continues logging.
1078
1078
1079 %logstart takes a second optional parameter: logging mode. This can be one
1079 %logstart takes a second optional parameter: logging mode. This can be one
1080 of (note that the modes are given unquoted):\
1080 of (note that the modes are given unquoted):\
1081 append: well, that says it.\
1081 append: well, that says it.\
1082 backup: rename (if exists) to name~ and start name.\
1082 backup: rename (if exists) to name~ and start name.\
1083 global: single logfile in your home dir, appended to.\
1083 global: single logfile in your home dir, appended to.\
1084 over : overwrite existing log.\
1084 over : overwrite existing log.\
1085 rotate: create rotating logs name.1~, name.2~, etc.
1085 rotate: create rotating logs name.1~, name.2~, etc.
1086
1086
1087 Options:
1087 Options:
1088
1088
1089 -o: log also IPython's output. In this mode, all commands which
1089 -o: log also IPython's output. In this mode, all commands which
1090 generate an Out[NN] prompt are recorded to the logfile, right after
1090 generate an Out[NN] prompt are recorded to the logfile, right after
1091 their corresponding input line. The output lines are always
1091 their corresponding input line. The output lines are always
1092 prepended with a '#[Out]# ' marker, so that the log remains valid
1092 prepended with a '#[Out]# ' marker, so that the log remains valid
1093 Python code.
1093 Python code.
1094
1094
1095 Since this marker is always the same, filtering only the output from
1095 Since this marker is always the same, filtering only the output from
1096 a log is very easy, using for example a simple awk call:
1096 a log is very easy, using for example a simple awk call:
1097
1097
1098 awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py
1098 awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py
1099
1099
1100 -r: log 'raw' input. Normally, IPython's logs contain the processed
1100 -r: log 'raw' input. Normally, IPython's logs contain the processed
1101 input, so that user lines are logged in their final form, converted
1101 input, so that user lines are logged in their final form, converted
1102 into valid Python. For example, %Exit is logged as
1102 into valid Python. For example, %Exit is logged as
1103 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1103 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1104 exactly as typed, with no transformations applied.
1104 exactly as typed, with no transformations applied.
1105
1105
1106 -t: put timestamps before each input line logged (these are put in
1106 -t: put timestamps before each input line logged (these are put in
1107 comments).
1107 comments).
1108
1108
1109 **%logstate**::
1109 **%logstate**::
1110
1110
1111 Print the status of the logging system.
1111 Print the status of the logging system.
1112
1112
1113 **%logstop**::
1113 **%logstop**::
1114
1114
1115 Fully stop logging and close log file.
1115 Fully stop logging and close log file.
1116
1116
1117 In order to start logging again, a new %logstart call needs to be made,
1117 In order to start logging again, a new %logstart call needs to be made,
1118 possibly (though not necessarily) with a new filename, mode and other
1118 possibly (though not necessarily) with a new filename, mode and other
1119 options.
1119 options.
1120
1120
1121 **%lsmagic**::
1121 **%lsmagic**::
1122
1122
1123 List currently available magic functions.
1123 List currently available magic functions.
1124
1124
1125 **%macro**::
1125 **%macro**::
1126
1126
1127 Define a set of input lines as a macro for future re-execution.
1127 Define a set of input lines as a macro for future re-execution.
1128
1128
1129 Usage:\
1129 Usage:\
1130 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1130 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1131
1131
1132 Options:
1132 Options:
1133
1133
1134 -r: use 'raw' input. By default, the 'processed' history is used,
1134 -r: use 'raw' input. By default, the 'processed' history is used,
1135 so that magics are loaded in their transformed version to valid
1135 so that magics are loaded in their transformed version to valid
1136 Python. If this option is given, the raw input as typed as the
1136 Python. If this option is given, the raw input as typed as the
1137 command line is used instead.
1137 command line is used instead.
1138
1138
1139 This will define a global variable called `name` which is a string
1139 This will define a global variable called `name` which is a string
1140 made of joining the slices and lines you specify (n1,n2,... numbers
1140 made of joining the slices and lines you specify (n1,n2,... numbers
1141 above) from your input history into a single string. This variable
1141 above) from your input history into a single string. This variable
1142 acts like an automatic function which re-executes those lines as if
1142 acts like an automatic function which re-executes those lines as if
1143 you had typed them. You just type 'name' at the prompt and the code
1143 you had typed them. You just type 'name' at the prompt and the code
1144 executes.
1144 executes.
1145
1145
1146 The notation for indicating number ranges is: n1-n2 means 'use line
1146 The notation for indicating number ranges is: n1-n2 means 'use line
1147 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1147 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1148 using the lines numbered 5,6 and 7.
1148 using the lines numbered 5,6 and 7.
1149
1149
1150 Note: as a 'hidden' feature, you can also use traditional python slice
1150 Note: as a 'hidden' feature, you can also use traditional python slice
1151 notation, where N:M means numbers N through M-1.
1151 notation, where N:M means numbers N through M-1.
1152
1152
1153 For example, if your history contains (%hist prints it):
1153 For example, if your history contains (%hist prints it):
1154
1154
1155 44: x=1\
1155 44: x=1\
1156 45: y=3\
1156 45: y=3\
1157 46: z=x+y\
1157 46: z=x+y\
1158 47: print x\
1158 47: print x\
1159 48: a=5\
1159 48: a=5\
1160 49: print 'x',x,'y',y\
1160 49: print 'x',x,'y',y\
1161
1161
1162 you can create a macro with lines 44 through 47 (included) and line 49
1162 you can create a macro with lines 44 through 47 (included) and line 49
1163 called my_macro with:
1163 called my_macro with:
1164
1164
1165 In [51]: %macro my_macro 44-47 49
1165 In [51]: %macro my_macro 44-47 49
1166
1166
1167 Now, typing `my_macro` (without quotes) will re-execute all this code
1167 Now, typing `my_macro` (without quotes) will re-execute all this code
1168 in one pass.
1168 in one pass.
1169
1169
1170 You don't need to give the line-numbers in order, and any given line
1170 You don't need to give the line-numbers in order, and any given line
1171 number can appear multiple times. You can assemble macros with any
1171 number can appear multiple times. You can assemble macros with any
1172 lines from your input history in any order.
1172 lines from your input history in any order.
1173
1173
1174 The macro is a simple object which holds its value in an attribute,
1174 The macro is a simple object which holds its value in an attribute,
1175 but IPython's display system checks for macros and executes them as
1175 but IPython's display system checks for macros and executes them as
1176 code instead of printing them when you type their name.
1176 code instead of printing them when you type their name.
1177
1177
1178 You can view a macro's contents by explicitly printing it with:
1178 You can view a macro's contents by explicitly printing it with:
1179
1179
1180 'print macro_name'.
1180 'print macro_name'.
1181
1181
1182 For one-off cases which DON'T contain magic function calls in them you
1182 For one-off cases which DON'T contain magic function calls in them you
1183 can obtain similar results by explicitly executing slices from your
1183 can obtain similar results by explicitly executing slices from your
1184 input history with:
1184 input history with:
1185
1185
1186 In [60]: exec In[44:48]+In[49]
1186 In [60]: exec In[44:48]+In[49]
1187
1187
1188 **%magic**::
1188 **%magic**::
1189
1189
1190 Print information about the magic function system.
1190 Print information about the magic function system.
1191
1191
1192 **%mglob**::
1192 **%mglob**::
1193
1193
1194 This program allows specifying filenames with "mglob" mechanism.
1194 This program allows specifying filenames with "mglob" mechanism.
1195 Supported syntax in globs (wilcard matching patterns)::
1195 Supported syntax in globs (wilcard matching patterns)::
1196
1196
1197 *.cpp ?ellowo*
1197 *.cpp ?ellowo*
1198 - obvious. Differs from normal glob in that dirs are not included.
1198 - obvious. Differs from normal glob in that dirs are not included.
1199 Unix users might want to write this as: "*.cpp" "?ellowo*"
1199 Unix users might want to write this as: "*.cpp" "?ellowo*"
1200 rec:/usr/share=*.txt,*.doc
1200 rec:/usr/share=*.txt,*.doc
1201 - get all *.txt and *.doc under /usr/share,
1201 - get all *.txt and *.doc under /usr/share,
1202 recursively
1202 recursively
1203 rec:/usr/share
1203 rec:/usr/share
1204 - All files under /usr/share, recursively
1204 - All files under /usr/share, recursively
1205 rec:*.py
1205 rec:*.py
1206 - All .py files under current working dir, recursively
1206 - All .py files under current working dir, recursively
1207 foo
1207 foo
1208 - File or dir foo
1208 - File or dir foo
1209 !*.bak readme*
1209 !*.bak readme*
1210 - readme*, exclude files ending with .bak
1210 - readme*, exclude files ending with .bak
1211 !.svn/ !.hg/ !*_Data/ rec:.
1211 !.svn/ !.hg/ !*_Data/ rec:.
1212 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
1212 - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse.
1213 Trailing / is the key, \ does not work!
1213 Trailing / is the key, \ does not work!
1214 dir:foo
1214 dir:foo
1215 - the directory foo if it exists (not files in foo)
1215 - the directory foo if it exists (not files in foo)
1216 dir:*
1216 dir:*
1217 - all directories in current folder
1217 - all directories in current folder
1218 foo.py bar.* !h* rec:*.py
1218 foo.py bar.* !h* rec:*.py
1219 - Obvious. !h* exclusion only applies for rec:*.py.
1219 - Obvious. !h* exclusion only applies for rec:*.py.
1220 foo.py is *not* included twice.
1220 foo.py is *not* included twice.
1221 @filelist.txt
1221 @filelist.txt
1222 - All files listed in 'filelist.txt' file, on separate lines.
1222 - All files listed in 'filelist.txt' file, on separate lines.
1223
1223
1224 **%page**::
1224 **%page**::
1225
1225
1226 Pretty print the object and display it through a pager.
1226 Pretty print the object and display it through a pager.
1227
1227
1228 %page [options] OBJECT
1228 %page [options] OBJECT
1229
1229
1230 If no object is given, use _ (last output).
1230 If no object is given, use _ (last output).
1231
1231
1232 Options:
1232 Options:
1233
1233
1234 -r: page str(object), don't pretty-print it.
1234 -r: page str(object), don't pretty-print it.
1235
1235
1236 **%pdb**::
1236 **%pdb**::
1237
1237
1238 Control the automatic calling of the pdb interactive debugger.
1238 Control the automatic calling of the pdb interactive debugger.
1239
1239
1240 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1240 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1241 argument it works as a toggle.
1241 argument it works as a toggle.
1242
1242
1243 When an exception is triggered, IPython can optionally call the
1243 When an exception is triggered, IPython can optionally call the
1244 interactive pdb debugger after the traceback printout. %pdb toggles
1244 interactive pdb debugger after the traceback printout. %pdb toggles
1245 this feature on and off.
1245 this feature on and off.
1246
1246
1247 The initial state of this feature is set in your ipythonrc
1247 The initial state of this feature is set in your ipythonrc
1248 configuration file (the variable is called 'pdb').
1248 configuration file (the variable is called 'pdb').
1249
1249
1250 If you want to just activate the debugger AFTER an exception has fired,
1250 If you want to just activate the debugger AFTER an exception has fired,
1251 without having to type '%pdb on' and rerunning your code, you can use
1251 without having to type '%pdb on' and rerunning your code, you can use
1252 the %debug magic.
1252 the %debug magic.
1253
1253
1254 **%pdef**::
1254 **%pdef**::
1255
1255
1256 Print the definition header for any callable object.
1256 Print the definition header for any callable object.
1257
1257
1258 If the object is a class, print the constructor information.
1258 If the object is a class, print the constructor information.
1259
1259
1260 **%pdoc**::
1260 **%pdoc**::
1261
1261
1262 Print the docstring for an object.
1262 Print the docstring for an object.
1263
1263
1264 If the given object is a class, it will print both the class and the
1264 If the given object is a class, it will print both the class and the
1265 constructor docstrings.
1265 constructor docstrings.
1266
1266
1267 **%pfile**::
1267 **%pfile**::
1268
1268
1269 Print (or run through pager) the file where an object is defined.
1269 Print (or run through pager) the file where an object is defined.
1270
1270
1271 The file opens at the line where the object definition begins. IPython
1271 The file opens at the line where the object definition begins. IPython
1272 will honor the environment variable PAGER if set, and otherwise will
1272 will honor the environment variable PAGER if set, and otherwise will
1273 do its best to print the file in a convenient form.
1273 do its best to print the file in a convenient form.
1274
1274
1275 If the given argument is not an object currently defined, IPython will
1275 If the given argument is not an object currently defined, IPython will
1276 try to interpret it as a filename (automatically adding a .py extension
1276 try to interpret it as a filename (automatically adding a .py extension
1277 if needed). You can thus use %pfile as a syntax highlighting code
1277 if needed). You can thus use %pfile as a syntax highlighting code
1278 viewer.
1278 viewer.
1279
1279
1280 **%pinfo**::
1280 **%pinfo**::
1281
1281
1282 Provide detailed information about an object.
1282 Provide detailed information about an object.
1283
1283
1284 '%pinfo object' is just a synonym for object? or ?object.
1284 '%pinfo object' is just a synonym for object? or ?object.
1285
1285
1286 **%popd**::
1286 **%popd**::
1287
1287
1288 Change to directory popped off the top of the stack.
1288 Change to directory popped off the top of the stack.
1289
1289
1290 **%profile**::
1290 **%profile**::
1291
1291
1292 Print your currently active IPyhton profile.
1292 Print your currently active IPyhton profile.
1293
1293
1294 **%prun**::
1294 **%prun**::
1295
1295
1296 Run a statement through the python code profiler.
1296 Run a statement through the python code profiler.
1297
1297
1298 Usage:\
1298 Usage:\
1299 %prun [options] statement
1299 %prun [options] statement
1300
1300
1301 The given statement (which doesn't require quote marks) is run via the
1301 The given statement (which doesn't require quote marks) is run via the
1302 python profiler in a manner similar to the profile.run() function.
1302 python profiler in a manner similar to the profile.run() function.
1303 Namespaces are internally managed to work correctly; profile.run
1303 Namespaces are internally managed to work correctly; profile.run
1304 cannot be used in IPython because it makes certain assumptions about
1304 cannot be used in IPython because it makes certain assumptions about
1305 namespaces which do not hold under IPython.
1305 namespaces which do not hold under IPython.
1306
1306
1307 Options:
1307 Options:
1308
1308
1309 -l <limit>: you can place restrictions on what or how much of the
1309 -l <limit>: you can place restrictions on what or how much of the
1310 profile gets printed. The limit value can be:
1310 profile gets printed. The limit value can be:
1311
1311
1312 * A string: only information for function names containing this string
1312 * A string: only information for function names containing this string
1313 is printed.
1313 is printed.
1314
1314
1315 * An integer: only these many lines are printed.
1315 * An integer: only these many lines are printed.
1316
1316
1317 * A float (between 0 and 1): this fraction of the report is printed
1317 * A float (between 0 and 1): this fraction of the report is printed
1318 (for example, use a limit of 0.4 to see the topmost 40% only).
1318 (for example, use a limit of 0.4 to see the topmost 40% only).
1319
1319
1320 You can combine several limits with repeated use of the option. For
1320 You can combine several limits with repeated use of the option. For
1321 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1321 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1322 information about class constructors.
1322 information about class constructors.
1323
1323
1324 -r: return the pstats.Stats object generated by the profiling. This
1324 -r: return the pstats.Stats object generated by the profiling. This
1325 object has all the information about the profile in it, and you can
1325 object has all the information about the profile in it, and you can
1326 later use it for further analysis or in other functions.
1326 later use it for further analysis or in other functions.
1327
1327
1328 -s <key>: sort profile by given key. You can provide more than one key
1328 -s <key>: sort profile by given key. You can provide more than one key
1329 by using the option several times: '-s key1 -s key2 -s key3...'. The
1329 by using the option several times: '-s key1 -s key2 -s key3...'. The
1330 default sorting key is 'time'.
1330 default sorting key is 'time'.
1331
1331
1332 The following is copied verbatim from the profile documentation
1332 The following is copied verbatim from the profile documentation
1333 referenced below:
1333 referenced below:
1334
1334
1335 When more than one key is provided, additional keys are used as
1335 When more than one key is provided, additional keys are used as
1336 secondary criteria when the there is equality in all keys selected
1336 secondary criteria when the there is equality in all keys selected
1337 before them.
1337 before them.
1338
1338
1339 Abbreviations can be used for any key names, as long as the
1339 Abbreviations can be used for any key names, as long as the
1340 abbreviation is unambiguous. The following are the keys currently
1340 abbreviation is unambiguous. The following are the keys currently
1341 defined:
1341 defined:
1342
1342
1343 Valid Arg Meaning\
1343 Valid Arg Meaning\
1344 "calls" call count\
1344 "calls" call count\
1345 "cumulative" cumulative time\
1345 "cumulative" cumulative time\
1346 "file" file name\
1346 "file" file name\
1347 "module" file name\
1347 "module" file name\
1348 "pcalls" primitive call count\
1348 "pcalls" primitive call count\
1349 "line" line number\
1349 "line" line number\
1350 "name" function name\
1350 "name" function name\
1351 "nfl" name/file/line\
1351 "nfl" name/file/line\
1352 "stdname" standard name\
1352 "stdname" standard name\
1353 "time" internal time
1353 "time" internal time
1354
1354
1355 Note that all sorts on statistics are in descending order (placing
1355 Note that all sorts on statistics are in descending order (placing
1356 most time consuming items first), where as name, file, and line number
1356 most time consuming items first), where as name, file, and line number
1357 searches are in ascending order (i.e., alphabetical). The subtle
1357 searches are in ascending order (i.e., alphabetical). The subtle
1358 distinction between "nfl" and "stdname" is that the standard name is a
1358 distinction between "nfl" and "stdname" is that the standard name is a
1359 sort of the name as printed, which means that the embedded line
1359 sort of the name as printed, which means that the embedded line
1360 numbers get compared in an odd way. For example, lines 3, 20, and 40
1360 numbers get compared in an odd way. For example, lines 3, 20, and 40
1361 would (if the file names were the same) appear in the string order
1361 would (if the file names were the same) appear in the string order
1362 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1362 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1363 line numbers. In fact, sort_stats("nfl") is the same as
1363 line numbers. In fact, sort_stats("nfl") is the same as
1364 sort_stats("name", "file", "line").
1364 sort_stats("name", "file", "line").
1365
1365
1366 -T <filename>: save profile results as shown on screen to a text
1366 -T <filename>: save profile results as shown on screen to a text
1367 file. The profile is still shown on screen.
1367 file. The profile is still shown on screen.
1368
1368
1369 -D <filename>: save (via dump_stats) profile statistics to given
1369 -D <filename>: save (via dump_stats) profile statistics to given
1370 filename. This data is in a format understod by the pstats module, and
1370 filename. This data is in a format understod by the pstats module, and
1371 is generated by a call to the dump_stats() method of profile
1371 is generated by a call to the dump_stats() method of profile
1372 objects. The profile is still shown on screen.
1372 objects. The profile is still shown on screen.
1373
1373
1374 If you want to run complete programs under the profiler's control, use
1374 If you want to run complete programs under the profiler's control, use
1375 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1375 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1376 contains profiler specific options as described here.
1376 contains profiler specific options as described here.
1377
1377
1378 You can read the complete documentation for the profile module with:\
1378 You can read the complete documentation for the profile module with:\
1379 In [1]: import profile; profile.help()
1379 In [1]: import profile; profile.help()
1380
1380
1381 **%psearch**::
1381 **%psearch**::
1382
1382
1383 Search for object in namespaces by wildcard.
1383 Search for object in namespaces by wildcard.
1384
1384
1385 %psearch [options] PATTERN [OBJECT TYPE]
1385 %psearch [options] PATTERN [OBJECT TYPE]
1386
1386
1387 Note: ? can be used as a synonym for %psearch, at the beginning or at
1387 Note: ? can be used as a synonym for %psearch, at the beginning or at
1388 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
1388 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
1389 rest of the command line must be unchanged (options come first), so
1389 rest of the command line must be unchanged (options come first), so
1390 for example the following forms are equivalent
1390 for example the following forms are equivalent
1391
1391
1392 %psearch -i a* function
1392 %psearch -i a* function
1393 -i a* function?
1393 -i a* function?
1394 ?-i a* function
1394 ?-i a* function
1395
1395
1396 Arguments:
1396 Arguments:
1397
1397
1398 PATTERN
1398 PATTERN
1399
1399
1400 where PATTERN is a string containing * as a wildcard similar to its
1400 where PATTERN is a string containing * as a wildcard similar to its
1401 use in a shell. The pattern is matched in all namespaces on the
1401 use in a shell. The pattern is matched in all namespaces on the
1402 search path. By default objects starting with a single _ are not
1402 search path. By default objects starting with a single _ are not
1403 matched, many IPython generated objects have a single
1403 matched, many IPython generated objects have a single
1404 underscore. The default is case insensitive matching. Matching is
1404 underscore. The default is case insensitive matching. Matching is
1405 also done on the attributes of objects and not only on the objects
1405 also done on the attributes of objects and not only on the objects
1406 in a module.
1406 in a module.
1407
1407
1408 [OBJECT TYPE]
1408 [OBJECT TYPE]
1409
1409
1410 Is the name of a python type from the types module. The name is
1410 Is the name of a python type from the types module. The name is
1411 given in lowercase without the ending type, ex. StringType is
1411 given in lowercase without the ending type, ex. StringType is
1412 written string. By adding a type here only objects matching the
1412 written string. By adding a type here only objects matching the
1413 given type are matched. Using all here makes the pattern match all
1413 given type are matched. Using all here makes the pattern match all
1414 types (this is the default).
1414 types (this is the default).
1415
1415
1416 Options:
1416 Options:
1417
1417
1418 -a: makes the pattern match even objects whose names start with a
1418 -a: makes the pattern match even objects whose names start with a
1419 single underscore. These names are normally ommitted from the
1419 single underscore. These names are normally ommitted from the
1420 search.
1420 search.
1421
1421
1422 -i/-c: make the pattern case insensitive/sensitive. If neither of
1422 -i/-c: make the pattern case insensitive/sensitive. If neither of
1423 these options is given, the default is read from your ipythonrc
1423 these options is given, the default is read from your ipythonrc
1424 file. The option name which sets this value is
1424 file. The option name which sets this value is
1425 'wildcards_case_sensitive'. If this option is not specified in your
1425 'wildcards_case_sensitive'. If this option is not specified in your
1426 ipythonrc file, IPython's internal default is to do a case sensitive
1426 ipythonrc file, IPython's internal default is to do a case sensitive
1427 search.
1427 search.
1428
1428
1429 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
1429 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
1430 specifiy can be searched in any of the following namespaces:
1430 specifiy can be searched in any of the following namespaces:
1431 'builtin', 'user', 'user_global','internal', 'alias', where
1431 'builtin', 'user', 'user_global','internal', 'alias', where
1432 'builtin' and 'user' are the search defaults. Note that you should
1432 'builtin' and 'user' are the search defaults. Note that you should
1433 not use quotes when specifying namespaces.
1433 not use quotes when specifying namespaces.
1434
1434
1435 'Builtin' contains the python module builtin, 'user' contains all
1435 'Builtin' contains the python module builtin, 'user' contains all
1436 user data, 'alias' only contain the shell aliases and no python
1436 user data, 'alias' only contain the shell aliases and no python
1437 objects, 'internal' contains objects used by IPython. The
1437 objects, 'internal' contains objects used by IPython. The
1438 'user_global' namespace is only used by embedded IPython instances,
1438 'user_global' namespace is only used by embedded IPython instances,
1439 and it contains module-level globals. You can add namespaces to the
1439 and it contains module-level globals. You can add namespaces to the
1440 search with -s or exclude them with -e (these options can be given
1440 search with -s or exclude them with -e (these options can be given
1441 more than once).
1441 more than once).
1442
1442
1443 Examples:
1443 Examples:
1444
1444
1445 %psearch a* -> objects beginning with an a
1445 %psearch a* -> objects beginning with an a
1446 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
1446 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
1447 %psearch a* function -> all functions beginning with an a
1447 %psearch a* function -> all functions beginning with an a
1448 %psearch re.e* -> objects beginning with an e in module re
1448 %psearch re.e* -> objects beginning with an e in module re
1449 %psearch r*.e* -> objects that start with e in modules starting in r
1449 %psearch r*.e* -> objects that start with e in modules starting in r
1450 %psearch r*.* string -> all strings in modules beginning with r
1450 %psearch r*.* string -> all strings in modules beginning with r
1451
1451
1452 Case sensitve search:
1452 Case sensitve search:
1453
1453
1454 %psearch -c a* list all object beginning with lower case a
1454 %psearch -c a* list all object beginning with lower case a
1455
1455
1456 Show objects beginning with a single _:
1456 Show objects beginning with a single _:
1457
1457
1458 %psearch -a _* list objects beginning with a single underscore
1458 %psearch -a _* list objects beginning with a single underscore
1459
1459
1460 **%psource**::
1460 **%psource**::
1461
1461
1462 Print (or run through pager) the source code for an object.
1462 Print (or run through pager) the source code for an object.
1463
1463
1464 **%pushd**::
1464 **%pushd**::
1465
1465
1466 Place the current dir on stack and change directory.
1466 Place the current dir on stack and change directory.
1467
1467
1468 Usage:\
1468 Usage:\
1469 %pushd ['dirname']
1469 %pushd ['dirname']
1470
1470
1471 **%pwd**::
1471 **%pwd**::
1472
1472
1473 Return the current working directory path.
1473 Return the current working directory path.
1474
1474
1475 **%pycat**::
1475 **%pycat**::
1476
1476
1477 Show a syntax-highlighted file through a pager.
1477 Show a syntax-highlighted file through a pager.
1478
1478
1479 This magic is similar to the cat utility, but it will assume the file
1479 This magic is similar to the cat utility, but it will assume the file
1480 to be Python source and will show it with syntax highlighting.
1480 to be Python source and will show it with syntax highlighting.
1481
1481
1482 **%quickref**::
1482 **%quickref**::
1483
1483
1484 Show a quick reference sheet
1484 Show a quick reference sheet
1485
1485
1486 **%quit**::
1486 **%quit**::
1487
1487
1488 Exit IPython, confirming if configured to do so (like %exit)
1488 Exit IPython, confirming if configured to do so (like %exit)
1489
1489
1490 **%r**::
1490 **%r**::
1491
1491
1492 Repeat previous input.
1492 Repeat previous input.
1493
1493
1494 Note: Consider using the more powerfull %rep instead!
1494 Note: Consider using the more powerfull %rep instead!
1495
1495
1496 If given an argument, repeats the previous command which starts with
1496 If given an argument, repeats the previous command which starts with
1497 the same string, otherwise it just repeats the previous input.
1497 the same string, otherwise it just repeats the previous input.
1498
1498
1499 Shell escaped commands (with ! as first character) are not recognized
1499 Shell escaped commands (with ! as first character) are not recognized
1500 by this system, only pure python code and magic commands.
1500 by this system, only pure python code and magic commands.
1501
1501
1502 **%rehashdir**::
1502 **%rehashdir**::
1503
1503
1504 Add executables in all specified dirs to alias table
1504 Add executables in all specified dirs to alias table
1505
1505
1506 Usage:
1506 Usage:
1507
1507
1508 %rehashdir c:/bin;c:/tools
1508 %rehashdir c:/bin;c:/tools
1509 - Add all executables under c:/bin and c:/tools to alias table, in
1509 - Add all executables under c:/bin and c:/tools to alias table, in
1510 order to make them directly executable from any directory.
1510 order to make them directly executable from any directory.
1511
1511
1512 Without arguments, add all executables in current directory.
1512 Without arguments, add all executables in current directory.
1513
1513
1514 **%rehashx**::
1514 **%rehashx**::
1515
1515
1516 Update the alias table with all executable files in $PATH.
1516 Update the alias table with all executable files in $PATH.
1517
1517
1518 This version explicitly checks that every entry in $PATH is a file
1518 This version explicitly checks that every entry in $PATH is a file
1519 with execute access (os.X_OK), so it is much slower than %rehash.
1519 with execute access (os.X_OK), so it is much slower than %rehash.
1520
1520
1521 Under Windows, it checks executability as a match agains a
1521 Under Windows, it checks executability as a match agains a
1522 '|'-separated string of extensions, stored in the IPython config
1522 '|'-separated string of extensions, stored in the IPython config
1523 variable win_exec_ext. This defaults to 'exe|com|bat'.
1523 variable win_exec_ext. This defaults to 'exe|com|bat'.
1524
1524
1525 This function also resets the root module cache of module completer,
1525 This function also resets the root module cache of module completer,
1526 used on slow filesystems.
1526 used on slow filesystems.
1527
1527
1528 **%rep**::
1528 **%rep**::
1529
1529
1530 Repeat a command, or get command to input line for editing
1530 Repeat a command, or get command to input line for editing
1531
1531
1532 - %rep (no arguments):
1532 - %rep (no arguments):
1533
1533
1534 Place a string version of last computation result (stored in the special '_'
1534 Place a string version of last computation result (stored in the special '_'
1535 variable) to the next input prompt. Allows you to create elaborate command
1535 variable) to the next input prompt. Allows you to create elaborate command
1536 lines without using copy-paste::
1536 lines without using copy-paste::
1537
1537
1538 $ l = ["hei", "vaan"]
1538 $ l = ["hei", "vaan"]
1539 $ "".join(l)
1539 $ "".join(l)
1540 ==> heivaan
1540 ==> heivaan
1541 $ %rep
1541 $ %rep
1542 $ heivaan_ <== cursor blinking
1542 $ heivaan_ <== cursor blinking
1543
1543
1544 %rep 45
1544 %rep 45
1545
1545
1546 Place history line 45 to next input prompt. Use %hist to find out the
1546 Place history line 45 to next input prompt. Use %hist to find out the
1547 number.
1547 number.
1548
1548
1549 %rep 1-4 6-7 3
1549 %rep 1-4 6-7 3
1550
1550
1551 Repeat the specified lines immediately. Input slice syntax is the same as
1551 Repeat the specified lines immediately. Input slice syntax is the same as
1552 in %macro and %save.
1552 in %macro and %save.
1553
1553
1554 %rep foo
1554 %rep foo
1555
1555
1556 Place the most recent line that has the substring "foo" to next input.
1556 Place the most recent line that has the substring "foo" to next input.
1557 (e.g. 'svn ci -m foobar').
1557 (e.g. 'svn ci -m foobar').
1558
1558
1559 **%reset**::
1559 **%reset**::
1560
1560
1561 Resets the namespace by removing all names defined by the user.
1561 Resets the namespace by removing all names defined by the user.
1562
1562
1563 Input/Output history are left around in case you need them.
1563 Input/Output history are left around in case you need them.
1564
1564
1565 **%run**::
1565 **%run**::
1566
1566
1567 Run the named file inside IPython as a program.
1567 Run the named file inside IPython as a program.
1568
1568
1569 Usage:\
1569 Usage:\
1570 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1570 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1571
1571
1572 Parameters after the filename are passed as command-line arguments to
1572 Parameters after the filename are passed as command-line arguments to
1573 the program (put in sys.argv). Then, control returns to IPython's
1573 the program (put in sys.argv). Then, control returns to IPython's
1574 prompt.
1574 prompt.
1575
1575
1576 This is similar to running at a system prompt:\
1576 This is similar to running at a system prompt:\
1577 $ python file args\
1577 $ python file args\
1578 but with the advantage of giving you IPython's tracebacks, and of
1578 but with the advantage of giving you IPython's tracebacks, and of
1579 loading all variables into your interactive namespace for further use
1579 loading all variables into your interactive namespace for further use
1580 (unless -p is used, see below).
1580 (unless -p is used, see below).
1581
1581
1582 The file is executed in a namespace initially consisting only of
1582 The file is executed in a namespace initially consisting only of
1583 __name__=='__main__' and sys.argv constructed as indicated. It thus
1583 __name__=='__main__' and sys.argv constructed as indicated. It thus
1584 sees its environment as if it were being run as a stand-alone program
1584 sees its environment as if it were being run as a stand-alone program
1585 (except for sharing global objects such as previously imported
1585 (except for sharing global objects such as previously imported
1586 modules). But after execution, the IPython interactive namespace gets
1586 modules). But after execution, the IPython interactive namespace gets
1587 updated with all variables defined in the program (except for __name__
1587 updated with all variables defined in the program (except for __name__
1588 and sys.argv). This allows for very convenient loading of code for
1588 and sys.argv). This allows for very convenient loading of code for
1589 interactive work, while giving each program a 'clean sheet' to run in.
1589 interactive work, while giving each program a 'clean sheet' to run in.
1590
1590
1591 Options:
1591 Options:
1592
1592
1593 -n: __name__ is NOT set to '__main__', but to the running file's name
1593 -n: __name__ is NOT set to '__main__', but to the running file's name
1594 without extension (as python does under import). This allows running
1594 without extension (as python does under import). This allows running
1595 scripts and reloading the definitions in them without calling code
1595 scripts and reloading the definitions in them without calling code
1596 protected by an ' if __name__ == "__main__" ' clause.
1596 protected by an ' if __name__ == "__main__" ' clause.
1597
1597
1598 -i: run the file in IPython's namespace instead of an empty one. This
1598 -i: run the file in IPython's namespace instead of an empty one. This
1599 is useful if you are experimenting with code written in a text editor
1599 is useful if you are experimenting with code written in a text editor
1600 which depends on variables defined interactively.
1600 which depends on variables defined interactively.
1601
1601
1602 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1602 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1603 being run. This is particularly useful if IPython is being used to
1603 being run. This is particularly useful if IPython is being used to
1604 run unittests, which always exit with a sys.exit() call. In such
1604 run unittests, which always exit with a sys.exit() call. In such
1605 cases you are interested in the output of the test results, not in
1605 cases you are interested in the output of the test results, not in
1606 seeing a traceback of the unittest module.
1606 seeing a traceback of the unittest module.
1607
1607
1608 -t: print timing information at the end of the run. IPython will give
1608 -t: print timing information at the end of the run. IPython will give
1609 you an estimated CPU time consumption for your script, which under
1609 you an estimated CPU time consumption for your script, which under
1610 Unix uses the resource module to avoid the wraparound problems of
1610 Unix uses the resource module to avoid the wraparound problems of
1611 time.clock(). Under Unix, an estimate of time spent on system tasks
1611 time.clock(). Under Unix, an estimate of time spent on system tasks
1612 is also given (for Windows platforms this is reported as 0.0).
1612 is also given (for Windows platforms this is reported as 0.0).
1613
1613
1614 If -t is given, an additional -N<N> option can be given, where <N>
1614 If -t is given, an additional -N<N> option can be given, where <N>
1615 must be an integer indicating how many times you want the script to
1615 must be an integer indicating how many times you want the script to
1616 run. The final timing report will include total and per run results.
1616 run. The final timing report will include total and per run results.
1617
1617
1618 For example (testing the script uniq_stable.py):
1618 For example (testing the script uniq_stable.py):
1619
1619
1620 In [1]: run -t uniq_stable
1620 In [1]: run -t uniq_stable
1621
1621
1622 IPython CPU timings (estimated):\
1622 IPython CPU timings (estimated):\
1623 User : 0.19597 s.\
1623 User : 0.19597 s.\
1624 System: 0.0 s.\
1624 System: 0.0 s.\
1625
1625
1626 In [2]: run -t -N5 uniq_stable
1626 In [2]: run -t -N5 uniq_stable
1627
1627
1628 IPython CPU timings (estimated):\
1628 IPython CPU timings (estimated):\
1629 Total runs performed: 5\
1629 Total runs performed: 5\
1630 Times : Total Per run\
1630 Times : Total Per run\
1631 User : 0.910862 s, 0.1821724 s.\
1631 User : 0.910862 s, 0.1821724 s.\
1632 System: 0.0 s, 0.0 s.
1632 System: 0.0 s, 0.0 s.
1633
1633
1634 -d: run your program under the control of pdb, the Python debugger.
1634 -d: run your program under the control of pdb, the Python debugger.
1635 This allows you to execute your program step by step, watch variables,
1635 This allows you to execute your program step by step, watch variables,
1636 etc. Internally, what IPython does is similar to calling:
1636 etc. Internally, what IPython does is similar to calling:
1637
1637
1638 pdb.run('execfile("YOURFILENAME")')
1638 pdb.run('execfile("YOURFILENAME")')
1639
1639
1640 with a breakpoint set on line 1 of your file. You can change the line
1640 with a breakpoint set on line 1 of your file. You can change the line
1641 number for this automatic breakpoint to be <N> by using the -bN option
1641 number for this automatic breakpoint to be <N> by using the -bN option
1642 (where N must be an integer). For example:
1642 (where N must be an integer). For example:
1643
1643
1644 %run -d -b40 myscript
1644 %run -d -b40 myscript
1645
1645
1646 will set the first breakpoint at line 40 in myscript.py. Note that
1646 will set the first breakpoint at line 40 in myscript.py. Note that
1647 the first breakpoint must be set on a line which actually does
1647 the first breakpoint must be set on a line which actually does
1648 something (not a comment or docstring) for it to stop execution.
1648 something (not a comment or docstring) for it to stop execution.
1649
1649
1650 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1650 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1651 first enter 'c' (without qoutes) to start execution up to the first
1651 first enter 'c' (without qoutes) to start execution up to the first
1652 breakpoint.
1652 breakpoint.
1653
1653
1654 Entering 'help' gives information about the use of the debugger. You
1654 Entering 'help' gives information about the use of the debugger. You
1655 can easily see pdb's full documentation with "import pdb;pdb.help()"
1655 can easily see pdb's full documentation with "import pdb;pdb.help()"
1656 at a prompt.
1656 at a prompt.
1657
1657
1658 -p: run program under the control of the Python profiler module (which
1658 -p: run program under the control of the Python profiler module (which
1659 prints a detailed report of execution times, function calls, etc).
1659 prints a detailed report of execution times, function calls, etc).
1660
1660
1661 You can pass other options after -p which affect the behavior of the
1661 You can pass other options after -p which affect the behavior of the
1662 profiler itself. See the docs for %prun for details.
1662 profiler itself. See the docs for %prun for details.
1663
1663
1664 In this mode, the program's variables do NOT propagate back to the
1664 In this mode, the program's variables do NOT propagate back to the
1665 IPython interactive namespace (because they remain in the namespace
1665 IPython interactive namespace (because they remain in the namespace
1666 where the profiler executes them).
1666 where the profiler executes them).
1667
1667
1668 Internally this triggers a call to %prun, see its documentation for
1668 Internally this triggers a call to %prun, see its documentation for
1669 details on the options available specifically for profiling.
1669 details on the options available specifically for profiling.
1670
1670
1671 There is one special usage for which the text above doesn't apply:
1671 There is one special usage for which the text above doesn't apply:
1672 if the filename ends with .ipy, the file is run as ipython script,
1672 if the filename ends with .ipy, the file is run as ipython script,
1673 just as if the commands were written on IPython prompt.
1673 just as if the commands were written on IPython prompt.
1674
1674
1675 **%runlog**::
1675 **%runlog**::
1676
1676
1677 Run files as logs.
1677 Run files as logs.
1678
1678
1679 Usage:\
1679 Usage:\
1680 %runlog file1 file2 ...
1680 %runlog file1 file2 ...
1681
1681
1682 Run the named files (treating them as log files) in sequence inside
1682 Run the named files (treating them as log files) in sequence inside
1683 the interpreter, and return to the prompt. This is much slower than
1683 the interpreter, and return to the prompt. This is much slower than
1684 %run because each line is executed in a try/except block, but it
1684 %run because each line is executed in a try/except block, but it
1685 allows running files with syntax errors in them.
1685 allows running files with syntax errors in them.
1686
1686
1687 Normally IPython will guess when a file is one of its own logfiles, so
1687 Normally IPython will guess when a file is one of its own logfiles, so
1688 you can typically use %run even for logs. This shorthand allows you to
1688 you can typically use %run even for logs. This shorthand allows you to
1689 force any file to be treated as a log file.
1689 force any file to be treated as a log file.
1690
1690
1691 **%save**::
1691 **%save**::
1692
1692
1693 Save a set of lines to a given filename.
1693 Save a set of lines to a given filename.
1694
1694
1695 Usage:\
1695 Usage:\
1696 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1696 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1697
1697
1698 Options:
1698 Options:
1699
1699
1700 -r: use 'raw' input. By default, the 'processed' history is used,
1700 -r: use 'raw' input. By default, the 'processed' history is used,
1701 so that magics are loaded in their transformed version to valid
1701 so that magics are loaded in their transformed version to valid
1702 Python. If this option is given, the raw input as typed as the
1702 Python. If this option is given, the raw input as typed as the
1703 command line is used instead.
1703 command line is used instead.
1704
1704
1705 This function uses the same syntax as %macro for line extraction, but
1705 This function uses the same syntax as %macro for line extraction, but
1706 instead of creating a macro it saves the resulting string to the
1706 instead of creating a macro it saves the resulting string to the
1707 filename you specify.
1707 filename you specify.
1708
1708
1709 It adds a '.py' extension to the file if you don't do so yourself, and
1709 It adds a '.py' extension to the file if you don't do so yourself, and
1710 it asks for confirmation before overwriting existing files.
1710 it asks for confirmation before overwriting existing files.
1711
1711
1712 **%sc**::
1712 **%sc**::
1713
1713
1714 Shell capture - execute a shell command and capture its output.
1714 Shell capture - execute a shell command and capture its output.
1715
1715
1716 DEPRECATED. Suboptimal, retained for backwards compatibility.
1716 DEPRECATED. Suboptimal, retained for backwards compatibility.
1717
1717
1718 You should use the form 'var = !command' instead. Example:
1718 You should use the form 'var = !command' instead. Example:
1719
1719
1720 "%sc -l myfiles = ls ~" should now be written as
1720 "%sc -l myfiles = ls ~" should now be written as
1721
1721
1722 "myfiles = !ls ~"
1722 "myfiles = !ls ~"
1723
1723
1724 myfiles.s, myfiles.l and myfiles.n still apply as documented
1724 myfiles.s, myfiles.l and myfiles.n still apply as documented
1725 below.
1725 below.
1726
1726
1727 --
1727 --
1728 %sc [options] varname=command
1728 %sc [options] varname=command
1729
1729
1730 IPython will run the given command using commands.getoutput(), and
1730 IPython will run the given command using commands.getoutput(), and
1731 will then update the user's interactive namespace with a variable
1731 will then update the user's interactive namespace with a variable
1732 called varname, containing the value of the call. Your command can
1732 called varname, containing the value of the call. Your command can
1733 contain shell wildcards, pipes, etc.
1733 contain shell wildcards, pipes, etc.
1734
1734
1735 The '=' sign in the syntax is mandatory, and the variable name you
1735 The '=' sign in the syntax is mandatory, and the variable name you
1736 supply must follow Python's standard conventions for valid names.
1736 supply must follow Python's standard conventions for valid names.
1737
1737
1738 (A special format without variable name exists for internal use)
1738 (A special format without variable name exists for internal use)
1739
1739
1740 Options:
1740 Options:
1741
1741
1742 -l: list output. Split the output on newlines into a list before
1742 -l: list output. Split the output on newlines into a list before
1743 assigning it to the given variable. By default the output is stored
1743 assigning it to the given variable. By default the output is stored
1744 as a single string.
1744 as a single string.
1745
1745
1746 -v: verbose. Print the contents of the variable.
1746 -v: verbose. Print the contents of the variable.
1747
1747
1748 In most cases you should not need to split as a list, because the
1748 In most cases you should not need to split as a list, because the
1749 returned value is a special type of string which can automatically
1749 returned value is a special type of string which can automatically
1750 provide its contents either as a list (split on newlines) or as a
1750 provide its contents either as a list (split on newlines) or as a
1751 space-separated string. These are convenient, respectively, either
1751 space-separated string. These are convenient, respectively, either
1752 for sequential processing or to be passed to a shell command.
1752 for sequential processing or to be passed to a shell command.
1753
1753
1754 For example:
1754 For example:
1755
1755
1756 # Capture into variable a
1756 # Capture into variable a
1757 In [9]: sc a=ls *py
1757 In [9]: sc a=ls *py
1758
1758
1759 # a is a string with embedded newlines
1759 # a is a string with embedded newlines
1760 In [10]: a
1760 In [10]: a
1761 Out[10]: 'setup.py win32_manual_post_install.py'
1761 Out[10]: 'setup.py win32_manual_post_install.py'
1762
1762
1763 # which can be seen as a list:
1763 # which can be seen as a list:
1764 In [11]: a.l
1764 In [11]: a.l
1765 Out[11]: ['setup.py', 'win32_manual_post_install.py']
1765 Out[11]: ['setup.py', 'win32_manual_post_install.py']
1766
1766
1767 # or as a whitespace-separated string:
1767 # or as a whitespace-separated string:
1768 In [12]: a.s
1768 In [12]: a.s
1769 Out[12]: 'setup.py win32_manual_post_install.py'
1769 Out[12]: 'setup.py win32_manual_post_install.py'
1770
1770
1771 # a.s is useful to pass as a single command line:
1771 # a.s is useful to pass as a single command line:
1772 In [13]: !wc -l $a.s
1772 In [13]: !wc -l $a.s
1773 146 setup.py
1773 146 setup.py
1774 130 win32_manual_post_install.py
1774 130 win32_manual_post_install.py
1775 276 total
1775 276 total
1776
1776
1777 # while the list form is useful to loop over:
1777 # while the list form is useful to loop over:
1778 In [14]: for f in a.l:
1778 In [14]: for f in a.l:
1779 ....: !wc -l $f
1779 ....: !wc -l $f
1780 ....:
1780 ....:
1781 146 setup.py
1781 146 setup.py
1782 130 win32_manual_post_install.py
1782 130 win32_manual_post_install.py
1783
1783
1784 Similiarly, the lists returned by the -l option are also special, in
1784 Similiarly, the lists returned by the -l option are also special, in
1785 the sense that you can equally invoke the .s attribute on them to
1785 the sense that you can equally invoke the .s attribute on them to
1786 automatically get a whitespace-separated string from their contents:
1786 automatically get a whitespace-separated string from their contents:
1787
1787
1788 In [1]: sc -l b=ls *py
1788 In [1]: sc -l b=ls *py
1789
1789
1790 In [2]: b
1790 In [2]: b
1791 Out[2]: ['setup.py', 'win32_manual_post_install.py']
1791 Out[2]: ['setup.py', 'win32_manual_post_install.py']
1792
1792
1793 In [3]: b.s
1793 In [3]: b.s
1794 Out[3]: 'setup.py win32_manual_post_install.py'
1794 Out[3]: 'setup.py win32_manual_post_install.py'
1795
1795
1796 In summary, both the lists and strings used for ouptut capture have
1796 In summary, both the lists and strings used for ouptut capture have
1797 the following special attributes:
1797 the following special attributes:
1798
1798
1799 .l (or .list) : value as list.
1799 .l (or .list) : value as list.
1800 .n (or .nlstr): value as newline-separated string.
1800 .n (or .nlstr): value as newline-separated string.
1801 .s (or .spstr): value as space-separated string.
1801 .s (or .spstr): value as space-separated string.
1802
1802
1803 **%store**::
1803 **%store**::
1804
1804
1805 Lightweight persistence for python variables.
1805 Lightweight persistence for python variables.
1806
1806
1807 Example:
1807 Example:
1808
1808
1809 ville@badger[~]|1> A = ['hello',10,'world']\
1809 ville@badger[~]|1> A = ['hello',10,'world']\
1810 ville@badger[~]|2> %store A\
1810 ville@badger[~]|2> %store A\
1811 ville@badger[~]|3> Exit
1811 ville@badger[~]|3> Exit
1812
1812
1813 (IPython session is closed and started again...)
1813 (IPython session is closed and started again...)
1814
1814
1815 ville@badger:~$ ipython -p pysh\
1815 ville@badger:~$ ipython -p pysh\
1816 ville@badger[~]|1> print A
1816 ville@badger[~]|1> print A
1817
1817
1818 ['hello', 10, 'world']
1818 ['hello', 10, 'world']
1819
1819
1820 Usage:
1820 Usage:
1821
1821
1822 %store - Show list of all variables and their current values\
1822 %store - Show list of all variables and their current values\
1823 %store <var> - Store the *current* value of the variable to disk\
1823 %store <var> - Store the *current* value of the variable to disk\
1824 %store -d <var> - Remove the variable and its value from storage\
1824 %store -d <var> - Remove the variable and its value from storage\
1825 %store -z - Remove all variables from storage\
1825 %store -z - Remove all variables from storage\
1826 %store -r - Refresh all variables from store (delete current vals)\
1826 %store -r - Refresh all variables from store (delete current vals)\
1827 %store foo >a.txt - Store value of foo to new file a.txt\
1827 %store foo >a.txt - Store value of foo to new file a.txt\
1828 %store foo >>a.txt - Append value of foo to file a.txt\
1828 %store foo >>a.txt - Append value of foo to file a.txt\
1829
1829
1830 It should be noted that if you change the value of a variable, you
1830 It should be noted that if you change the value of a variable, you
1831 need to %store it again if you want to persist the new value.
1831 need to %store it again if you want to persist the new value.
1832
1832
1833 Note also that the variables will need to be pickleable; most basic
1833 Note also that the variables will need to be pickleable; most basic
1834 python types can be safely %stored.
1834 python types can be safely %stored.
1835
1835
1836 Also aliases can be %store'd across sessions.
1836 Also aliases can be %store'd across sessions.
1837
1837
1838 **%sx**::
1838 **%sx**::
1839
1839
1840 Shell execute - run a shell command and capture its output.
1840 Shell execute - run a shell command and capture its output.
1841
1841
1842 %sx command
1842 %sx command
1843
1843
1844 IPython will run the given command using commands.getoutput(), and
1844 IPython will run the given command using commands.getoutput(), and
1845 return the result formatted as a list (split on '\n'). Since the
1845 return the result formatted as a list (split on '\n'). Since the
1846 output is _returned_, it will be stored in ipython's regular output
1846 output is _returned_, it will be stored in ipython's regular output
1847 cache Out[N] and in the '_N' automatic variables.
1847 cache Out[N] and in the '_N' automatic variables.
1848
1848
1849 Notes:
1849 Notes:
1850
1850
1851 1) If an input line begins with '!!', then %sx is automatically
1851 1) If an input line begins with '!!', then %sx is automatically
1852 invoked. That is, while:
1852 invoked. That is, while:
1853 !ls
1853 !ls
1854 causes ipython to simply issue system('ls'), typing
1854 causes ipython to simply issue system('ls'), typing
1855 !!ls
1855 !!ls
1856 is a shorthand equivalent to:
1856 is a shorthand equivalent to:
1857 %sx ls
1857 %sx ls
1858
1858
1859 2) %sx differs from %sc in that %sx automatically splits into a list,
1859 2) %sx differs from %sc in that %sx automatically splits into a list,
1860 like '%sc -l'. The reason for this is to make it as easy as possible
1860 like '%sc -l'. The reason for this is to make it as easy as possible
1861 to process line-oriented shell output via further python commands.
1861 to process line-oriented shell output via further python commands.
1862 %sc is meant to provide much finer control, but requires more
1862 %sc is meant to provide much finer control, but requires more
1863 typing.
1863 typing.
1864
1864
1865 3) Just like %sc -l, this is a list with special attributes:
1865 3) Just like %sc -l, this is a list with special attributes:
1866
1866
1867 .l (or .list) : value as list.
1867 .l (or .list) : value as list.
1868 .n (or .nlstr): value as newline-separated string.
1868 .n (or .nlstr): value as newline-separated string.
1869 .s (or .spstr): value as whitespace-separated string.
1869 .s (or .spstr): value as whitespace-separated string.
1870
1870
1871 This is very useful when trying to use such lists as arguments to
1871 This is very useful when trying to use such lists as arguments to
1872 system commands.
1872 system commands.
1873
1873
1874 **%system_verbose**::
1874 **%system_verbose**::
1875
1875
1876 Set verbose printing of system calls.
1876 Set verbose printing of system calls.
1877
1877
1878 If called without an argument, act as a toggle
1878 If called without an argument, act as a toggle
1879
1879
1880 **%time**::
1880 **%time**::
1881
1881
1882 Time execution of a Python statement or expression.
1882 Time execution of a Python statement or expression.
1883
1883
1884 The CPU and wall clock times are printed, and the value of the
1884 The CPU and wall clock times are printed, and the value of the
1885 expression (if any) is returned. Note that under Win32, system time
1885 expression (if any) is returned. Note that under Win32, system time
1886 is always reported as 0, since it can not be measured.
1886 is always reported as 0, since it can not be measured.
1887
1887
1888 This function provides very basic timing functionality. In Python
1888 This function provides very basic timing functionality. In Python
1889 2.3, the timeit module offers more control and sophistication, so this
1889 2.3, the timeit module offers more control and sophistication, so this
1890 could be rewritten to use it (patches welcome).
1890 could be rewritten to use it (patches welcome).
1891
1891
1892 Some examples:
1892 Some examples:
1893
1893
1894 In [1]: time 2**128
1894 In [1]: time 2**128
1895 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1895 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1896 Wall time: 0.00
1896 Wall time: 0.00
1897 Out[1]: 340282366920938463463374607431768211456L
1897 Out[1]: 340282366920938463463374607431768211456L
1898
1898
1899 In [2]: n = 1000000
1899 In [2]: n = 1000000
1900
1900
1901 In [3]: time sum(range(n))
1901 In [3]: time sum(range(n))
1902 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1902 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1903 Wall time: 1.37
1903 Wall time: 1.37
1904 Out[3]: 499999500000L
1904 Out[3]: 499999500000L
1905
1905
1906 In [4]: time print 'hello world'
1906 In [4]: time print 'hello world'
1907 hello world
1907 hello world
1908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1908 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1909 Wall time: 0.00
1909 Wall time: 0.00
1910
1910
1911 Note that the time needed by Python to compile the given expression
1911 Note that the time needed by Python to compile the given expression
1912 will be reported if it is more than 0.1s. In this example, the
1912 will be reported if it is more than 0.1s. In this example, the
1913 actual exponentiation is done by Python at compilation time, so while
1913 actual exponentiation is done by Python at compilation time, so while
1914 the expression can take a noticeable amount of time to compute, that
1914 the expression can take a noticeable amount of time to compute, that
1915 time is purely due to the compilation:
1915 time is purely due to the compilation:
1916
1916
1917 In [5]: time 3**9999;
1917 In [5]: time 3**9999;
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1919 Wall time: 0.00 s
1919 Wall time: 0.00 s
1920
1920
1921 In [6]: time 3**999999;
1921 In [6]: time 3**999999;
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 Wall time: 0.00 s
1923 Wall time: 0.00 s
1924 Compiler : 0.78 s
1924 Compiler : 0.78 s
1925
1925
1926 **%timeit**::
1926 **%timeit**::
1927
1927
1928 Time execution of a Python statement or expression
1928 Time execution of a Python statement or expression
1929
1929
1930 Usage:\
1930 Usage:\
1931 %timeit [-n<N> -r<R> [-t|-c]] statement
1931 %timeit [-n<N> -r<R> [-t|-c]] statement
1932
1932
1933 Time execution of a Python statement or expression using the timeit
1933 Time execution of a Python statement or expression using the timeit
1934 module.
1934 module.
1935
1935
1936 Options:
1936 Options:
1937 -n<N>: execute the given statement <N> times in a loop. If this value
1937 -n<N>: execute the given statement <N> times in a loop. If this value
1938 is not given, a fitting value is chosen.
1938 is not given, a fitting value is chosen.
1939
1939
1940 -r<R>: repeat the loop iteration <R> times and take the best result.
1940 -r<R>: repeat the loop iteration <R> times and take the best result.
1941 Default: 3
1941 Default: 3
1942
1942
1943 -t: use time.time to measure the time, which is the default on Unix.
1943 -t: use time.time to measure the time, which is the default on Unix.
1944 This function measures wall time.
1944 This function measures wall time.
1945
1945
1946 -c: use time.clock to measure the time, which is the default on
1946 -c: use time.clock to measure the time, which is the default on
1947 Windows and measures wall time. On Unix, resource.getrusage is used
1947 Windows and measures wall time. On Unix, resource.getrusage is used
1948 instead and returns the CPU user time.
1948 instead and returns the CPU user time.
1949
1949
1950 -p<P>: use a precision of <P> digits to display the timing result.
1950 -p<P>: use a precision of <P> digits to display the timing result.
1951 Default: 3
1951 Default: 3
1952
1952
1953
1953
1954 Examples:\
1954 Examples:\
1955 In [1]: %timeit pass
1955 In [1]: %timeit pass
1956 10000000 loops, best of 3: 53.3 ns per loop
1956 10000000 loops, best of 3: 53.3 ns per loop
1957
1957
1958 In [2]: u = None
1958 In [2]: u = None
1959
1959
1960 In [3]: %timeit u is None
1960 In [3]: %timeit u is None
1961 10000000 loops, best of 3: 184 ns per loop
1961 10000000 loops, best of 3: 184 ns per loop
1962
1962
1963 In [4]: %timeit -r 4 u == None
1963 In [4]: %timeit -r 4 u == None
1964 1000000 loops, best of 4: 242 ns per loop
1964 1000000 loops, best of 4: 242 ns per loop
1965
1965
1966 In [5]: import time
1966 In [5]: import time
1967
1967
1968 In [6]: %timeit -n1 time.sleep(2)
1968 In [6]: %timeit -n1 time.sleep(2)
1969 1 loops, best of 3: 2 s per loop
1969 1 loops, best of 3: 2 s per loop
1970
1970
1971
1971
1972 The times reported by %timeit will be slightly higher than those
1972 The times reported by %timeit will be slightly higher than those
1973 reported by the timeit.py script when variables are accessed. This is
1973 reported by the timeit.py script when variables are accessed. This is
1974 due to the fact that %timeit executes the statement in the namespace
1974 due to the fact that %timeit executes the statement in the namespace
1975 of the shell, compared with timeit.py, which uses a single setup
1975 of the shell, compared with timeit.py, which uses a single setup
1976 statement to import function or create variables. Generally, the bias
1976 statement to import function or create variables. Generally, the bias
1977 does not matter as long as results from timeit.py are not mixed with
1977 does not matter as long as results from timeit.py are not mixed with
1978 those from %timeit.
1978 those from %timeit.
1979
1979
1980 **%unalias**::
1980 **%unalias**::
1981
1981
1982 Remove an alias
1982 Remove an alias
1983
1983
1984 **%upgrade**::
1984 **%upgrade**::
1985
1985
1986 Upgrade your IPython installation
1986 Upgrade your IPython installation
1987
1987
1988 This will copy the config files that don't yet exist in your
1988 This will copy the config files that don't yet exist in your
1989 ipython dir from the system config dir. Use this after upgrading
1989 ipython dir from the system config dir. Use this after upgrading
1990 IPython if you don't wish to delete your .ipython dir.
1990 IPython if you don't wish to delete your .ipython dir.
1991
1991
1992 Call with -nolegacy to get rid of ipythonrc* files (recommended for
1992 Call with -nolegacy to get rid of ipythonrc* files (recommended for
1993 new users)
1993 new users)
1994
1994
1995 **%which**::
1995 **%which**::
1996
1996
1997 %which <cmd> => search PATH for files matching cmd. Also scans aliases.
1997 %which <cmd> => search PATH for files matching cmd. Also scans aliases.
1998
1998
1999 Traverses PATH and prints all files (not just executables!) that match the
1999 Traverses PATH and prints all files (not just executables!) that match the
2000 pattern on command line. Probably more useful in finding stuff
2000 pattern on command line. Probably more useful in finding stuff
2001 interactively than 'which', which only prints the first matching item.
2001 interactively than 'which', which only prints the first matching item.
2002
2002
2003 Also discovers and expands aliases, so you'll see what will be executed
2003 Also discovers and expands aliases, so you'll see what will be executed
2004 when you call an alias.
2004 when you call an alias.
2005
2005
2006 Example:
2006 Example:
2007
2007
2008 [~]|62> %which d
2008 [~]|62> %which d
2009 d -> ls -F --color=auto
2009 d -> ls -F --color=auto
2010 == c:\cygwin\bin\ls.exe
2010 == c:\cygwin\bin\ls.exe
2011 c:\cygwin\bin\d.exe
2011 c:\cygwin\bin\d.exe
2012
2012
2013 [~]|64> %which diff*
2013 [~]|64> %which diff*
2014 diff3 -> diff3
2014 diff3 -> diff3
2015 == c:\cygwin\bin\diff3.exe
2015 == c:\cygwin\bin\diff3.exe
2016 diff -> diff
2016 diff -> diff
2017 == c:\cygwin\bin\diff.exe
2017 == c:\cygwin\bin\diff.exe
2018 c:\cygwin\bin\diff.exe
2018 c:\cygwin\bin\diff.exe
2019 c:\cygwin\bin\diff3.exe
2019 c:\cygwin\bin\diff3.exe
2020
2020
2021 **%who**::
2021 **%who**::
2022
2022
2023 Print all interactive variables, with some minimal formatting.
2023 Print all interactive variables, with some minimal formatting.
2024
2024
2025 If any arguments are given, only variables whose type matches one of
2025 If any arguments are given, only variables whose type matches one of
2026 these are printed. For example:
2026 these are printed. For example:
2027
2027
2028 %who function str
2028 %who function str
2029
2029
2030 will only list functions and strings, excluding all other types of
2030 will only list functions and strings, excluding all other types of
2031 variables. To find the proper type names, simply use type(var) at a
2031 variables. To find the proper type names, simply use type(var) at a
2032 command line to see how python prints type names. For example:
2032 command line to see how python prints type names. For example:
2033
2033
2034 In [1]: type('hello')\
2034 In [1]: type('hello')\
2035 Out[1]: <type 'str'>
2035 Out[1]: <type 'str'>
2036
2036
2037 indicates that the type name for strings is 'str'.
2037 indicates that the type name for strings is 'str'.
2038
2038
2039 %who always excludes executed names loaded through your configuration
2039 %who always excludes executed names loaded through your configuration
2040 file and things which are internal to IPython.
2040 file and things which are internal to IPython.
2041
2041
2042 This is deliberate, as typically you may load many modules and the
2042 This is deliberate, as typically you may load many modules and the
2043 purpose of %who is to show you only what you've manually defined.
2043 purpose of %who is to show you only what you've manually defined.
2044
2044
2045 **%who_ls**::
2045 **%who_ls**::
2046
2046
2047 Return a sorted list of all interactive variables.
2047 Return a sorted list of all interactive variables.
2048
2048
2049 If arguments are given, only variables of types matching these
2049 If arguments are given, only variables of types matching these
2050 arguments are returned.
2050 arguments are returned.
2051
2051
2052 **%whos**::
2052 **%whos**::
2053
2053
2054 Like %who, but gives some extra information about each variable.
2054 Like %who, but gives some extra information about each variable.
2055
2055
2056 The same type filtering of %who can be applied here.
2056 The same type filtering of %who can be applied here.
2057
2057
2058 For all variables, the type is printed. Additionally it prints:
2058 For all variables, the type is printed. Additionally it prints:
2059
2059
2060 - For {},[],(): their length.
2060 - For {},[],(): their length.
2061
2061
2062 - For numpy and Numeric arrays, a summary with shape, number of
2062 - For numpy and Numeric arrays, a summary with shape, number of
2063 elements, typecode and size in memory.
2063 elements, typecode and size in memory.
2064
2064
2065 - Everything else: a string representation, snipping their middle if
2065 - Everything else: a string representation, snipping their middle if
2066 too long.
2066 too long.
2067
2067
2068 **%xmode**::
2068 **%xmode**::
2069
2069
2070 Switch modes for the exception handlers.
2070 Switch modes for the exception handlers.
2071
2071
2072 Valid modes: Plain, Context and Verbose.
2072 Valid modes: Plain, Context and Verbose.
2073
2073
2074 If called without arguments, acts as a toggle.
2074 If called without arguments, acts as a toggle.
2075
2075
2076 .. magic_end
2076 .. magic_end
2077
2077
2078 Access to the standard Python help
2078 Access to the standard Python help
2079 ----------------------------------
2079 ----------------------------------
2080
2080
2081 As of Python 2.1, a help system is available with access to object docstrings
2081 As of Python 2.1, a help system is available with access to object docstrings
2082 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
2082 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
2083 also type help(object) to obtain information about a given object, and
2083 also type help(object) to obtain information about a given object, and
2084 help('keyword') for information on a keyword. As noted :ref:`here
2084 help('keyword') for information on a keyword. As noted :ref:`here
2085 <accessing_help>`, you need to properly configure your environment variable
2085 <accessing_help>`, you need to properly configure your environment variable
2086 PYTHONDOCS for this feature to work correctly.
2086 PYTHONDOCS for this feature to work correctly.
2087
2087
2088 .. _dynamic_object_info:
2088 .. _dynamic_object_info:
2089
2089
2090 Dynamic object information
2090 Dynamic object information
2091 --------------------------
2091 --------------------------
2092
2092
2093 Typing ?word or word? prints detailed information about an object. If
2093 Typing ?word or word? prints detailed information about an object. If
2094 certain strings in the object are too long (docstrings, code, etc.) they
2094 certain strings in the object are too long (docstrings, code, etc.) they
2095 get snipped in the center for brevity. This system gives access variable
2095 get snipped in the center for brevity. This system gives access variable
2096 types and values, full source code for any object (if available),
2096 types and values, full source code for any object (if available),
2097 function prototypes and other useful information.
2097 function prototypes and other useful information.
2098
2098
2099 Typing ??word or word?? gives access to the full information without
2099 Typing ??word or word?? gives access to the full information without
2100 snipping long strings. Long strings are sent to the screen through the
2100 snipping long strings. Long strings are sent to the screen through the
2101 less pager if longer than the screen and printed otherwise. On systems
2101 less pager if longer than the screen and printed otherwise. On systems
2102 lacking the less command, IPython uses a very basic internal pager.
2102 lacking the less command, IPython uses a very basic internal pager.
2103
2103
2104 The following magic functions are particularly useful for gathering
2104 The following magic functions are particularly useful for gathering
2105 information about your working environment. You can get more details by
2105 information about your working environment. You can get more details by
2106 typing %magic or querying them individually (use %function_name? with or
2106 typing %magic or querying them individually (use %function_name? with or
2107 without the %), this is just a summary:
2107 without the %), this is just a summary:
2108
2108
2109 * **%pdoc <object>**: Print (or run through a pager if too long) the
2109 * **%pdoc <object>**: Print (or run through a pager if too long) the
2110 docstring for an object. If the given object is a class, it will
2110 docstring for an object. If the given object is a class, it will
2111 print both the class and the constructor docstrings.
2111 print both the class and the constructor docstrings.
2112 * **%pdef <object>**: Print the definition header for any callable
2112 * **%pdef <object>**: Print the definition header for any callable
2113 object. If the object is a class, print the constructor information.
2113 object. If the object is a class, print the constructor information.
2114 * **%psource <object>**: Print (or run through a pager if too long)
2114 * **%psource <object>**: Print (or run through a pager if too long)
2115 the source code for an object.
2115 the source code for an object.
2116 * **%pfile <object>**: Show the entire source file where an object was
2116 * **%pfile <object>**: Show the entire source file where an object was
2117 defined via a pager, opening it at the line where the object
2117 defined via a pager, opening it at the line where the object
2118 definition begins.
2118 definition begins.
2119 * **%who/%whos**: These functions give information about identifiers
2119 * **%who/%whos**: These functions give information about identifiers
2120 you have defined interactively (not things you loaded or defined
2120 you have defined interactively (not things you loaded or defined
2121 in your configuration files). %who just prints a list of
2121 in your configuration files). %who just prints a list of
2122 identifiers and %whos prints a table with some basic details about
2122 identifiers and %whos prints a table with some basic details about
2123 each identifier.
2123 each identifier.
2124
2124
2125 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
2125 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
2126 %pdef, %psource) give you access to documentation even on things which
2126 %pdef, %psource) give you access to documentation even on things which
2127 are not really defined as separate identifiers. Try for example typing
2127 are not really defined as separate identifiers. Try for example typing
2128 {}.get? or after doing import os, type os.path.abspath??.
2128 {}.get? or after doing import os, type os.path.abspath??.
2129
2129
2130
2130
2131 .. _readline:
2131 .. _readline:
2132
2132
2133 Readline-based features
2133 Readline-based features
2134 -----------------------
2134 -----------------------
2135
2135
2136 These features require the GNU readline library, so they won't work if
2136 These features require the GNU readline library, so they won't work if
2137 your Python installation lacks readline support. We will first describe
2137 your Python installation lacks readline support. We will first describe
2138 the default behavior IPython uses, and then how to change it to suit
2138 the default behavior IPython uses, and then how to change it to suit
2139 your preferences.
2139 your preferences.
2140
2140
2141
2141
2142 Command line completion
2142 Command line completion
2143 +++++++++++++++++++++++
2143 +++++++++++++++++++++++
2144
2144
2145 At any time, hitting TAB will complete any available python commands or
2145 At any time, hitting TAB will complete any available python commands or
2146 variable names, and show you a list of the possible completions if
2146 variable names, and show you a list of the possible completions if
2147 there's no unambiguous one. It will also complete filenames in the
2147 there's no unambiguous one. It will also complete filenames in the
2148 current directory if no python names match what you've typed so far.
2148 current directory if no python names match what you've typed so far.
2149
2149
2150
2150
2151 Search command history
2151 Search command history
2152 ++++++++++++++++++++++
2152 ++++++++++++++++++++++
2153
2153
2154 IPython provides two ways for searching through previous input and thus
2154 IPython provides two ways for searching through previous input and thus
2155 reduce the need for repetitive typing:
2155 reduce the need for repetitive typing:
2156
2156
2157 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
2157 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
2158 (next,down) to search through only the history items that match
2158 (next,down) to search through only the history items that match
2159 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
2159 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
2160 prompt, they just behave like normal arrow keys.
2160 prompt, they just behave like normal arrow keys.
2161 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
2161 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
2162 searches your history for lines that contain what you've typed so
2162 searches your history for lines that contain what you've typed so
2163 far, completing as much as it can.
2163 far, completing as much as it can.
2164
2164
2165
2165
2166 Persistent command history across sessions
2166 Persistent command history across sessions
2167 ++++++++++++++++++++++++++++++++++++++++++
2167 ++++++++++++++++++++++++++++++++++++++++++
2168
2168
2169 IPython will save your input history when it leaves and reload it next
2169 IPython will save your input history when it leaves and reload it next
2170 time you restart it. By default, the history file is named
2170 time you restart it. By default, the history file is named
2171 $IPYTHONDIR/history, but if you've loaded a named profile,
2171 $IPYTHONDIR/history, but if you've loaded a named profile,
2172 '-PROFILE_NAME' is appended to the name. This allows you to keep
2172 '-PROFILE_NAME' is appended to the name. This allows you to keep
2173 separate histories related to various tasks: commands related to
2173 separate histories related to various tasks: commands related to
2174 numerical work will not be clobbered by a system shell history, for
2174 numerical work will not be clobbered by a system shell history, for
2175 example.
2175 example.
2176
2176
2177
2177
2178 Autoindent
2178 Autoindent
2179 ++++++++++
2179 ++++++++++
2180
2180
2181 IPython can recognize lines ending in ':' and indent the next line,
2181 IPython can recognize lines ending in ':' and indent the next line,
2182 while also un-indenting automatically after 'raise' or 'return'.
2182 while also un-indenting automatically after 'raise' or 'return'.
2183
2183
2184 This feature uses the readline library, so it will honor your ~/.inputrc
2184 This feature uses the readline library, so it will honor your ~/.inputrc
2185 configuration (or whatever file your INPUTRC variable points to). Adding
2185 configuration (or whatever file your INPUTRC variable points to). Adding
2186 the following lines to your .inputrc file can make indenting/unindenting
2186 the following lines to your .inputrc file can make indenting/unindenting
2187 more convenient (M-i indents, M-u unindents)::
2187 more convenient (M-i indents, M-u unindents)::
2188
2188
2189 $if Python
2189 $if Python
2190 "\M-i": " "
2190 "\M-i": " "
2191 "\M-u": "\d\d\d\d"
2191 "\M-u": "\d\d\d\d"
2192 $endif
2192 $endif
2193
2193
2194 Note that there are 4 spaces between the quote marks after "M-i" above.
2194 Note that there are 4 spaces between the quote marks after "M-i" above.
2195
2195
2196 Warning: this feature is ON by default, but it can cause problems with
2196 Warning: this feature is ON by default, but it can cause problems with
2197 the pasting of multi-line indented code (the pasted code gets
2197 the pasting of multi-line indented code (the pasted code gets
2198 re-indented on each line). A magic function %autoindent allows you to
2198 re-indented on each line). A magic function %autoindent allows you to
2199 toggle it on/off at runtime. You can also disable it permanently on in
2199 toggle it on/off at runtime. You can also disable it permanently on in
2200 your ipythonrc file (set autoindent 0).
2200 your ipythonrc file (set autoindent 0).
2201
2201
2202
2202
2203 Customizing readline behavior
2203 Customizing readline behavior
2204 +++++++++++++++++++++++++++++
2204 +++++++++++++++++++++++++++++
2205
2205
2206 All these features are based on the GNU readline library, which has an
2206 All these features are based on the GNU readline library, which has an
2207 extremely customizable interface. Normally, readline is configured via a
2207 extremely customizable interface. Normally, readline is configured via a
2208 file which defines the behavior of the library; the details of the
2208 file which defines the behavior of the library; the details of the
2209 syntax for this can be found in the readline documentation available
2209 syntax for this can be found in the readline documentation available
2210 with your system or on the Internet. IPython doesn't read this file (if
2210 with your system or on the Internet. IPython doesn't read this file (if
2211 it exists) directly, but it does support passing to readline valid
2211 it exists) directly, but it does support passing to readline valid
2212 options via a simple interface. In brief, you can customize readline by
2212 options via a simple interface. In brief, you can customize readline by
2213 setting the following options in your ipythonrc configuration file (note
2213 setting the following options in your ipythonrc configuration file (note
2214 that these options can not be specified at the command line):
2214 that these options can not be specified at the command line):
2215
2215
2216 * **readline_parse_and_bind**: this option can appear as many times as
2216 * **readline_parse_and_bind**: this option can appear as many times as
2217 you want, each time defining a string to be executed via a
2217 you want, each time defining a string to be executed via a
2218 readline.parse_and_bind() command. The syntax for valid commands
2218 readline.parse_and_bind() command. The syntax for valid commands
2219 of this kind can be found by reading the documentation for the GNU
2219 of this kind can be found by reading the documentation for the GNU
2220 readline library, as these commands are of the kind which readline
2220 readline library, as these commands are of the kind which readline
2221 accepts in its configuration file.
2221 accepts in its configuration file.
2222 * **readline_remove_delims**: a string of characters to be removed
2222 * **readline_remove_delims**: a string of characters to be removed
2223 from the default word-delimiters list used by readline, so that
2223 from the default word-delimiters list used by readline, so that
2224 completions may be performed on strings which contain them. Do not
2224 completions may be performed on strings which contain them. Do not
2225 change the default value unless you know what you're doing.
2225 change the default value unless you know what you're doing.
2226 * **readline_omit__names**: when tab-completion is enabled, hitting
2226 * **readline_omit__names**: when tab-completion is enabled, hitting
2227 <tab> after a '.' in a name will complete all attributes of an
2227 <tab> after a '.' in a name will complete all attributes of an
2228 object, including all the special methods whose names include
2228 object, including all the special methods whose names include
2229 double underscores (like __getitem__ or __class__). If you'd
2229 double underscores (like __getitem__ or __class__). If you'd
2230 rather not see these names by default, you can set this option to
2230 rather not see these names by default, you can set this option to
2231 1. Note that even when this option is set, you can still see those
2231 1. Note that even when this option is set, you can still see those
2232 names by explicitly typing a _ after the period and hitting <tab>:
2232 names by explicitly typing a _ after the period and hitting <tab>:
2233 'name._<tab>' will always complete attribute names starting with '_'.
2233 'name._<tab>' will always complete attribute names starting with '_'.
2234
2234
2235 This option is off by default so that new users see all
2235 This option is off by default so that new users see all
2236 attributes of any objects they are dealing with.
2236 attributes of any objects they are dealing with.
2237
2237
2238 You will find the default values along with a corresponding detailed
2238 You will find the default values along with a corresponding detailed
2239 explanation in your ipythonrc file.
2239 explanation in your ipythonrc file.
2240
2240
2241
2241
2242 Session logging and restoring
2242 Session logging and restoring
2243 -----------------------------
2243 -----------------------------
2244
2244
2245 You can log all input from a session either by starting IPython with the
2245 You can log all input from a session either by starting IPython with the
2246 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
2246 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
2247 or by activating the logging at any moment with the magic function %logstart.
2247 or by activating the logging at any moment with the magic function %logstart.
2248
2248
2249 Log files can later be reloaded with the -logplay option and IPython
2249 Log files can later be reloaded with the -logplay option and IPython
2250 will attempt to 'replay' the log by executing all the lines in it, thus
2250 will attempt to 'replay' the log by executing all the lines in it, thus
2251 restoring the state of a previous session. This feature is not quite
2251 restoring the state of a previous session. This feature is not quite
2252 perfect, but can still be useful in many cases.
2252 perfect, but can still be useful in many cases.
2253
2253
2254 The log files can also be used as a way to have a permanent record of
2254 The log files can also be used as a way to have a permanent record of
2255 any code you wrote while experimenting. Log files are regular text files
2255 any code you wrote while experimenting. Log files are regular text files
2256 which you can later open in your favorite text editor to extract code or
2256 which you can later open in your favorite text editor to extract code or
2257 to 'clean them up' before using them to replay a session.
2257 to 'clean them up' before using them to replay a session.
2258
2258
2259 The %logstart function for activating logging in mid-session is used as
2259 The %logstart function for activating logging in mid-session is used as
2260 follows:
2260 follows:
2261
2261
2262 %logstart [log_name [log_mode]]
2262 %logstart [log_name [log_mode]]
2263
2263
2264 If no name is given, it defaults to a file named 'log' in your
2264 If no name is given, it defaults to a file named 'log' in your
2265 IPYTHONDIR directory, in 'rotate' mode (see below).
2265 IPYTHONDIR directory, in 'rotate' mode (see below).
2266
2266
2267 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
2267 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
2268 history up to that point and then continues logging.
2268 history up to that point and then continues logging.
2269
2269
2270 %logstart takes a second optional parameter: logging mode. This can be
2270 %logstart takes a second optional parameter: logging mode. This can be
2271 one of (note that the modes are given unquoted):
2271 one of (note that the modes are given unquoted):
2272
2272
2273 * [over:] overwrite existing log_name.
2273 * [over:] overwrite existing log_name.
2274 * [backup:] rename (if exists) to log_name~ and start log_name.
2274 * [backup:] rename (if exists) to log_name~ and start log_name.
2275 * [append:] well, that says it.
2275 * [append:] well, that says it.
2276 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
2276 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
2277
2277
2278 The %logoff and %logon functions allow you to temporarily stop and
2278 The %logoff and %logon functions allow you to temporarily stop and
2279 resume logging to a file which had previously been started with
2279 resume logging to a file which had previously been started with
2280 %logstart. They will fail (with an explanation) if you try to use them
2280 %logstart. They will fail (with an explanation) if you try to use them
2281 before logging has been started.
2281 before logging has been started.
2282
2282
2283 .. _system_shell_access:
2283 .. _system_shell_access:
2284
2284
2285 System shell access
2285 System shell access
2286 -------------------
2286 -------------------
2287
2287
2288 Any input line beginning with a ! character is passed verbatim (minus
2288 Any input line beginning with a ! character is passed verbatim (minus
2289 the !, of course) to the underlying operating system. For example,
2289 the !, of course) to the underlying operating system. For example,
2290 typing !ls will run 'ls' in the current directory.
2290 typing !ls will run 'ls' in the current directory.
2291
2291
2292 Manual capture of command output
2292 Manual capture of command output
2293 --------------------------------
2293 --------------------------------
2294
2294
2295 If the input line begins with two exclamation marks, !!, the command is
2295 If the input line begins with two exclamation marks, !!, the command is
2296 executed but its output is captured and returned as a python list, split
2296 executed but its output is captured and returned as a python list, split
2297 on newlines. Any output sent by the subprocess to standard error is
2297 on newlines. Any output sent by the subprocess to standard error is
2298 printed separately, so that the resulting list only captures standard
2298 printed separately, so that the resulting list only captures standard
2299 output. The !! syntax is a shorthand for the %sx magic command.
2299 output. The !! syntax is a shorthand for the %sx magic command.
2300
2300
2301 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
2301 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
2302 but allowing more fine-grained control of the capture details, and
2302 but allowing more fine-grained control of the capture details, and
2303 storing the result directly into a named variable. The direct use of
2303 storing the result directly into a named variable. The direct use of
2304 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
2304 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
2305 instead.
2305 instead.
2306
2306
2307 IPython also allows you to expand the value of python variables when
2307 IPython also allows you to expand the value of python variables when
2308 making system calls. Any python variable or expression which you prepend
2308 making system calls. Any python variable or expression which you prepend
2309 with $ will get expanded before the system call is made::
2309 with $ will get expanded before the system call is made::
2310
2310
2311 In [1]: pyvar='Hello world'
2311 In [1]: pyvar='Hello world'
2312 In [2]: !echo "A python variable: $pyvar"
2312 In [2]: !echo "A python variable: $pyvar"
2313 A python variable: Hello world
2313 A python variable: Hello world
2314
2314
2315 If you want the shell to actually see a literal $, you need to type it
2315 If you want the shell to actually see a literal $, you need to type it
2316 twice::
2316 twice::
2317
2317
2318 In [3]: !echo "A system variable: $$HOME"
2318 In [3]: !echo "A system variable: $$HOME"
2319 A system variable: /home/fperez
2319 A system variable: /home/fperez
2320
2320
2321 You can pass arbitrary expressions, though you'll need to delimit them
2321 You can pass arbitrary expressions, though you'll need to delimit them
2322 with {} if there is ambiguity as to the extent of the expression::
2322 with {} if there is ambiguity as to the extent of the expression::
2323
2323
2324 In [5]: x=10
2324 In [5]: x=10
2325 In [6]: y=20
2325 In [6]: y=20
2326 In [13]: !echo $x+y
2326 In [13]: !echo $x+y
2327 10+y
2327 10+y
2328 In [7]: !echo ${x+y}
2328 In [7]: !echo ${x+y}
2329 30
2329 30
2330
2330
2331 Even object attributes can be expanded::
2331 Even object attributes can be expanded::
2332
2332
2333 In [12]: !echo $sys.argv
2333 In [12]: !echo $sys.argv
2334 [/home/fperez/usr/bin/ipython]
2334 [/home/fperez/usr/bin/ipython]
2335
2335
2336
2336
2337 System command aliases
2337 System command aliases
2338 ----------------------
2338 ----------------------
2339
2339
2340 The %alias magic function and the alias option in the ipythonrc
2340 The %alias magic function and the alias option in the ipythonrc
2341 configuration file allow you to define magic functions which are in fact
2341 configuration file allow you to define magic functions which are in fact
2342 system shell commands. These aliases can have parameters.
2342 system shell commands. These aliases can have parameters.
2343
2343
2344 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2344 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2345
2345
2346 Then, typing '%alias_name params' will execute the system command 'cmd
2346 Then, typing '%alias_name params' will execute the system command 'cmd
2347 params' (from your underlying operating system).
2347 params' (from your underlying operating system).
2348
2348
2349 You can also define aliases with parameters using %s specifiers (one per
2349 You can also define aliases with parameters using %s specifiers (one per
2350 parameter). The following example defines the %parts function as an
2350 parameter). The following example defines the %parts function as an
2351 alias to the command 'echo first %s second %s' where each %s will be
2351 alias to the command 'echo first %s second %s' where each %s will be
2352 replaced by a positional parameter to the call to %parts::
2352 replaced by a positional parameter to the call to %parts::
2353
2353
2354 In [1]: alias parts echo first %s second %s
2354 In [1]: alias parts echo first %s second %s
2355 In [2]: %parts A B
2355 In [2]: %parts A B
2356 first A second B
2356 first A second B
2357 In [3]: %parts A
2357 In [3]: %parts A
2358 Incorrect number of arguments: 2 expected.
2358 Incorrect number of arguments: 2 expected.
2359 parts is an alias to: 'echo first %s second %s'
2359 parts is an alias to: 'echo first %s second %s'
2360
2360
2361 If called with no parameters, %alias prints the table of currently
2361 If called with no parameters, %alias prints the table of currently
2362 defined aliases.
2362 defined aliases.
2363
2363
2364 The %rehash/rehashx magics allow you to load your entire $PATH as
2364 The %rehash/rehashx magics allow you to load your entire $PATH as
2365 ipython aliases. See their respective docstrings (or sec. 6.2
2365 ipython aliases. See their respective docstrings (or sec. 6.2
2366 <#sec:magic> for further details).
2366 <#sec:magic> for further details).
2367
2367
2368
2368
2369 .. _dreload:
2369 .. _dreload:
2370
2370
2371 Recursive reload
2371 Recursive reload
2372 ----------------
2372 ----------------
2373
2373
2374 The dreload function does a recursive reload of a module: changes made
2374 The dreload function does a recursive reload of a module: changes made
2375 to the module since you imported will actually be available without
2375 to the module since you imported will actually be available without
2376 having to exit.
2376 having to exit.
2377
2377
2378
2378
2379 Verbose and colored exception traceback printouts
2379 Verbose and colored exception traceback printouts
2380 -------------------------------------------------
2380 -------------------------------------------------
2381
2381
2382 IPython provides the option to see very detailed exception tracebacks,
2382 IPython provides the option to see very detailed exception tracebacks,
2383 which can be especially useful when debugging large programs. You can
2383 which can be especially useful when debugging large programs. You can
2384 run any Python file with the %run function to benefit from these
2384 run any Python file with the %run function to benefit from these
2385 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
2385 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
2386 be colored (if your terminal supports it) which makes them much easier
2386 be colored (if your terminal supports it) which makes them much easier
2387 to parse visually.
2387 to parse visually.
2388
2388
2389 See the magic xmode and colors functions for details (just type %magic).
2389 See the magic xmode and colors functions for details (just type %magic).
2390
2390
2391 These features are basically a terminal version of Ka-Ping Yee's cgitb
2391 These features are basically a terminal version of Ka-Ping Yee's cgitb
2392 module, now part of the standard Python library.
2392 module, now part of the standard Python library.
2393
2393
2394
2394
2395 .. _input_caching:
2395 .. _input_caching:
2396
2396
2397 Input caching system
2397 Input caching system
2398 --------------------
2398 --------------------
2399
2399
2400 IPython offers numbered prompts (In/Out) with input and output caching.
2400 IPython offers numbered prompts (In/Out) with input and output caching
2401 All input is saved and can be retrieved as variables (besides the usual
2401 (also referred to as 'input history'). All input is saved and can be
2402 arrow key recall).
2402 retrieved as variables (besides the usual arrow key recall), in
2403 addition to the %rep magic command that brings a history entry
2404 up for editing on the next command line.
2403
2405
2404 The following GLOBAL variables always exist (so don't overwrite them!):
2406 The following GLOBAL variables always exist (so don't overwrite them!):
2405 _i: stores previous input. _ii: next previous. _iii: next-next previous.
2407 _i: stores previous input. _ii: next previous. _iii: next-next previous.
2406 _ih : a list of all input _ih[n] is the input from line n and this list
2408 _ih : a list of all input _ih[n] is the input from line n and this list
2407 is aliased to the global variable In. If you overwrite In with a
2409 is aliased to the global variable In. If you overwrite In with a
2408 variable of your own, you can remake the assignment to the internal list
2410 variable of your own, you can remake the assignment to the internal list
2409 with a simple 'In=_ih'.
2411 with a simple 'In=_ih'.
2410
2412
2411 Additionally, global variables named _i<n> are dynamically created (<n>
2413 Additionally, global variables named _i<n> are dynamically created (<n>
2412 being the prompt counter), such that
2414 being the prompt counter), such that
2413 _i<n> == _ih[<n>] == In[<n>].
2415 _i<n> == _ih[<n>] == In[<n>].
2414
2416
2415 For example, what you typed at prompt 14 is available as _i14, _ih[14]
2417 For example, what you typed at prompt 14 is available as _i14, _ih[14]
2416 and In[14].
2418 and In[14].
2417
2419
2418 This allows you to easily cut and paste multi line interactive prompts
2420 This allows you to easily cut and paste multi line interactive prompts
2419 by printing them out: they print like a clean string, without prompt
2421 by printing them out: they print like a clean string, without prompt
2420 characters. You can also manipulate them like regular variables (they
2422 characters. You can also manipulate them like regular variables (they
2421 are strings), modify or exec them (typing 'exec _i9' will re-execute the
2423 are strings), modify or exec them (typing 'exec _i9' will re-execute the
2422 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
2424 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
2423 9 through 13 and line 18).
2425 9 through 13 and line 18).
2424
2426
2425 You can also re-execute multiple lines of input easily by using the
2427 You can also re-execute multiple lines of input easily by using the
2426 magic %macro function (which automates the process and allows
2428 magic %macro function (which automates the process and allows
2427 re-execution without having to type 'exec' every time). The macro system
2429 re-execution without having to type 'exec' every time). The macro system
2428 also allows you to re-execute previous lines which include magic
2430 also allows you to re-execute previous lines which include magic
2429 function calls (which require special processing). Type %macro? or see
2431 function calls (which require special processing). Type %macro? or see
2430 sec. 6.2 <#sec:magic> for more details on the macro system.
2432 sec. 6.2 <#sec:magic> for more details on the macro system.
2431
2433
2432 A history function %hist allows you to see any part of your input
2434 A history function %hist allows you to see any part of your input
2433 history by printing a range of the _i variables.
2435 history by printing a range of the _i variables.
2434
2436
2437 You can also search ('grep') through your history by typing
2438 '%hist -g somestring'. This also searches through the so called *shadow history*,
2439 which remembers all the commands (apart from multiline code blocks)
2440 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
2441 etc. You can bring shadow history entries listed by '%hist -g' up for editing
2442 (or re-execution by just pressing ENTER) with %rep command. Shadow history
2443 entries are not available as _iNUMBER variables, and they are identified by
2444 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
2445 history entry, but 0231 is a shadow history entry.
2446
2447 Shadow history was added because the readline history is inherently very
2448 unsafe - if you have multiple IPython sessions open, the last session
2449 to close will overwrite the history of previountly closed session. Likewise,
2450 if a crash occurs, history is never saved, whereas shadow history entries
2451 are added after entering every command (so a command executed
2452 in another IPython session is immediately available in other IPython
2453 sessions that are open).
2454
2455 To conserve space, a command can exist in shadow history only once - it doesn't
2456 make sense to store a common line like "cd .." a thousand times. The idea is
2457 mainly to provide a reliable place where valuable, hard-to-remember commands can
2458 always be retrieved, as opposed to providing an exact sequence of commands
2459 you have entered in actual order.
2460
2461 Because shadow history has all the commands you have ever executed,
2462 time taken by %hist -g will increase oven time. If it ever starts to take
2463 too long (or it ends up containing sensitive information like passwords),
2464 clear the shadow history by `%clear shadow_nuke`.
2465
2466 Time taken to add entries to shadow history should be negligible, but
2467 in any case, if you start noticing performance degradation after using
2468 IPython for a long time (or running a script that floods the shadow history!),
2469 you can 'compress' the shadow history by executing
2470 `%clear shadow_compress`. In practice, this should never be necessary
2471 in normal use.
2472
2435 .. _output_caching:
2473 .. _output_caching:
2436
2474
2437 Output caching system
2475 Output caching system
2438 ---------------------
2476 ---------------------
2439
2477
2440 For output that is returned from actions, a system similar to the input
2478 For output that is returned from actions, a system similar to the input
2441 cache exists but using _ instead of _i. Only actions that produce a
2479 cache exists but using _ instead of _i. Only actions that produce a
2442 result (NOT assignments, for example) are cached. If you are familiar
2480 result (NOT assignments, for example) are cached. If you are familiar
2443 with Mathematica, IPython's _ variables behave exactly like
2481 with Mathematica, IPython's _ variables behave exactly like
2444 Mathematica's % variables.
2482 Mathematica's % variables.
2445
2483
2446 The following GLOBAL variables always exist (so don't overwrite them!):
2484 The following GLOBAL variables always exist (so don't overwrite them!):
2447
2485
2448 * [_] (a single underscore) : stores previous output, like Python's
2486 * [_] (a single underscore) : stores previous output, like Python's
2449 default interpreter.
2487 default interpreter.
2450 * [__] (two underscores): next previous.
2488 * [__] (two underscores): next previous.
2451 * [___] (three underscores): next-next previous.
2489 * [___] (three underscores): next-next previous.
2452
2490
2453 Additionally, global variables named _<n> are dynamically created (<n>
2491 Additionally, global variables named _<n> are dynamically created (<n>
2454 being the prompt counter), such that the result of output <n> is always
2492 being the prompt counter), such that the result of output <n> is always
2455 available as _<n> (don't use the angle brackets, just the number, e.g.
2493 available as _<n> (don't use the angle brackets, just the number, e.g.
2456 _21).
2494 _21).
2457
2495
2458 These global variables are all stored in a global dictionary (not a
2496 These global variables are all stored in a global dictionary (not a
2459 list, since it only has entries for lines which returned a result)
2497 list, since it only has entries for lines which returned a result)
2460 available under the names _oh and Out (similar to _ih and In). So the
2498 available under the names _oh and Out (similar to _ih and In). So the
2461 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
2499 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
2462 accidentally overwrite the Out variable you can recover it by typing
2500 accidentally overwrite the Out variable you can recover it by typing
2463 'Out=_oh' at the prompt.
2501 'Out=_oh' at the prompt.
2464
2502
2465 This system obviously can potentially put heavy memory demands on your
2503 This system obviously can potentially put heavy memory demands on your
2466 system, since it prevents Python's garbage collector from removing any
2504 system, since it prevents Python's garbage collector from removing any
2467 previously computed results. You can control how many results are kept
2505 previously computed results. You can control how many results are kept
2468 in memory with the option (at the command line or in your ipythonrc
2506 in memory with the option (at the command line or in your ipythonrc
2469 file) cache_size. If you set it to 0, the whole system is completely
2507 file) cache_size. If you set it to 0, the whole system is completely
2470 disabled and the prompts revert to the classic '>>>' of normal Python.
2508 disabled and the prompts revert to the classic '>>>' of normal Python.
2471
2509
2472
2510
2473 Directory history
2511 Directory history
2474 -----------------
2512 -----------------
2475
2513
2476 Your history of visited directories is kept in the global list _dh, and
2514 Your history of visited directories is kept in the global list _dh, and
2477 the magic %cd command can be used to go to any entry in that list. The
2515 the magic %cd command can be used to go to any entry in that list. The
2478 %dhist command allows you to view this history. do ``cd -<TAB`` to
2516 %dhist command allows you to view this history. Do ``cd -<TAB`` to
2479 conventiently view the directory history.
2517 conventiently view the directory history.
2480
2518
2481
2519
2482 Automatic parentheses and quotes
2520 Automatic parentheses and quotes
2483 --------------------------------
2521 --------------------------------
2484
2522
2485 These features were adapted from Nathan Gray's LazyPython. They are
2523 These features were adapted from Nathan Gray's LazyPython. They are
2486 meant to allow less typing for common situations.
2524 meant to allow less typing for common situations.
2487
2525
2488
2526
2489 Automatic parentheses
2527 Automatic parentheses
2490 ---------------------
2528 ---------------------
2491
2529
2492 Callable objects (i.e. functions, methods, etc) can be invoked like this
2530 Callable objects (i.e. functions, methods, etc) can be invoked like this
2493 (notice the commas between the arguments)::
2531 (notice the commas between the arguments)::
2494
2532
2495 >>> callable_ob arg1, arg2, arg3
2533 >>> callable_ob arg1, arg2, arg3
2496
2534
2497 and the input will be translated to this::
2535 and the input will be translated to this::
2498
2536
2499 -> callable_ob(arg1, arg2, arg3)
2537 -> callable_ob(arg1, arg2, arg3)
2500
2538
2501 You can force automatic parentheses by using '/' as the first character
2539 You can force automatic parentheses by using '/' as the first character
2502 of a line. For example::
2540 of a line. For example::
2503
2541
2504 >>> /globals # becomes 'globals()'
2542 >>> /globals # becomes 'globals()'
2505
2543
2506 Note that the '/' MUST be the first character on the line! This won't work::
2544 Note that the '/' MUST be the first character on the line! This won't work::
2507
2545
2508 >>> print /globals # syntax error
2546 >>> print /globals # syntax error
2509
2547
2510 In most cases the automatic algorithm should work, so you should rarely
2548 In most cases the automatic algorithm should work, so you should rarely
2511 need to explicitly invoke /. One notable exception is if you are trying
2549 need to explicitly invoke /. One notable exception is if you are trying
2512 to call a function with a list of tuples as arguments (the parenthesis
2550 to call a function with a list of tuples as arguments (the parenthesis
2513 will confuse IPython)::
2551 will confuse IPython)::
2514
2552
2515 In [1]: zip (1,2,3),(4,5,6) # won't work
2553 In [1]: zip (1,2,3),(4,5,6) # won't work
2516
2554
2517 but this will work::
2555 but this will work::
2518
2556
2519 In [2]: /zip (1,2,3),(4,5,6)
2557 In [2]: /zip (1,2,3),(4,5,6)
2520 ---> zip ((1,2,3),(4,5,6))
2558 ---> zip ((1,2,3),(4,5,6))
2521 Out[2]= [(1, 4), (2, 5), (3, 6)]
2559 Out[2]= [(1, 4), (2, 5), (3, 6)]
2522
2560
2523 IPython tells you that it has altered your command line by displaying
2561 IPython tells you that it has altered your command line by displaying
2524 the new command line preceded by ->. e.g.::
2562 the new command line preceded by ->. e.g.::
2525
2563
2526 In [18]: callable list
2564 In [18]: callable list
2527 ----> callable (list)
2565 ----> callable (list)
2528
2566
2529
2567
2530 Automatic quoting
2568 Automatic quoting
2531 -----------------
2569 -----------------
2532
2570
2533 You can force automatic quoting of a function's arguments by using ','
2571 You can force automatic quoting of a function's arguments by using ','
2534 or ';' as the first character of a line. For example::
2572 or ';' as the first character of a line. For example::
2535
2573
2536 >>> ,my_function /home/me # becomes my_function("/home/me")
2574 >>> ,my_function /home/me # becomes my_function("/home/me")
2537
2575
2538 If you use ';' instead, the whole argument is quoted as a single string
2576 If you use ';' instead, the whole argument is quoted as a single string
2539 (while ',' splits on whitespace)::
2577 (while ',' splits on whitespace)::
2540
2578
2541 >>> ,my_function a b c # becomes my_function("a","b","c")
2579 >>> ,my_function a b c # becomes my_function("a","b","c")
2542
2580
2543 >>> ;my_function a b c # becomes my_function("a b c")
2581 >>> ;my_function a b c # becomes my_function("a b c")
2544
2582
2545 Note that the ',' or ';' MUST be the first character on the line! This
2583 Note that the ',' or ';' MUST be the first character on the line! This
2546 won't work::
2584 won't work::
2547
2585
2548 >>> x = ,my_function /home/me # syntax error
2586 >>> x = ,my_function /home/me # syntax error
2549
2587
2550 IPython as your default Python environment
2588 IPython as your default Python environment
2551 ==========================================
2589 ==========================================
2552
2590
2553 Python honors the environment variable PYTHONSTARTUP and will execute at
2591 Python honors the environment variable PYTHONSTARTUP and will execute at
2554 startup the file referenced by this variable. If you put at the end of
2592 startup the file referenced by this variable. If you put at the end of
2555 this file the following two lines of code::
2593 this file the following two lines of code::
2556
2594
2557 import IPython
2595 import IPython
2558 IPython.Shell.IPShell().mainloop(sys_exit=1)
2596 IPython.Shell.IPShell().mainloop(sys_exit=1)
2559
2597
2560 then IPython will be your working environment anytime you start Python.
2598 then IPython will be your working environment anytime you start Python.
2561 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
2599 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
2562 it finishes, otherwise you'll be back at the normal Python '>>>'
2600 it finishes, otherwise you'll be back at the normal Python '>>>'
2563 prompt.
2601 prompt.
2564
2602
2565 This is probably useful to developers who manage multiple Python
2603 This is probably useful to developers who manage multiple Python
2566 versions and don't want to have correspondingly multiple IPython
2604 versions and don't want to have correspondingly multiple IPython
2567 versions. Note that in this mode, there is no way to pass IPython any
2605 versions. Note that in this mode, there is no way to pass IPython any
2568 command-line options, as those are trapped first by Python itself.
2606 command-line options, as those are trapped first by Python itself.
2569
2607
2570 .. _Embedding:
2608 .. _Embedding:
2571
2609
2572 Embedding IPython
2610 Embedding IPython
2573 =================
2611 =================
2574
2612
2575 It is possible to start an IPython instance inside your own Python
2613 It is possible to start an IPython instance inside your own Python
2576 programs. This allows you to evaluate dynamically the state of your
2614 programs. This allows you to evaluate dynamically the state of your
2577 code, operate with your variables, analyze them, etc. Note however that
2615 code, operate with your variables, analyze them, etc. Note however that
2578 any changes you make to values while in the shell do not propagate back
2616 any changes you make to values while in the shell do not propagate back
2579 to the running code, so it is safe to modify your values because you
2617 to the running code, so it is safe to modify your values because you
2580 won't break your code in bizarre ways by doing so.
2618 won't break your code in bizarre ways by doing so.
2581
2619
2582 This feature allows you to easily have a fully functional python
2620 This feature allows you to easily have a fully functional python
2583 environment for doing object introspection anywhere in your code with a
2621 environment for doing object introspection anywhere in your code with a
2584 simple function call. In some cases a simple print statement is enough,
2622 simple function call. In some cases a simple print statement is enough,
2585 but if you need to do more detailed analysis of a code fragment this
2623 but if you need to do more detailed analysis of a code fragment this
2586 feature can be very valuable.
2624 feature can be very valuable.
2587
2625
2588 It can also be useful in scientific computing situations where it is
2626 It can also be useful in scientific computing situations where it is
2589 common to need to do some automatic, computationally intensive part and
2627 common to need to do some automatic, computationally intensive part and
2590 then stop to look at data, plots, etc.
2628 then stop to look at data, plots, etc.
2591 Opening an IPython instance will give you full access to your data and
2629 Opening an IPython instance will give you full access to your data and
2592 functions, and you can resume program execution once you are done with
2630 functions, and you can resume program execution once you are done with
2593 the interactive part (perhaps to stop again later, as many times as
2631 the interactive part (perhaps to stop again later, as many times as
2594 needed).
2632 needed).
2595
2633
2596 The following code snippet is the bare minimum you need to include in
2634 The following code snippet is the bare minimum you need to include in
2597 your Python programs for this to work (detailed examples follow later)::
2635 your Python programs for this to work (detailed examples follow later)::
2598
2636
2599 from IPython.Shell import IPShellEmbed
2637 from IPython.Shell import IPShellEmbed
2600
2638
2601 ipshell = IPShellEmbed()
2639 ipshell = IPShellEmbed()
2602
2640
2603 ipshell() # this call anywhere in your program will start IPython
2641 ipshell() # this call anywhere in your program will start IPython
2604
2642
2605 You can run embedded instances even in code which is itself being run at
2643 You can run embedded instances even in code which is itself being run at
2606 the IPython interactive prompt with '%run <filename>'. Since it's easy
2644 the IPython interactive prompt with '%run <filename>'. Since it's easy
2607 to get lost as to where you are (in your top-level IPython or in your
2645 to get lost as to where you are (in your top-level IPython or in your
2608 embedded one), it's a good idea in such cases to set the in/out prompts
2646 embedded one), it's a good idea in such cases to set the in/out prompts
2609 to something different for the embedded instances. The code examples
2647 to something different for the embedded instances. The code examples
2610 below illustrate this.
2648 below illustrate this.
2611
2649
2612 You can also have multiple IPython instances in your program and open
2650 You can also have multiple IPython instances in your program and open
2613 them separately, for example with different options for data
2651 them separately, for example with different options for data
2614 presentation. If you close and open the same instance multiple times,
2652 presentation. If you close and open the same instance multiple times,
2615 its prompt counters simply continue from each execution to the next.
2653 its prompt counters simply continue from each execution to the next.
2616
2654
2617 Please look at the docstrings in the Shell.py module for more details on
2655 Please look at the docstrings in the Shell.py module for more details on
2618 the use of this system.
2656 the use of this system.
2619
2657
2620 The following sample file illustrating how to use the embedding
2658 The following sample file illustrating how to use the embedding
2621 functionality is provided in the examples directory as example-embed.py.
2659 functionality is provided in the examples directory as example-embed.py.
2622 It should be fairly self-explanatory::
2660 It should be fairly self-explanatory::
2623
2661
2624
2662
2625 #!/usr/bin/env python
2663 #!/usr/bin/env python
2626
2664
2627 """An example of how to embed an IPython shell into a running program.
2665 """An example of how to embed an IPython shell into a running program.
2628
2666
2629 Please see the documentation in the IPython.Shell module for more details.
2667 Please see the documentation in the IPython.Shell module for more details.
2630
2668
2631 The accompanying file example-embed-short.py has quick code fragments for
2669 The accompanying file example-embed-short.py has quick code fragments for
2632 embedding which you can cut and paste in your code once you understand how
2670 embedding which you can cut and paste in your code once you understand how
2633 things work.
2671 things work.
2634
2672
2635 The code in this file is deliberately extra-verbose, meant for learning."""
2673 The code in this file is deliberately extra-verbose, meant for learning."""
2636
2674
2637 # The basics to get you going:
2675 # The basics to get you going:
2638
2676
2639 # IPython sets the __IPYTHON__ variable so you can know if you have nested
2677 # IPython sets the __IPYTHON__ variable so you can know if you have nested
2640 # copies running.
2678 # copies running.
2641
2679
2642 # Try running this code both at the command line and from inside IPython (with
2680 # Try running this code both at the command line and from inside IPython (with
2643 # %run example-embed.py)
2681 # %run example-embed.py)
2644 try:
2682 try:
2645 __IPYTHON__
2683 __IPYTHON__
2646 except NameError:
2684 except NameError:
2647 nested = 0
2685 nested = 0
2648 args = ['']
2686 args = ['']
2649 else:
2687 else:
2650 print "Running nested copies of IPython."
2688 print "Running nested copies of IPython."
2651 print "The prompts for the nested copy have been modified"
2689 print "The prompts for the nested copy have been modified"
2652 nested = 1
2690 nested = 1
2653 # what the embedded instance will see as sys.argv:
2691 # what the embedded instance will see as sys.argv:
2654 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
2692 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
2655 '-po','Out<\\#>: ','-nosep']
2693 '-po','Out<\\#>: ','-nosep']
2656
2694
2657 # First import the embeddable shell class
2695 # First import the embeddable shell class
2658 from IPython.Shell import IPShellEmbed
2696 from IPython.Shell import IPShellEmbed
2659
2697
2660 # Now create an instance of the embeddable shell. The first argument is a
2698 # Now create an instance of the embeddable shell. The first argument is a
2661 # string with options exactly as you would type them if you were starting
2699 # string with options exactly as you would type them if you were starting
2662 # IPython at the system command line. Any parameters you want to define for
2700 # IPython at the system command line. Any parameters you want to define for
2663 # configuration can thus be specified here.
2701 # configuration can thus be specified here.
2664 ipshell = IPShellEmbed(args,
2702 ipshell = IPShellEmbed(args,
2665 banner = 'Dropping into IPython',
2703 banner = 'Dropping into IPython',
2666 exit_msg = 'Leaving Interpreter, back to program.')
2704 exit_msg = 'Leaving Interpreter, back to program.')
2667
2705
2668 # Make a second instance, you can have as many as you want.
2706 # Make a second instance, you can have as many as you want.
2669 if nested:
2707 if nested:
2670 args[1] = 'In2<\\#>'
2708 args[1] = 'In2<\\#>'
2671 else:
2709 else:
2672 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
2710 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
2673 '-po','Out<\\#>: ','-nosep']
2711 '-po','Out<\\#>: ','-nosep']
2674 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
2712 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
2675
2713
2676 print '\nHello. This is printed from the main controller program.\n'
2714 print '\nHello. This is printed from the main controller program.\n'
2677
2715
2678 # You can then call ipshell() anywhere you need it (with an optional
2716 # You can then call ipshell() anywhere you need it (with an optional
2679 # message):
2717 # message):
2680 ipshell('***Called from top level. '
2718 ipshell('***Called from top level. '
2681 'Hit Ctrl-D to exit interpreter and continue program.\n'
2719 'Hit Ctrl-D to exit interpreter and continue program.\n'
2682 'Note that if you use %kill_embedded, you can fully deactivate\n'
2720 'Note that if you use %kill_embedded, you can fully deactivate\n'
2683 'This embedded instance so it will never turn on again')
2721 'This embedded instance so it will never turn on again')
2684
2722
2685 print '\nBack in caller program, moving along...\n'
2723 print '\nBack in caller program, moving along...\n'
2686
2724
2687 #---------------------------------------------------------------------------
2725 #---------------------------------------------------------------------------
2688 # More details:
2726 # More details:
2689
2727
2690 # IPShellEmbed instances don't print the standard system banner and
2728 # IPShellEmbed instances don't print the standard system banner and
2691 # messages. The IPython banner (which actually may contain initialization
2729 # messages. The IPython banner (which actually may contain initialization
2692 # messages) is available as <instance>.IP.BANNER in case you want it.
2730 # messages) is available as <instance>.IP.BANNER in case you want it.
2693
2731
2694 # IPShellEmbed instances print the following information everytime they
2732 # IPShellEmbed instances print the following information everytime they
2695 # start:
2733 # start:
2696
2734
2697 # - A global startup banner.
2735 # - A global startup banner.
2698
2736
2699 # - A call-specific header string, which you can use to indicate where in the
2737 # - A call-specific header string, which you can use to indicate where in the
2700 # execution flow the shell is starting.
2738 # execution flow the shell is starting.
2701
2739
2702 # They also print an exit message every time they exit.
2740 # They also print an exit message every time they exit.
2703
2741
2704 # Both the startup banner and the exit message default to None, and can be set
2742 # Both the startup banner and the exit message default to None, and can be set
2705 # either at the instance constructor or at any other time with the
2743 # either at the instance constructor or at any other time with the
2706 # set_banner() and set_exit_msg() methods.
2744 # set_banner() and set_exit_msg() methods.
2707
2745
2708 # The shell instance can be also put in 'dummy' mode globally or on a per-call
2746 # The shell instance can be also put in 'dummy' mode globally or on a per-call
2709 # basis. This gives you fine control for debugging without having to change
2747 # basis. This gives you fine control for debugging without having to change
2710 # code all over the place.
2748 # code all over the place.
2711
2749
2712 # The code below illustrates all this.
2750 # The code below illustrates all this.
2713
2751
2714
2752
2715 # This is how the global banner and exit_msg can be reset at any point
2753 # This is how the global banner and exit_msg can be reset at any point
2716 ipshell.set_banner('Entering interpreter - New Banner')
2754 ipshell.set_banner('Entering interpreter - New Banner')
2717 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
2755 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
2718
2756
2719 def foo(m):
2757 def foo(m):
2720 s = 'spam'
2758 s = 'spam'
2721 ipshell('***In foo(). Try @whos, or print s or m:')
2759 ipshell('***In foo(). Try @whos, or print s or m:')
2722 print 'foo says m = ',m
2760 print 'foo says m = ',m
2723
2761
2724 def bar(n):
2762 def bar(n):
2725 s = 'eggs'
2763 s = 'eggs'
2726 ipshell('***In bar(). Try @whos, or print s or n:')
2764 ipshell('***In bar(). Try @whos, or print s or n:')
2727 print 'bar says n = ',n
2765 print 'bar says n = ',n
2728
2766
2729 # Some calls to the above functions which will trigger IPython:
2767 # Some calls to the above functions which will trigger IPython:
2730 print 'Main program calling foo("eggs")\n'
2768 print 'Main program calling foo("eggs")\n'
2731 foo('eggs')
2769 foo('eggs')
2732
2770
2733 # The shell can be put in 'dummy' mode where calls to it silently return. This
2771 # The shell can be put in 'dummy' mode where calls to it silently return. This
2734 # allows you, for example, to globally turn off debugging for a program with a
2772 # allows you, for example, to globally turn off debugging for a program with a
2735 # single call.
2773 # single call.
2736 ipshell.set_dummy_mode(1)
2774 ipshell.set_dummy_mode(1)
2737 print '\nTrying to call IPython which is now "dummy":'
2775 print '\nTrying to call IPython which is now "dummy":'
2738 ipshell()
2776 ipshell()
2739 print 'Nothing happened...'
2777 print 'Nothing happened...'
2740 # The global 'dummy' mode can still be overridden for a single call
2778 # The global 'dummy' mode can still be overridden for a single call
2741 print '\nOverriding dummy mode manually:'
2779 print '\nOverriding dummy mode manually:'
2742 ipshell(dummy=0)
2780 ipshell(dummy=0)
2743
2781
2744 # Reactivate the IPython shell
2782 # Reactivate the IPython shell
2745 ipshell.set_dummy_mode(0)
2783 ipshell.set_dummy_mode(0)
2746
2784
2747 print 'You can even have multiple embedded instances:'
2785 print 'You can even have multiple embedded instances:'
2748 ipshell2()
2786 ipshell2()
2749
2787
2750 print '\nMain program calling bar("spam")\n'
2788 print '\nMain program calling bar("spam")\n'
2751 bar('spam')
2789 bar('spam')
2752
2790
2753 print 'Main program finished. Bye!'
2791 print 'Main program finished. Bye!'
2754
2792
2755 #********************** End of file <example-embed.py> ***********************
2793 #********************** End of file <example-embed.py> ***********************
2756
2794
2757 Once you understand how the system functions, you can use the following
2795 Once you understand how the system functions, you can use the following
2758 code fragments in your programs which are ready for cut and paste::
2796 code fragments in your programs which are ready for cut and paste::
2759
2797
2760
2798
2761 """Quick code snippets for embedding IPython into other programs.
2799 """Quick code snippets for embedding IPython into other programs.
2762
2800
2763 See example-embed.py for full details, this file has the bare minimum code for
2801 See example-embed.py for full details, this file has the bare minimum code for
2764 cut and paste use once you understand how to use the system."""
2802 cut and paste use once you understand how to use the system."""
2765
2803
2766 #---------------------------------------------------------------------------
2804 #---------------------------------------------------------------------------
2767 # This code loads IPython but modifies a few things if it detects it's running
2805 # This code loads IPython but modifies a few things if it detects it's running
2768 # embedded in another IPython session (helps avoid confusion)
2806 # embedded in another IPython session (helps avoid confusion)
2769
2807
2770 try:
2808 try:
2771 __IPYTHON__
2809 __IPYTHON__
2772 except NameError:
2810 except NameError:
2773 argv = ['']
2811 argv = ['']
2774 banner = exit_msg = ''
2812 banner = exit_msg = ''
2775 else:
2813 else:
2776 # Command-line options for IPython (a list like sys.argv)
2814 # Command-line options for IPython (a list like sys.argv)
2777 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
2815 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
2778 banner = '*** Nested interpreter ***'
2816 banner = '*** Nested interpreter ***'
2779 exit_msg = '*** Back in main IPython ***'
2817 exit_msg = '*** Back in main IPython ***'
2780
2818
2781 # First import the embeddable shell class
2819 # First import the embeddable shell class
2782 from IPython.Shell import IPShellEmbed
2820 from IPython.Shell import IPShellEmbed
2783 # Now create the IPython shell instance. Put ipshell() anywhere in your code
2821 # Now create the IPython shell instance. Put ipshell() anywhere in your code
2784 # where you want it to open.
2822 # where you want it to open.
2785 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
2823 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
2786
2824
2787 #---------------------------------------------------------------------------
2825 #---------------------------------------------------------------------------
2788 # This code will load an embeddable IPython shell always with no changes for
2826 # This code will load an embeddable IPython shell always with no changes for
2789 # nested embededings.
2827 # nested embededings.
2790
2828
2791 from IPython.Shell import IPShellEmbed
2829 from IPython.Shell import IPShellEmbed
2792 ipshell = IPShellEmbed()
2830 ipshell = IPShellEmbed()
2793 # Now ipshell() will open IPython anywhere in the code.
2831 # Now ipshell() will open IPython anywhere in the code.
2794
2832
2795 #---------------------------------------------------------------------------
2833 #---------------------------------------------------------------------------
2796 # This code loads an embeddable shell only if NOT running inside
2834 # This code loads an embeddable shell only if NOT running inside
2797 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
2835 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
2798 # dummy function.
2836 # dummy function.
2799
2837
2800 try:
2838 try:
2801 __IPYTHON__
2839 __IPYTHON__
2802 except NameError:
2840 except NameError:
2803 from IPython.Shell import IPShellEmbed
2841 from IPython.Shell import IPShellEmbed
2804 ipshell = IPShellEmbed()
2842 ipshell = IPShellEmbed()
2805 # Now ipshell() will open IPython anywhere in the code
2843 # Now ipshell() will open IPython anywhere in the code
2806 else:
2844 else:
2807 # Define a dummy ipshell() so the same code doesn't crash inside an
2845 # Define a dummy ipshell() so the same code doesn't crash inside an
2808 # interactive IPython
2846 # interactive IPython
2809 def ipshell(): pass
2847 def ipshell(): pass
2810
2848
2811 #******************* End of file <example-embed-short.py> ********************
2849 #******************* End of file <example-embed-short.py> ********************
2812
2850
2813 Using the Python debugger (pdb)
2851 Using the Python debugger (pdb)
2814 ===============================
2852 ===============================
2815
2853
2816 Running entire programs via pdb
2854 Running entire programs via pdb
2817 -------------------------------
2855 -------------------------------
2818
2856
2819 pdb, the Python debugger, is a powerful interactive debugger which
2857 pdb, the Python debugger, is a powerful interactive debugger which
2820 allows you to step through code, set breakpoints, watch variables,
2858 allows you to step through code, set breakpoints, watch variables,
2821 etc. IPython makes it very easy to start any script under the control
2859 etc. IPython makes it very easy to start any script under the control
2822 of pdb, regardless of whether you have wrapped it into a 'main()'
2860 of pdb, regardless of whether you have wrapped it into a 'main()'
2823 function or not. For this, simply type '%run -d myscript' at an
2861 function or not. For this, simply type '%run -d myscript' at an
2824 IPython prompt. See the %run command's documentation (via '%run?' or
2862 IPython prompt. See the %run command's documentation (via '%run?' or
2825 in Sec. magic_ for more details, including how to control where pdb
2863 in Sec. magic_ for more details, including how to control where pdb
2826 will stop execution first.
2864 will stop execution first.
2827
2865
2828 For more information on the use of the pdb debugger, read the included
2866 For more information on the use of the pdb debugger, read the included
2829 pdb.doc file (part of the standard Python distribution). On a stock
2867 pdb.doc file (part of the standard Python distribution). On a stock
2830 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
2868 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
2831 easiest way to read it is by using the help() function of the pdb module
2869 easiest way to read it is by using the help() function of the pdb module
2832 as follows (in an IPython prompt):
2870 as follows (in an IPython prompt):
2833
2871
2834 In [1]: import pdb
2872 In [1]: import pdb
2835 In [2]: pdb.help()
2873 In [2]: pdb.help()
2836
2874
2837 This will load the pdb.doc document in a file viewer for you automatically.
2875 This will load the pdb.doc document in a file viewer for you automatically.
2838
2876
2839
2877
2840 Automatic invocation of pdb on exceptions
2878 Automatic invocation of pdb on exceptions
2841 -----------------------------------------
2879 -----------------------------------------
2842
2880
2843 IPython, if started with the -pdb option (or if the option is set in
2881 IPython, if started with the -pdb option (or if the option is set in
2844 your rc file) can call the Python pdb debugger every time your code
2882 your rc file) can call the Python pdb debugger every time your code
2845 triggers an uncaught exception. This feature
2883 triggers an uncaught exception. This feature
2846 can also be toggled at any time with the %pdb magic command. This can be
2884 can also be toggled at any time with the %pdb magic command. This can be
2847 extremely useful in order to find the origin of subtle bugs, because pdb
2885 extremely useful in order to find the origin of subtle bugs, because pdb
2848 opens up at the point in your code which triggered the exception, and
2886 opens up at the point in your code which triggered the exception, and
2849 while your program is at this point 'dead', all the data is still
2887 while your program is at this point 'dead', all the data is still
2850 available and you can walk up and down the stack frame and understand
2888 available and you can walk up and down the stack frame and understand
2851 the origin of the problem.
2889 the origin of the problem.
2852
2890
2853 Furthermore, you can use these debugging facilities both with the
2891 Furthermore, you can use these debugging facilities both with the
2854 embedded IPython mode and without IPython at all. For an embedded shell
2892 embedded IPython mode and without IPython at all. For an embedded shell
2855 (see sec. Embedding_), simply call the constructor with
2893 (see sec. Embedding_), simply call the constructor with
2856 '-pdb' in the argument string and automatically pdb will be called if an
2894 '-pdb' in the argument string and automatically pdb will be called if an
2857 uncaught exception is triggered by your code.
2895 uncaught exception is triggered by your code.
2858
2896
2859 For stand-alone use of the feature in your programs which do not use
2897 For stand-alone use of the feature in your programs which do not use
2860 IPython at all, put the following lines toward the top of your 'main'
2898 IPython at all, put the following lines toward the top of your 'main'
2861 routine::
2899 routine::
2862
2900
2863 import sys,IPython.ultraTB
2901 import sys,IPython.ultraTB
2864 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
2902 sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose',
2865 color_scheme='Linux', call_pdb=1)
2903 color_scheme='Linux', call_pdb=1)
2866
2904
2867 The mode keyword can be either 'Verbose' or 'Plain', giving either very
2905 The mode keyword can be either 'Verbose' or 'Plain', giving either very
2868 detailed or normal tracebacks respectively. The color_scheme keyword can
2906 detailed or normal tracebacks respectively. The color_scheme keyword can
2869 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
2907 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
2870 options which can be set in IPython with -colors and -xmode.
2908 options which can be set in IPython with -colors and -xmode.
2871
2909
2872 This will give any of your programs detailed, colored tracebacks with
2910 This will give any of your programs detailed, colored tracebacks with
2873 automatic invocation of pdb.
2911 automatic invocation of pdb.
2874
2912
2875
2913
2876 Extensions for syntax processing
2914 Extensions for syntax processing
2877 ================================
2915 ================================
2878
2916
2879 This isn't for the faint of heart, because the potential for breaking
2917 This isn't for the faint of heart, because the potential for breaking
2880 things is quite high. But it can be a very powerful and useful feature.
2918 things is quite high. But it can be a very powerful and useful feature.
2881 In a nutshell, you can redefine the way IPython processes the user input
2919 In a nutshell, you can redefine the way IPython processes the user input
2882 line to accept new, special extensions to the syntax without needing to
2920 line to accept new, special extensions to the syntax without needing to
2883 change any of IPython's own code.
2921 change any of IPython's own code.
2884
2922
2885 In the IPython/Extensions directory you will find some examples
2923 In the IPython/Extensions directory you will find some examples
2886 supplied, which we will briefly describe now. These can be used 'as is'
2924 supplied, which we will briefly describe now. These can be used 'as is'
2887 (and both provide very useful functionality), or you can use them as a
2925 (and both provide very useful functionality), or you can use them as a
2888 starting point for writing your own extensions.
2926 starting point for writing your own extensions.
2889
2927
2890
2928
2891 Pasting of code starting with '>>> ' or '... '
2929 Pasting of code starting with '>>> ' or '... '
2892 ----------------------------------------------
2930 ----------------------------------------------
2893
2931
2894 In the python tutorial it is common to find code examples which have
2932 In the python tutorial it is common to find code examples which have
2895 been taken from real python sessions. The problem with those is that all
2933 been taken from real python sessions. The problem with those is that all
2896 the lines begin with either '>>> ' or '... ', which makes it impossible
2934 the lines begin with either '>>> ' or '... ', which makes it impossible
2897 to paste them all at once. One must instead do a line by line manual
2935 to paste them all at once. One must instead do a line by line manual
2898 copying, carefully removing the leading extraneous characters.
2936 copying, carefully removing the leading extraneous characters.
2899
2937
2900 This extension identifies those starting characters and removes them
2938 This extension identifies those starting characters and removes them
2901 from the input automatically, so that one can paste multi-line examples
2939 from the input automatically, so that one can paste multi-line examples
2902 directly into IPython, saving a lot of time. Please look at the file
2940 directly into IPython, saving a lot of time. Please look at the file
2903 InterpreterPasteInput.py in the IPython/Extensions directory for details
2941 InterpreterPasteInput.py in the IPython/Extensions directory for details
2904 on how this is done.
2942 on how this is done.
2905
2943
2906 IPython comes with a special profile enabling this feature, called
2944 IPython comes with a special profile enabling this feature, called
2907 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
2945 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
2908 will be available. In a normal IPython session you can activate the
2946 will be available. In a normal IPython session you can activate the
2909 feature by importing the corresponding module with:
2947 feature by importing the corresponding module with:
2910 In [1]: import IPython.Extensions.InterpreterPasteInput
2948 In [1]: import IPython.Extensions.InterpreterPasteInput
2911
2949
2912 The following is a 'screenshot' of how things work when this extension
2950 The following is a 'screenshot' of how things work when this extension
2913 is on, copying an example from the standard tutorial::
2951 is on, copying an example from the standard tutorial::
2914
2952
2915 IPython profile: tutorial
2953 IPython profile: tutorial
2916
2954
2917 *** Pasting of code with ">>>" or "..." has been enabled.
2955 *** Pasting of code with ">>>" or "..." has been enabled.
2918
2956
2919 In [1]: >>> def fib2(n): # return Fibonacci series up to n
2957 In [1]: >>> def fib2(n): # return Fibonacci series up to n
2920 ...: ... """Return a list containing the Fibonacci series up to
2958 ...: ... """Return a list containing the Fibonacci series up to
2921 n."""
2959 n."""
2922 ...: ... result = []
2960 ...: ... result = []
2923 ...: ... a, b = 0, 1
2961 ...: ... a, b = 0, 1
2924 ...: ... while b < n:
2962 ...: ... while b < n:
2925 ...: ... result.append(b) # see below
2963 ...: ... result.append(b) # see below
2926 ...: ... a, b = b, a+b
2964 ...: ... a, b = b, a+b
2927 ...: ... return result
2965 ...: ... return result
2928 ...:
2966 ...:
2929
2967
2930 In [2]: fib2(10)
2968 In [2]: fib2(10)
2931 Out[2]: [1, 1, 2, 3, 5, 8]
2969 Out[2]: [1, 1, 2, 3, 5, 8]
2932
2970
2933 Note that as currently written, this extension does not recognize
2971 Note that as currently written, this extension does not recognize
2934 IPython's prompts for pasting. Those are more complicated, since the
2972 IPython's prompts for pasting. Those are more complicated, since the
2935 user can change them very easily, they involve numbers and can vary in
2973 user can change them very easily, they involve numbers and can vary in
2936 length. One could however extract all the relevant information from the
2974 length. One could however extract all the relevant information from the
2937 IPython instance and build an appropriate regular expression. This is
2975 IPython instance and build an appropriate regular expression. This is
2938 left as an exercise for the reader.
2976 left as an exercise for the reader.
2939
2977
2940
2978
2941 Input of physical quantities with units
2979 Input of physical quantities with units
2942 ---------------------------------------
2980 ---------------------------------------
2943
2981
2944 The module PhysicalQInput allows a simplified form of input for physical
2982 The module PhysicalQInput allows a simplified form of input for physical
2945 quantities with units. This file is meant to be used in conjunction with
2983 quantities with units. This file is meant to be used in conjunction with
2946 the PhysicalQInteractive module (in the same directory) and
2984 the PhysicalQInteractive module (in the same directory) and
2947 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
2985 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
2948 (http://dirac.cnrs-orleans.fr/ScientificPython/).
2986 (http://dirac.cnrs-orleans.fr/ScientificPython/).
2949
2987
2950 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
2988 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
2951 but these must be declared as instances of a class. For example, to
2989 but these must be declared as instances of a class. For example, to
2952 define v as a velocity of 3 m/s, normally you would write::
2990 define v as a velocity of 3 m/s, normally you would write::
2953
2991
2954 In [1]: v = PhysicalQuantity(3,'m/s')
2992 In [1]: v = PhysicalQuantity(3,'m/s')
2955
2993
2956 Using the PhysicalQ_Input extension this can be input instead as:
2994 Using the PhysicalQ_Input extension this can be input instead as:
2957 In [1]: v = 3 m/s
2995 In [1]: v = 3 m/s
2958 which is much more convenient for interactive use (even though it is
2996 which is much more convenient for interactive use (even though it is
2959 blatantly invalid Python syntax).
2997 blatantly invalid Python syntax).
2960
2998
2961 The physics profile supplied with IPython (enabled via 'ipython -p
2999 The physics profile supplied with IPython (enabled via 'ipython -p
2962 physics') uses these extensions, which you can also activate with:
3000 physics') uses these extensions, which you can also activate with:
2963
3001
2964 from math import * # math MUST be imported BEFORE PhysicalQInteractive
3002 from math import * # math MUST be imported BEFORE PhysicalQInteractive
2965 from IPython.Extensions.PhysicalQInteractive import *
3003 from IPython.Extensions.PhysicalQInteractive import *
2966 import IPython.Extensions.PhysicalQInput
3004 import IPython.Extensions.PhysicalQInput
2967
3005
2968
3006
2969 Threading support
3007 Threading support
2970 =================
3008 =================
2971
3009
2972 WARNING: The threading support is still somewhat experimental, and it
3010 WARNING: The threading support is still somewhat experimental, and it
2973 has only seen reasonable testing under Linux. Threaded code is
3011 has only seen reasonable testing under Linux. Threaded code is
2974 particularly tricky to debug, and it tends to show extremely
3012 particularly tricky to debug, and it tends to show extremely
2975 platform-dependent behavior. Since I only have access to Linux machines,
3013 platform-dependent behavior. Since I only have access to Linux machines,
2976 I will have to rely on user's experiences and assistance for this area
3014 I will have to rely on user's experiences and assistance for this area
2977 of IPython to improve under other platforms.
3015 of IPython to improve under other platforms.
2978
3016
2979 IPython, via the -gthread , -qthread, -q4thread and -wthread options
3017 IPython, via the -gthread , -qthread, -q4thread and -wthread options
2980 (described in Sec. `Threading options`_), can run in
3018 (described in Sec. `Threading options`_), can run in
2981 multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications
3019 multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications
2982 respectively. These GUI toolkits need to control the python main loop of
3020 respectively. These GUI toolkits need to control the python main loop of
2983 execution, so under a normal Python interpreter, starting a pyGTK, Qt3,
3021 execution, so under a normal Python interpreter, starting a pyGTK, Qt3,
2984 Qt4 or WXPython application will immediately freeze the shell.
3022 Qt4 or WXPython application will immediately freeze the shell.
2985
3023
2986 IPython, with one of these options (you can only use one at a time),
3024 IPython, with one of these options (you can only use one at a time),
2987 separates the graphical loop and IPython's code execution run into
3025 separates the graphical loop and IPython's code execution run into
2988 different threads. This allows you to test interactively (with %run, for
3026 different threads. This allows you to test interactively (with %run, for
2989 example) your GUI code without blocking.
3027 example) your GUI code without blocking.
2990
3028
2991 A nice mini-tutorial on using IPython along with the Qt Designer
3029 A nice mini-tutorial on using IPython along with the Qt Designer
2992 application is available at the SciPy wiki:
3030 application is available at the SciPy wiki:
2993 http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer.
3031 http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer.
2994
3032
2995
3033
2996 Tk issues
3034 Tk issues
2997 ---------
3035 ---------
2998
3036
2999 As indicated in Sec. `Threading options`_, a special -tk option is
3037 As indicated in Sec. `Threading options`_, a special -tk option is
3000 provided to try and allow Tk graphical applications to coexist
3038 provided to try and allow Tk graphical applications to coexist
3001 interactively with WX, Qt or GTK ones. Whether this works at all,
3039 interactively with WX, Qt or GTK ones. Whether this works at all,
3002 however, is very platform and configuration dependent. Please
3040 however, is very platform and configuration dependent. Please
3003 experiment with simple test cases before committing to using this
3041 experiment with simple test cases before committing to using this
3004 combination of Tk and GTK/Qt/WX threading in a production environment.
3042 combination of Tk and GTK/Qt/WX threading in a production environment.
3005
3043
3006
3044
3007 I/O pitfalls
3045 I/O pitfalls
3008 ------------
3046 ------------
3009
3047
3010 Be mindful that the Python interpreter switches between threads every
3048 Be mindful that the Python interpreter switches between threads every
3011 $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This
3049 $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This
3012 value can be read by using the sys.getcheckinterval() function, and it
3050 value can be read by using the sys.getcheckinterval() function, and it
3013 can be reset via sys.setcheckinterval(N). This switching of threads can
3051 can be reset via sys.setcheckinterval(N). This switching of threads can
3014 cause subtly confusing effects if one of your threads is doing file I/O.
3052 cause subtly confusing effects if one of your threads is doing file I/O.
3015 In text mode, most systems only flush file buffers when they encounter a
3053 In text mode, most systems only flush file buffers when they encounter a
3016 '\n'. An instruction as simple as::
3054 '\n'. An instruction as simple as::
3017
3055
3018 print >> filehandle, ''hello world''
3056 print >> filehandle, ''hello world''
3019
3057
3020 actually consists of several bytecodes, so it is possible that the
3058 actually consists of several bytecodes, so it is possible that the
3021 newline does not reach your file before the next thread switch.
3059 newline does not reach your file before the next thread switch.
3022 Similarly, if you are writing to a file in binary mode, the file won't
3060 Similarly, if you are writing to a file in binary mode, the file won't
3023 be flushed until the buffer fills, and your other thread may see
3061 be flushed until the buffer fills, and your other thread may see
3024 apparently truncated files.
3062 apparently truncated files.
3025
3063
3026 For this reason, if you are using IPython's thread support and have (for
3064 For this reason, if you are using IPython's thread support and have (for
3027 example) a GUI application which will read data generated by files
3065 example) a GUI application which will read data generated by files
3028 written to from the IPython thread, the safest approach is to open all
3066 written to from the IPython thread, the safest approach is to open all
3029 of your files in unbuffered mode (the third argument to the file/open
3067 of your files in unbuffered mode (the third argument to the file/open
3030 function is the buffering value)::
3068 function is the buffering value)::
3031
3069
3032 filehandle = open(filename,mode,0)
3070 filehandle = open(filename,mode,0)
3033
3071
3034 This is obviously a brute force way of avoiding race conditions with the
3072 This is obviously a brute force way of avoiding race conditions with the
3035 file buffering. If you want to do it cleanly, and you have a resource
3073 file buffering. If you want to do it cleanly, and you have a resource
3036 which is being shared by the interactive IPython loop and your GUI
3074 which is being shared by the interactive IPython loop and your GUI
3037 thread, you should really handle it with thread locking and
3075 thread, you should really handle it with thread locking and
3038 syncrhonization properties. The Python documentation discusses these.
3076 syncrhonization properties. The Python documentation discusses these.
3039
3077
3040 .. _interactive_demos:
3078 .. _interactive_demos:
3041
3079
3042 Interactive demos with IPython
3080 Interactive demos with IPython
3043 ==============================
3081 ==============================
3044
3082
3045 IPython ships with a basic system for running scripts interactively in
3083 IPython ships with a basic system for running scripts interactively in
3046 sections, useful when presenting code to audiences. A few tags embedded
3084 sections, useful when presenting code to audiences. A few tags embedded
3047 in comments (so that the script remains valid Python code) divide a file
3085 in comments (so that the script remains valid Python code) divide a file
3048 into separate blocks, and the demo can be run one block at a time, with
3086 into separate blocks, and the demo can be run one block at a time, with
3049 IPython printing (with syntax highlighting) the block before executing
3087 IPython printing (with syntax highlighting) the block before executing
3050 it, and returning to the interactive prompt after each block. The
3088 it, and returning to the interactive prompt after each block. The
3051 interactive namespace is updated after each block is run with the
3089 interactive namespace is updated after each block is run with the
3052 contents of the demo's namespace.
3090 contents of the demo's namespace.
3053
3091
3054 This allows you to show a piece of code, run it and then execute
3092 This allows you to show a piece of code, run it and then execute
3055 interactively commands based on the variables just created. Once you
3093 interactively commands based on the variables just created. Once you
3056 want to continue, you simply execute the next block of the demo. The
3094 want to continue, you simply execute the next block of the demo. The
3057 following listing shows the markup necessary for dividing a script into
3095 following listing shows the markup necessary for dividing a script into
3058 sections for execution as a demo::
3096 sections for execution as a demo::
3059
3097
3060
3098
3061 """A simple interactive demo to illustrate the use of IPython's Demo class.
3099 """A simple interactive demo to illustrate the use of IPython's Demo class.
3062
3100
3063 Any python script can be run as a demo, but that does little more than showing
3101 Any python script can be run as a demo, but that does little more than showing
3064 it on-screen, syntax-highlighted in one shot. If you add a little simple
3102 it on-screen, syntax-highlighted in one shot. If you add a little simple
3065 markup, you can stop at specified intervals and return to the ipython prompt,
3103 markup, you can stop at specified intervals and return to the ipython prompt,
3066 resuming execution later.
3104 resuming execution later.
3067 """
3105 """
3068
3106
3069 print 'Hello, welcome to an interactive IPython demo.'
3107 print 'Hello, welcome to an interactive IPython demo.'
3070 print 'Executing this block should require confirmation before proceeding,'
3108 print 'Executing this block should require confirmation before proceeding,'
3071 print 'unless auto_all has been set to true in the demo object'
3109 print 'unless auto_all has been set to true in the demo object'
3072
3110
3073 # The mark below defines a block boundary, which is a point where IPython will
3111 # The mark below defines a block boundary, which is a point where IPython will
3074 # stop execution and return to the interactive prompt.
3112 # stop execution and return to the interactive prompt.
3075 # Note that in actual interactive execution,
3113 # Note that in actual interactive execution,
3076 # <demo> --- stop ---
3114 # <demo> --- stop ---
3077
3115
3078 x = 1
3116 x = 1
3079 y = 2
3117 y = 2
3080
3118
3081 # <demo> --- stop ---
3119 # <demo> --- stop ---
3082
3120
3083 # the mark below makes this block as silent
3121 # the mark below makes this block as silent
3084 # <demo> silent
3122 # <demo> silent
3085
3123
3086 print 'This is a silent block, which gets executed but not printed.'
3124 print 'This is a silent block, which gets executed but not printed.'
3087
3125
3088 # <demo> --- stop ---
3126 # <demo> --- stop ---
3089 # <demo> auto
3127 # <demo> auto
3090 print 'This is an automatic block.'
3128 print 'This is an automatic block.'
3091 print 'It is executed without asking for confirmation, but printed.'
3129 print 'It is executed without asking for confirmation, but printed.'
3092 z = x+y
3130 z = x+y
3093
3131
3094 print 'z=',x
3132 print 'z=',x
3095
3133
3096 # <demo> --- stop ---
3134 # <demo> --- stop ---
3097 # This is just another normal block.
3135 # This is just another normal block.
3098 print 'z is now:', z
3136 print 'z is now:', z
3099
3137
3100 print 'bye!'
3138 print 'bye!'
3101
3139
3102 In order to run a file as a demo, you must first make a Demo object out
3140 In order to run a file as a demo, you must first make a Demo object out
3103 of it. If the file is named myscript.py, the following code will make a
3141 of it. If the file is named myscript.py, the following code will make a
3104 demo::
3142 demo::
3105
3143
3106 from IPython.demo import Demo
3144 from IPython.demo import Demo
3107
3145
3108 mydemo = Demo('myscript.py')
3146 mydemo = Demo('myscript.py')
3109
3147
3110 This creates the mydemo object, whose blocks you run one at a time by
3148 This creates the mydemo object, whose blocks you run one at a time by
3111 simply calling the object with no arguments. If you have autocall active
3149 simply calling the object with no arguments. If you have autocall active
3112 in IPython (the default), all you need to do is type::
3150 in IPython (the default), all you need to do is type::
3113
3151
3114 mydemo
3152 mydemo
3115
3153
3116 and IPython will call it, executing each block. Demo objects can be
3154 and IPython will call it, executing each block. Demo objects can be
3117 restarted, you can move forward or back skipping blocks, re-execute the
3155 restarted, you can move forward or back skipping blocks, re-execute the
3118 last block, etc. Simply use the Tab key on a demo object to see its
3156 last block, etc. Simply use the Tab key on a demo object to see its
3119 methods, and call '?' on them to see their docstrings for more usage
3157 methods, and call '?' on them to see their docstrings for more usage
3120 details. In addition, the demo module itself contains a comprehensive
3158 details. In addition, the demo module itself contains a comprehensive
3121 docstring, which you can access via::
3159 docstring, which you can access via::
3122
3160
3123 from IPython import demo
3161 from IPython import demo
3124
3162
3125 demo?
3163 demo?
3126
3164
3127 Limitations: It is important to note that these demos are limited to
3165 Limitations: It is important to note that these demos are limited to
3128 fairly simple uses. In particular, you can not put division marks in
3166 fairly simple uses. In particular, you can not put division marks in
3129 indented code (loops, if statements, function definitions, etc.)
3167 indented code (loops, if statements, function definitions, etc.)
3130 Supporting something like this would basically require tracking the
3168 Supporting something like this would basically require tracking the
3131 internal execution state of the Python interpreter, so only top-level
3169 internal execution state of the Python interpreter, so only top-level
3132 divisions are allowed. If you want to be able to open an IPython
3170 divisions are allowed. If you want to be able to open an IPython
3133 instance at an arbitrary point in a program, you can use IPython's
3171 instance at an arbitrary point in a program, you can use IPython's
3134 embedding facilities, described in detail in Sec. 9
3172 embedding facilities, described in detail in Sec. 9
3135
3173
3136
3174
3137 .. _Matplotlib support:
3175 .. _Matplotlib support:
3138
3176
3139 Plotting with matplotlib
3177 Plotting with matplotlib
3140 ========================
3178 ========================
3141
3179
3142 The matplotlib library (http://matplotlib.sourceforge.net
3180 The matplotlib library (http://matplotlib.sourceforge.net
3143 http://matplotlib.sourceforge.net) provides high quality 2D plotting for
3181 http://matplotlib.sourceforge.net) provides high quality 2D plotting for
3144 Python. Matplotlib can produce plots on screen using a variety of GUI
3182 Python. Matplotlib can produce plots on screen using a variety of GUI
3145 toolkits, including Tk, GTK and WXPython. It also provides a number of
3183 toolkits, including Tk, GTK and WXPython. It also provides a number of
3146 commands useful for scientific computing, all with a syntax compatible
3184 commands useful for scientific computing, all with a syntax compatible
3147 with that of the popular Matlab program.
3185 with that of the popular Matlab program.
3148
3186
3149 IPython accepts the special option -pylab (see :ref:`here
3187 IPython accepts the special option -pylab (see :ref:`here
3150 <command_line_options>`). This configures it to support matplotlib, honoring
3188 <command_line_options>`). This configures it to support matplotlib, honoring
3151 the settings in the .matplotlibrc file. IPython will detect the user's choice
3189 the settings in the .matplotlibrc file. IPython will detect the user's choice
3152 of matplotlib GUI backend, and automatically select the proper threading model
3190 of matplotlib GUI backend, and automatically select the proper threading model
3153 to prevent blocking. It also sets matplotlib in interactive mode and modifies
3191 to prevent blocking. It also sets matplotlib in interactive mode and modifies
3154 %run slightly, so that any matplotlib-based script can be executed using %run
3192 %run slightly, so that any matplotlib-based script can be executed using %run
3155 and the final show() command does not block the interactive shell.
3193 and the final show() command does not block the interactive shell.
3156
3194
3157 The -pylab option must be given first in order for IPython to configure its
3195 The -pylab option must be given first in order for IPython to configure its
3158 threading mode. However, you can still issue other options afterwards. This
3196 threading mode. However, you can still issue other options afterwards. This
3159 allows you to have a matplotlib-based environment customized with additional
3197 allows you to have a matplotlib-based environment customized with additional
3160 modules using the standard IPython profile mechanism (see :ref:`here
3198 modules using the standard IPython profile mechanism (see :ref:`here
3161 <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in
3199 <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in
3162 ipythonrc-myprofile after configuring matplotlib.
3200 ipythonrc-myprofile after configuring matplotlib.
General Comments 0
You need to be logged in to leave comments. Login now